babylon.max.js 4.0 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449554505545155452554535545455455554565545755458554595546055461554625546355464554655546655467554685546955470554715547255473554745547555476554775547855479554805548155482554835548455485554865548755488554895549055491554925549355494554955549655497554985549955500555015550255503555045550555506555075550855509555105551155512555135551455515555165551755518555195552055521555225552355524555255552655527555285552955530555315553255533555345553555536555375553855539555405554155542555435554455545555465554755548555495555055551555525555355554555555555655557555585555955560555615556255563555645556555566555675556855569555705557155572555735557455575555765557755578555795558055581555825558355584555855558655587555885558955590555915559255593555945559555596555975559855599556005560155602556035560455605556065560755608556095561055611556125561355614556155561655617556185561955620556215562255623556245562555626556275562855629556305563155632556335563455635556365563755638556395564055641556425564355644556455564655647556485564955650556515565255653556545565555656556575565855659556605566155662556635566455665556665566755668556695567055671556725567355674556755567655677556785567955680556815568255683556845568555686556875568855689556905569155692556935569455695556965569755698556995570055701557025570355704557055570655707557085570955710557115571255713557145571555716557175571855719557205572155722557235572455725557265572755728557295573055731557325573355734557355573655737557385573955740557415574255743557445574555746557475574855749557505575155752557535575455755557565575755758557595576055761557625576355764557655576655767557685576955770557715577255773557745577555776557775577855779557805578155782557835578455785557865578755788557895579055791557925579355794557955579655797557985579955800558015580255803558045580555806558075580855809558105581155812558135581455815558165581755818558195582055821558225582355824558255582655827558285582955830558315583255833558345583555836558375583855839558405584155842558435584455845558465584755848558495585055851558525585355854558555585655857558585585955860558615586255863558645586555866558675586855869558705587155872558735587455875558765587755878558795588055881558825588355884558855588655887558885588955890558915589255893558945589555896558975589855899559005590155902559035590455905559065590755908559095591055911559125591355914559155591655917559185591955920559215592255923559245592555926559275592855929559305593155932559335593455935559365593755938559395594055941559425594355944559455594655947559485594955950559515595255953559545595555956559575595855959559605596155962559635596455965559665596755968559695597055971559725597355974559755597655977559785597955980559815598255983559845598555986559875598855989559905599155992559935599455995559965599755998559995600056001560025600356004560055600656007560085600956010560115601256013560145601556016560175601856019560205602156022560235602456025560265602756028560295603056031560325603356034560355603656037560385603956040560415604256043560445604556046560475604856049560505605156052560535605456055560565605756058560595606056061560625606356064560655606656067560685606956070560715607256073560745607556076560775607856079560805608156082560835608456085560865608756088560895609056091560925609356094560955609656097560985609956100561015610256103561045610556106561075610856109561105611156112561135611456115561165611756118561195612056121561225612356124561255612656127561285612956130561315613256133561345613556136561375613856139561405614156142561435614456145561465614756148561495615056151561525615356154561555615656157561585615956160561615616256163561645616556166561675616856169561705617156172561735617456175561765617756178561795618056181561825618356184561855618656187561885618956190561915619256193561945619556196561975619856199562005620156202562035620456205562065620756208562095621056211562125621356214562155621656217562185621956220562215622256223562245622556226562275622856229562305623156232562335623456235562365623756238562395624056241562425624356244562455624656247562485624956250562515625256253562545625556256562575625856259562605626156262562635626456265562665626756268562695627056271562725627356274562755627656277562785627956280562815628256283562845628556286562875628856289562905629156292562935629456295562965629756298562995630056301563025630356304563055630656307563085630956310563115631256313563145631556316563175631856319563205632156322563235632456325563265632756328563295633056331563325633356334563355633656337563385633956340563415634256343563445634556346563475634856349563505635156352563535635456355563565635756358563595636056361563625636356364563655636656367563685636956370563715637256373563745637556376563775637856379563805638156382563835638456385563865638756388563895639056391563925639356394563955639656397563985639956400564015640256403564045640556406564075640856409564105641156412564135641456415564165641756418564195642056421564225642356424564255642656427564285642956430564315643256433564345643556436564375643856439564405644156442564435644456445564465644756448564495645056451564525645356454564555645656457564585645956460564615646256463564645646556466564675646856469564705647156472564735647456475564765647756478564795648056481564825648356484564855648656487564885648956490564915649256493564945649556496564975649856499565005650156502565035650456505565065650756508565095651056511565125651356514565155651656517565185651956520565215652256523565245652556526565275652856529565305653156532565335653456535565365653756538565395654056541565425654356544565455654656547565485654956550565515655256553565545655556556565575655856559565605656156562565635656456565565665656756568565695657056571565725657356574565755657656577565785657956580565815658256583565845658556586565875658856589565905659156592565935659456595565965659756598565995660056601566025660356604566055660656607566085660956610566115661256613566145661556616566175661856619566205662156622566235662456625566265662756628566295663056631566325663356634566355663656637566385663956640566415664256643566445664556646566475664856649566505665156652566535665456655566565665756658566595666056661566625666356664566655666656667566685666956670566715667256673566745667556676566775667856679566805668156682566835668456685566865668756688566895669056691566925669356694566955669656697566985669956700567015670256703567045670556706567075670856709567105671156712567135671456715567165671756718567195672056721567225672356724567255672656727567285672956730567315673256733567345673556736567375673856739567405674156742567435674456745567465674756748567495675056751567525675356754567555675656757567585675956760567615676256763567645676556766567675676856769567705677156772567735677456775567765677756778567795678056781567825678356784567855678656787567885678956790567915679256793567945679556796567975679856799568005680156802568035680456805568065680756808568095681056811568125681356814568155681656817568185681956820568215682256823568245682556826568275682856829568305683156832568335683456835568365683756838568395684056841568425684356844568455684656847568485684956850568515685256853568545685556856568575685856859568605686156862568635686456865568665686756868568695687056871568725687356874568755687656877568785687956880568815688256883568845688556886568875688856889568905689156892568935689456895568965689756898568995690056901569025690356904569055690656907569085690956910569115691256913569145691556916569175691856919569205692156922569235692456925569265692756928569295693056931569325693356934569355693656937569385693956940569415694256943569445694556946569475694856949569505695156952569535695456955569565695756958569595696056961569625696356964569655696656967569685696956970569715697256973569745697556976569775697856979569805698156982569835698456985569865698756988569895699056991569925699356994569955699656997569985699957000570015700257003570045700557006570075700857009570105701157012570135701457015570165701757018570195702057021570225702357024570255702657027570285702957030570315703257033570345703557036570375703857039570405704157042570435704457045570465704757048570495705057051570525705357054570555705657057570585705957060570615706257063570645706557066570675706857069570705707157072570735707457075570765707757078570795708057081570825708357084570855708657087570885708957090570915709257093570945709557096570975709857099571005710157102571035710457105571065710757108571095711057111571125711357114571155711657117571185711957120571215712257123571245712557126571275712857129571305713157132571335713457135571365713757138571395714057141571425714357144571455714657147571485714957150571515715257153571545715557156571575715857159571605716157162571635716457165571665716757168571695717057171571725717357174571755717657177571785717957180571815718257183571845718557186571875718857189571905719157192571935719457195571965719757198571995720057201572025720357204572055720657207572085720957210572115721257213572145721557216572175721857219572205722157222572235722457225572265722757228572295723057231572325723357234572355723657237572385723957240572415724257243572445724557246572475724857249572505725157252572535725457255572565725757258572595726057261572625726357264572655726657267572685726957270572715727257273572745727557276572775727857279572805728157282572835728457285572865728757288572895729057291572925729357294572955729657297572985729957300573015730257303573045730557306573075730857309573105731157312573135731457315573165731757318573195732057321573225732357324573255732657327573285732957330573315733257333573345733557336573375733857339573405734157342573435734457345573465734757348573495735057351573525735357354573555735657357573585735957360573615736257363573645736557366573675736857369573705737157372573735737457375573765737757378573795738057381573825738357384573855738657387573885738957390573915739257393573945739557396573975739857399574005740157402574035740457405574065740757408574095741057411574125741357414574155741657417574185741957420574215742257423574245742557426574275742857429574305743157432574335743457435574365743757438574395744057441574425744357444574455744657447574485744957450574515745257453574545745557456574575745857459574605746157462574635746457465574665746757468574695747057471574725747357474574755747657477574785747957480574815748257483574845748557486574875748857489574905749157492574935749457495574965749757498574995750057501575025750357504575055750657507575085750957510575115751257513575145751557516575175751857519575205752157522575235752457525575265752757528575295753057531575325753357534575355753657537575385753957540575415754257543575445754557546575475754857549575505755157552575535755457555575565755757558575595756057561575625756357564575655756657567575685756957570575715757257573575745757557576575775757857579575805758157582575835758457585575865758757588575895759057591575925759357594575955759657597575985759957600576015760257603576045760557606576075760857609576105761157612576135761457615576165761757618576195762057621576225762357624576255762657627576285762957630576315763257633576345763557636576375763857639576405764157642576435764457645576465764757648576495765057651576525765357654576555765657657576585765957660576615766257663576645766557666576675766857669576705767157672576735767457675576765767757678576795768057681576825768357684576855768657687576885768957690576915769257693576945769557696576975769857699577005770157702577035770457705577065770757708577095771057711577125771357714577155771657717577185771957720577215772257723577245772557726577275772857729577305773157732577335773457735577365773757738577395774057741577425774357744577455774657747577485774957750577515775257753577545775557756577575775857759577605776157762577635776457765577665776757768577695777057771577725777357774577755777657777577785777957780577815778257783577845778557786577875778857789577905779157792577935779457795577965779757798577995780057801578025780357804578055780657807578085780957810578115781257813578145781557816578175781857819578205782157822578235782457825578265782757828578295783057831578325783357834578355783657837578385783957840578415784257843578445784557846578475784857849578505785157852578535785457855578565785757858578595786057861578625786357864578655786657867578685786957870578715787257873578745787557876578775787857879578805788157882578835788457885578865788757888578895789057891578925789357894578955789657897578985789957900579015790257903579045790557906579075790857909579105791157912579135791457915579165791757918579195792057921579225792357924579255792657927579285792957930579315793257933579345793557936579375793857939579405794157942579435794457945579465794757948579495795057951579525795357954579555795657957579585795957960579615796257963579645796557966579675796857969579705797157972579735797457975579765797757978579795798057981579825798357984579855798657987579885798957990579915799257993579945799557996579975799857999580005800158002580035800458005580065800758008580095801058011580125801358014580155801658017580185801958020580215802258023580245802558026580275802858029580305803158032580335803458035580365803758038580395804058041580425804358044580455804658047580485804958050580515805258053580545805558056580575805858059580605806158062580635806458065580665806758068580695807058071580725807358074580755807658077580785807958080580815808258083580845808558086580875808858089580905809158092580935809458095580965809758098580995810058101581025810358104581055810658107581085810958110581115811258113581145811558116581175811858119581205812158122581235812458125581265812758128581295813058131581325813358134581355813658137581385813958140581415814258143581445814558146581475814858149581505815158152581535815458155581565815758158581595816058161581625816358164581655816658167581685816958170581715817258173581745817558176581775817858179581805818158182581835818458185581865818758188581895819058191581925819358194581955819658197581985819958200582015820258203582045820558206582075820858209582105821158212582135821458215582165821758218582195822058221582225822358224582255822658227582285822958230582315823258233582345823558236582375823858239582405824158242582435824458245582465824758248582495825058251582525825358254582555825658257582585825958260582615826258263582645826558266582675826858269582705827158272582735827458275582765827758278582795828058281582825828358284582855828658287582885828958290582915829258293582945829558296582975829858299583005830158302583035830458305583065830758308583095831058311583125831358314583155831658317583185831958320583215832258323583245832558326583275832858329583305833158332583335833458335583365833758338583395834058341583425834358344583455834658347583485834958350583515835258353583545835558356583575835858359583605836158362583635836458365583665836758368583695837058371583725837358374583755837658377583785837958380583815838258383583845838558386583875838858389583905839158392583935839458395583965839758398583995840058401584025840358404584055840658407584085840958410584115841258413584145841558416584175841858419584205842158422584235842458425584265842758428584295843058431584325843358434584355843658437584385843958440584415844258443584445844558446584475844858449584505845158452584535845458455584565845758458584595846058461584625846358464584655846658467584685846958470584715847258473584745847558476584775847858479584805848158482584835848458485584865848758488584895849058491584925849358494584955849658497584985849958500585015850258503585045850558506585075850858509585105851158512585135851458515585165851758518585195852058521585225852358524585255852658527585285852958530585315853258533585345853558536585375853858539585405854158542585435854458545585465854758548585495855058551585525855358554585555855658557585585855958560585615856258563585645856558566585675856858569585705857158572585735857458575585765857758578585795858058581585825858358584585855858658587585885858958590585915859258593585945859558596585975859858599586005860158602586035860458605586065860758608586095861058611586125861358614586155861658617586185861958620586215862258623586245862558626586275862858629586305863158632586335863458635586365863758638586395864058641586425864358644586455864658647586485864958650586515865258653586545865558656586575865858659586605866158662586635866458665586665866758668586695867058671586725867358674586755867658677586785867958680586815868258683586845868558686586875868858689586905869158692586935869458695586965869758698586995870058701587025870358704587055870658707587085870958710587115871258713587145871558716587175871858719587205872158722587235872458725587265872758728587295873058731587325873358734587355873658737587385873958740587415874258743587445874558746587475874858749587505875158752587535875458755587565875758758587595876058761587625876358764587655876658767587685876958770587715877258773587745877558776587775877858779587805878158782587835878458785587865878758788587895879058791587925879358794587955879658797587985879958800588015880258803588045880558806588075880858809588105881158812588135881458815588165881758818588195882058821588225882358824588255882658827588285882958830588315883258833588345883558836588375883858839588405884158842588435884458845588465884758848588495885058851588525885358854588555885658857588585885958860588615886258863588645886558866588675886858869588705887158872588735887458875588765887758878588795888058881588825888358884588855888658887588885888958890588915889258893588945889558896588975889858899589005890158902589035890458905589065890758908589095891058911589125891358914589155891658917589185891958920589215892258923589245892558926589275892858929589305893158932589335893458935589365893758938589395894058941589425894358944589455894658947589485894958950589515895258953589545895558956589575895858959589605896158962589635896458965589665896758968589695897058971589725897358974589755897658977589785897958980589815898258983589845898558986589875898858989589905899158992589935899458995589965899758998589995900059001590025900359004590055900659007590085900959010590115901259013590145901559016590175901859019590205902159022590235902459025590265902759028590295903059031590325903359034590355903659037590385903959040590415904259043590445904559046590475904859049590505905159052590535905459055590565905759058590595906059061590625906359064590655906659067590685906959070590715907259073590745907559076590775907859079590805908159082590835908459085590865908759088590895909059091590925909359094590955909659097590985909959100591015910259103591045910559106591075910859109591105911159112591135911459115591165911759118591195912059121591225912359124591255912659127591285912959130591315913259133591345913559136591375913859139591405914159142591435914459145591465914759148591495915059151591525915359154591555915659157591585915959160591615916259163591645916559166591675916859169591705917159172591735917459175591765917759178591795918059181591825918359184591855918659187591885918959190591915919259193591945919559196591975919859199592005920159202592035920459205592065920759208592095921059211592125921359214592155921659217592185921959220592215922259223592245922559226592275922859229592305923159232592335923459235592365923759238592395924059241592425924359244592455924659247592485924959250592515925259253592545925559256592575925859259592605926159262592635926459265592665926759268592695927059271592725927359274592755927659277592785927959280592815928259283592845928559286592875928859289592905929159292592935929459295592965929759298592995930059301593025930359304593055930659307593085930959310593115931259313593145931559316593175931859319593205932159322593235932459325593265932759328593295933059331593325933359334593355933659337593385933959340593415934259343593445934559346593475934859349593505935159352593535935459355593565935759358593595936059361593625936359364593655936659367593685936959370593715937259373593745937559376593775937859379593805938159382593835938459385593865938759388593895939059391593925939359394593955939659397593985939959400594015940259403594045940559406594075940859409594105941159412594135941459415594165941759418594195942059421594225942359424594255942659427594285942959430594315943259433594345943559436594375943859439594405944159442594435944459445594465944759448594495945059451594525945359454594555945659457594585945959460594615946259463594645946559466594675946859469594705947159472594735947459475594765947759478594795948059481594825948359484594855948659487594885948959490594915949259493594945949559496594975949859499595005950159502595035950459505595065950759508595095951059511595125951359514595155951659517595185951959520595215952259523595245952559526595275952859529595305953159532595335953459535595365953759538595395954059541595425954359544595455954659547595485954959550595515955259553595545955559556595575955859559595605956159562595635956459565595665956759568595695957059571595725957359574595755957659577595785957959580595815958259583595845958559586595875958859589595905959159592595935959459595595965959759598595995960059601596025960359604596055960659607596085960959610596115961259613596145961559616596175961859619596205962159622596235962459625596265962759628596295963059631596325963359634596355963659637596385963959640596415964259643596445964559646596475964859649596505965159652596535965459655596565965759658596595966059661596625966359664596655966659667596685966959670596715967259673596745967559676596775967859679596805968159682596835968459685596865968759688596895969059691596925969359694596955969659697596985969959700597015970259703597045970559706597075970859709597105971159712597135971459715597165971759718597195972059721597225972359724597255972659727597285972959730597315973259733597345973559736597375973859739597405974159742597435974459745597465974759748597495975059751597525975359754597555975659757597585975959760597615976259763597645976559766597675976859769597705977159772597735977459775597765977759778597795978059781597825978359784597855978659787597885978959790597915979259793597945979559796597975979859799598005980159802598035980459805598065980759808598095981059811598125981359814598155981659817598185981959820598215982259823598245982559826598275982859829598305983159832598335983459835598365983759838598395984059841598425984359844598455984659847598485984959850598515985259853598545985559856598575985859859598605986159862598635986459865598665986759868598695987059871598725987359874598755987659877598785987959880598815988259883598845988559886598875988859889598905989159892598935989459895598965989759898598995990059901599025990359904599055990659907599085990959910599115991259913599145991559916599175991859919599205992159922599235992459925599265992759928599295993059931599325993359934599355993659937599385993959940599415994259943599445994559946599475994859949599505995159952599535995459955599565995759958599595996059961599625996359964599655996659967599685996959970599715997259973599745997559976599775997859979599805998159982599835998459985599865998759988599895999059991599925999359994599955999659997599985999960000600016000260003600046000560006600076000860009600106001160012600136001460015600166001760018600196002060021600226002360024600256002660027600286002960030600316003260033600346003560036600376003860039600406004160042600436004460045600466004760048600496005060051600526005360054600556005660057600586005960060600616006260063600646006560066600676006860069600706007160072600736007460075600766007760078600796008060081600826008360084600856008660087600886008960090600916009260093600946009560096600976009860099601006010160102601036010460105601066010760108601096011060111601126011360114601156011660117601186011960120601216012260123601246012560126601276012860129601306013160132601336013460135601366013760138601396014060141601426014360144601456014660147601486014960150601516015260153601546015560156601576015860159601606016160162601636016460165601666016760168601696017060171601726017360174601756017660177601786017960180601816018260183601846018560186601876018860189601906019160192601936019460195601966019760198601996020060201602026020360204602056020660207602086020960210602116021260213602146021560216602176021860219602206022160222602236022460225602266022760228602296023060231602326023360234602356023660237602386023960240602416024260243602446024560246602476024860249602506025160252602536025460255602566025760258602596026060261602626026360264602656026660267602686026960270602716027260273602746027560276602776027860279602806028160282602836028460285602866028760288602896029060291602926029360294602956029660297602986029960300603016030260303603046030560306603076030860309603106031160312603136031460315603166031760318603196032060321603226032360324603256032660327603286032960330603316033260333603346033560336603376033860339603406034160342603436034460345603466034760348603496035060351603526035360354603556035660357603586035960360603616036260363603646036560366603676036860369603706037160372603736037460375603766037760378603796038060381603826038360384603856038660387603886038960390603916039260393603946039560396603976039860399604006040160402604036040460405604066040760408604096041060411604126041360414604156041660417604186041960420604216042260423604246042560426604276042860429604306043160432604336043460435604366043760438604396044060441604426044360444604456044660447604486044960450604516045260453604546045560456604576045860459604606046160462604636046460465604666046760468604696047060471604726047360474604756047660477604786047960480604816048260483604846048560486604876048860489604906049160492604936049460495604966049760498604996050060501605026050360504605056050660507605086050960510605116051260513605146051560516605176051860519605206052160522605236052460525605266052760528605296053060531605326053360534605356053660537605386053960540605416054260543605446054560546605476054860549605506055160552605536055460555605566055760558605596056060561605626056360564605656056660567605686056960570605716057260573605746057560576605776057860579605806058160582605836058460585605866058760588605896059060591605926059360594605956059660597605986059960600606016060260603606046060560606606076060860609606106061160612606136061460615606166061760618606196062060621606226062360624606256062660627606286062960630606316063260633606346063560636606376063860639606406064160642606436064460645606466064760648606496065060651606526065360654606556065660657606586065960660606616066260663606646066560666606676066860669606706067160672606736067460675606766067760678606796068060681606826068360684606856068660687606886068960690606916069260693606946069560696606976069860699607006070160702607036070460705607066070760708607096071060711607126071360714607156071660717607186071960720607216072260723607246072560726607276072860729607306073160732607336073460735607366073760738607396074060741607426074360744607456074660747607486074960750607516075260753607546075560756607576075860759607606076160762607636076460765607666076760768607696077060771607726077360774607756077660777607786077960780607816078260783607846078560786607876078860789607906079160792607936079460795607966079760798607996080060801608026080360804608056080660807608086080960810608116081260813608146081560816608176081860819608206082160822608236082460825608266082760828608296083060831608326083360834608356083660837608386083960840608416084260843608446084560846608476084860849608506085160852608536085460855608566085760858608596086060861608626086360864608656086660867608686086960870608716087260873608746087560876608776087860879608806088160882608836088460885608866088760888608896089060891608926089360894608956089660897608986089960900609016090260903609046090560906609076090860909609106091160912609136091460915609166091760918609196092060921609226092360924609256092660927609286092960930609316093260933609346093560936609376093860939609406094160942609436094460945609466094760948609496095060951609526095360954609556095660957609586095960960609616096260963609646096560966609676096860969609706097160972609736097460975609766097760978609796098060981609826098360984609856098660987609886098960990609916099260993609946099560996609976099860999610006100161002610036100461005610066100761008610096101061011610126101361014610156101661017610186101961020610216102261023610246102561026610276102861029610306103161032610336103461035610366103761038610396104061041610426104361044610456104661047610486104961050610516105261053610546105561056610576105861059610606106161062610636106461065610666106761068610696107061071610726107361074610756107661077610786107961080610816108261083610846108561086610876108861089610906109161092610936109461095610966109761098610996110061101611026110361104611056110661107611086110961110611116111261113611146111561116611176111861119611206112161122611236112461125611266112761128611296113061131611326113361134611356113661137611386113961140611416114261143611446114561146611476114861149611506115161152611536115461155611566115761158611596116061161611626116361164611656116661167611686116961170611716117261173611746117561176611776117861179611806118161182611836118461185611866118761188611896119061191611926119361194611956119661197611986119961200612016120261203612046120561206612076120861209612106121161212612136121461215612166121761218612196122061221612226122361224612256122661227612286122961230612316123261233612346123561236612376123861239612406124161242612436124461245612466124761248612496125061251612526125361254612556125661257612586125961260612616126261263612646126561266612676126861269612706127161272612736127461275612766127761278612796128061281612826128361284612856128661287612886128961290612916129261293612946129561296612976129861299613006130161302613036130461305613066130761308613096131061311613126131361314613156131661317613186131961320613216132261323613246132561326613276132861329613306133161332613336133461335613366133761338613396134061341613426134361344613456134661347613486134961350613516135261353613546135561356613576135861359613606136161362613636136461365613666136761368613696137061371613726137361374613756137661377613786137961380613816138261383613846138561386613876138861389613906139161392613936139461395613966139761398613996140061401614026140361404614056140661407614086140961410614116141261413614146141561416614176141861419614206142161422614236142461425614266142761428614296143061431614326143361434614356143661437614386143961440614416144261443614446144561446614476144861449614506145161452614536145461455614566145761458614596146061461614626146361464614656146661467614686146961470614716147261473614746147561476614776147861479614806148161482614836148461485614866148761488614896149061491614926149361494614956149661497614986149961500615016150261503615046150561506615076150861509615106151161512615136151461515615166151761518615196152061521615226152361524615256152661527615286152961530615316153261533615346153561536615376153861539615406154161542615436154461545615466154761548615496155061551615526155361554615556155661557615586155961560615616156261563615646156561566615676156861569615706157161572615736157461575615766157761578615796158061581615826158361584615856158661587615886158961590615916159261593615946159561596615976159861599616006160161602616036160461605616066160761608616096161061611616126161361614616156161661617616186161961620616216162261623616246162561626616276162861629616306163161632616336163461635616366163761638616396164061641616426164361644616456164661647616486164961650616516165261653616546165561656616576165861659616606166161662616636166461665616666166761668616696167061671616726167361674616756167661677616786167961680616816168261683616846168561686616876168861689616906169161692616936169461695616966169761698616996170061701617026170361704617056170661707617086170961710617116171261713617146171561716617176171861719617206172161722617236172461725617266172761728617296173061731617326173361734617356173661737617386173961740617416174261743617446174561746617476174861749617506175161752617536175461755617566175761758617596176061761617626176361764617656176661767617686176961770617716177261773617746177561776617776177861779617806178161782617836178461785617866178761788617896179061791617926179361794617956179661797617986179961800618016180261803618046180561806618076180861809618106181161812618136181461815618166181761818618196182061821618226182361824618256182661827618286182961830618316183261833618346183561836618376183861839618406184161842618436184461845618466184761848618496185061851618526185361854618556185661857618586185961860618616186261863618646186561866618676186861869618706187161872618736187461875618766187761878618796188061881618826188361884618856188661887618886188961890618916189261893618946189561896618976189861899619006190161902619036190461905619066190761908619096191061911619126191361914619156191661917619186191961920619216192261923619246192561926619276192861929619306193161932619336193461935619366193761938619396194061941619426194361944619456194661947619486194961950619516195261953619546195561956619576195861959619606196161962619636196461965619666196761968619696197061971619726197361974619756197661977619786197961980619816198261983619846198561986619876198861989619906199161992619936199461995619966199761998619996200062001620026200362004620056200662007620086200962010620116201262013620146201562016620176201862019620206202162022620236202462025620266202762028620296203062031620326203362034620356203662037620386203962040620416204262043620446204562046620476204862049620506205162052620536205462055620566205762058620596206062061620626206362064620656206662067620686206962070620716207262073620746207562076620776207862079620806208162082620836208462085620866208762088620896209062091620926209362094620956209662097620986209962100621016210262103621046210562106621076210862109621106211162112621136211462115621166211762118621196212062121621226212362124621256212662127621286212962130621316213262133621346213562136621376213862139621406214162142621436214462145621466214762148621496215062151621526215362154621556215662157621586215962160621616216262163621646216562166621676216862169621706217162172621736217462175621766217762178621796218062181621826218362184621856218662187621886218962190621916219262193621946219562196621976219862199622006220162202622036220462205622066220762208622096221062211622126221362214622156221662217622186221962220622216222262223622246222562226622276222862229622306223162232622336223462235622366223762238622396224062241622426224362244622456224662247622486224962250622516225262253622546225562256622576225862259622606226162262622636226462265622666226762268622696227062271622726227362274622756227662277622786227962280622816228262283622846228562286622876228862289622906229162292622936229462295622966229762298622996230062301623026230362304623056230662307623086230962310623116231262313623146231562316623176231862319623206232162322623236232462325623266232762328623296233062331623326233362334623356233662337623386233962340623416234262343623446234562346623476234862349623506235162352623536235462355623566235762358623596236062361623626236362364623656236662367623686236962370623716237262373623746237562376623776237862379623806238162382623836238462385623866238762388623896239062391623926239362394623956239662397623986239962400624016240262403624046240562406624076240862409624106241162412624136241462415624166241762418624196242062421624226242362424624256242662427624286242962430624316243262433624346243562436624376243862439624406244162442624436244462445624466244762448624496245062451624526245362454624556245662457624586245962460624616246262463624646246562466624676246862469624706247162472624736247462475624766247762478624796248062481624826248362484624856248662487624886248962490624916249262493624946249562496624976249862499625006250162502625036250462505625066250762508625096251062511625126251362514625156251662517625186251962520625216252262523625246252562526625276252862529625306253162532625336253462535625366253762538625396254062541625426254362544625456254662547625486254962550625516255262553625546255562556625576255862559625606256162562625636256462565625666256762568625696257062571625726257362574625756257662577625786257962580625816258262583625846258562586625876258862589625906259162592625936259462595625966259762598625996260062601626026260362604626056260662607626086260962610626116261262613626146261562616626176261862619626206262162622626236262462625626266262762628626296263062631626326263362634626356263662637626386263962640626416264262643626446264562646626476264862649626506265162652626536265462655626566265762658626596266062661626626266362664626656266662667626686266962670626716267262673626746267562676626776267862679626806268162682626836268462685626866268762688626896269062691626926269362694626956269662697626986269962700627016270262703627046270562706627076270862709627106271162712627136271462715627166271762718627196272062721627226272362724627256272662727627286272962730627316273262733627346273562736627376273862739627406274162742627436274462745627466274762748627496275062751627526275362754627556275662757627586275962760627616276262763627646276562766627676276862769627706277162772627736277462775627766277762778627796278062781627826278362784627856278662787627886278962790627916279262793627946279562796627976279862799628006280162802628036280462805628066280762808628096281062811628126281362814628156281662817628186281962820628216282262823628246282562826628276282862829628306283162832628336283462835628366283762838628396284062841628426284362844628456284662847628486284962850628516285262853628546285562856628576285862859628606286162862628636286462865628666286762868628696287062871628726287362874628756287662877628786287962880628816288262883628846288562886628876288862889628906289162892628936289462895628966289762898628996290062901629026290362904629056290662907629086290962910629116291262913629146291562916629176291862919629206292162922629236292462925629266292762928629296293062931629326293362934629356293662937629386293962940629416294262943629446294562946629476294862949629506295162952629536295462955629566295762958629596296062961629626296362964629656296662967629686296962970629716297262973629746297562976629776297862979629806298162982629836298462985629866298762988629896299062991629926299362994629956299662997629986299963000630016300263003630046300563006630076300863009630106301163012630136301463015630166301763018630196302063021630226302363024630256302663027630286302963030630316303263033630346303563036630376303863039630406304163042630436304463045630466304763048630496305063051630526305363054630556305663057630586305963060630616306263063630646306563066630676306863069630706307163072630736307463075630766307763078630796308063081630826308363084630856308663087630886308963090630916309263093630946309563096630976309863099631006310163102631036310463105631066310763108631096311063111631126311363114631156311663117631186311963120631216312263123631246312563126631276312863129631306313163132631336313463135631366313763138631396314063141631426314363144631456314663147631486314963150631516315263153631546315563156631576315863159631606316163162631636316463165631666316763168631696317063171631726317363174631756317663177631786317963180631816318263183631846318563186631876318863189631906319163192631936319463195631966319763198631996320063201632026320363204632056320663207632086320963210632116321263213632146321563216632176321863219632206322163222632236322463225632266322763228632296323063231632326323363234632356323663237632386323963240632416324263243632446324563246632476324863249632506325163252632536325463255632566325763258632596326063261632626326363264632656326663267632686326963270632716327263273632746327563276632776327863279632806328163282632836328463285632866328763288632896329063291632926329363294632956329663297632986329963300633016330263303633046330563306633076330863309633106331163312633136331463315633166331763318633196332063321633226332363324633256332663327633286332963330633316333263333633346333563336633376333863339633406334163342633436334463345633466334763348633496335063351633526335363354633556335663357633586335963360633616336263363633646336563366633676336863369633706337163372633736337463375633766337763378633796338063381633826338363384633856338663387633886338963390633916339263393633946339563396633976339863399634006340163402634036340463405634066340763408634096341063411634126341363414634156341663417634186341963420634216342263423634246342563426634276342863429634306343163432634336343463435634366343763438634396344063441634426344363444634456344663447634486344963450634516345263453634546345563456634576345863459634606346163462634636346463465634666346763468634696347063471634726347363474634756347663477634786347963480634816348263483634846348563486634876348863489634906349163492634936349463495634966349763498634996350063501635026350363504635056350663507635086350963510635116351263513635146351563516635176351863519635206352163522635236352463525635266352763528635296353063531635326353363534635356353663537635386353963540635416354263543635446354563546635476354863549635506355163552635536355463555635566355763558635596356063561635626356363564635656356663567635686356963570635716357263573635746357563576635776357863579635806358163582635836358463585635866358763588635896359063591635926359363594635956359663597635986359963600636016360263603636046360563606636076360863609636106361163612636136361463615636166361763618636196362063621636226362363624636256362663627636286362963630636316363263633636346363563636636376363863639636406364163642636436364463645636466364763648636496365063651636526365363654636556365663657636586365963660636616366263663636646366563666636676366863669636706367163672636736367463675636766367763678636796368063681636826368363684636856368663687636886368963690636916369263693636946369563696636976369863699637006370163702637036370463705637066370763708637096371063711637126371363714637156371663717637186371963720637216372263723637246372563726637276372863729637306373163732637336373463735637366373763738637396374063741637426374363744637456374663747637486374963750637516375263753637546375563756637576375863759637606376163762637636376463765637666376763768637696377063771637726377363774637756377663777637786377963780637816378263783637846378563786637876378863789637906379163792637936379463795637966379763798637996380063801638026380363804638056380663807638086380963810638116381263813638146381563816638176381863819638206382163822638236382463825638266382763828638296383063831638326383363834638356383663837638386383963840638416384263843638446384563846638476384863849638506385163852638536385463855638566385763858638596386063861638626386363864638656386663867638686386963870638716387263873638746387563876638776387863879638806388163882638836388463885638866388763888638896389063891638926389363894638956389663897638986389963900639016390263903639046390563906639076390863909639106391163912639136391463915639166391763918639196392063921639226392363924639256392663927639286392963930639316393263933639346393563936639376393863939639406394163942639436394463945639466394763948639496395063951639526395363954639556395663957639586395963960639616396263963639646396563966639676396863969639706397163972639736397463975639766397763978639796398063981639826398363984639856398663987639886398963990639916399263993639946399563996639976399863999640006400164002640036400464005640066400764008640096401064011640126401364014640156401664017640186401964020640216402264023640246402564026640276402864029640306403164032640336403464035640366403764038640396404064041640426404364044640456404664047640486404964050640516405264053640546405564056640576405864059640606406164062640636406464065640666406764068640696407064071640726407364074640756407664077640786407964080640816408264083640846408564086640876408864089640906409164092640936409464095640966409764098640996410064101641026410364104641056410664107641086410964110641116411264113641146411564116641176411864119641206412164122641236412464125641266412764128641296413064131641326413364134641356413664137641386413964140641416414264143641446414564146641476414864149641506415164152641536415464155641566415764158641596416064161641626416364164641656416664167641686416964170641716417264173641746417564176641776417864179641806418164182641836418464185641866418764188641896419064191641926419364194641956419664197641986419964200642016420264203642046420564206642076420864209642106421164212642136421464215642166421764218642196422064221642226422364224642256422664227642286422964230642316423264233642346423564236642376423864239642406424164242642436424464245642466424764248642496425064251642526425364254642556425664257642586425964260642616426264263642646426564266642676426864269642706427164272642736427464275642766427764278642796428064281642826428364284642856428664287642886428964290642916429264293642946429564296642976429864299643006430164302643036430464305643066430764308643096431064311643126431364314643156431664317643186431964320643216432264323643246432564326643276432864329643306433164332643336433464335643366433764338643396434064341643426434364344643456434664347643486434964350643516435264353643546435564356643576435864359643606436164362643636436464365643666436764368643696437064371643726437364374643756437664377643786437964380643816438264383643846438564386643876438864389643906439164392643936439464395643966439764398643996440064401644026440364404644056440664407644086440964410644116441264413644146441564416644176441864419644206442164422644236442464425644266442764428644296443064431644326443364434644356443664437644386443964440644416444264443644446444564446644476444864449644506445164452644536445464455644566445764458644596446064461644626446364464644656446664467644686446964470644716447264473644746447564476644776447864479644806448164482644836448464485644866448764488644896449064491644926449364494644956449664497644986449964500645016450264503645046450564506645076450864509645106451164512645136451464515645166451764518645196452064521645226452364524645256452664527645286452964530645316453264533645346453564536645376453864539645406454164542645436454464545645466454764548645496455064551645526455364554645556455664557645586455964560645616456264563645646456564566645676456864569645706457164572645736457464575645766457764578645796458064581645826458364584645856458664587645886458964590645916459264593645946459564596645976459864599646006460164602646036460464605646066460764608646096461064611646126461364614646156461664617646186461964620646216462264623646246462564626646276462864629646306463164632646336463464635646366463764638646396464064641646426464364644646456464664647646486464964650646516465264653646546465564656646576465864659646606466164662646636466464665646666466764668646696467064671646726467364674646756467664677646786467964680646816468264683646846468564686646876468864689646906469164692646936469464695646966469764698646996470064701647026470364704647056470664707647086470964710647116471264713647146471564716647176471864719647206472164722647236472464725647266472764728647296473064731647326473364734647356473664737647386473964740647416474264743647446474564746647476474864749647506475164752647536475464755647566475764758647596476064761647626476364764647656476664767647686476964770647716477264773647746477564776647776477864779647806478164782647836478464785647866478764788647896479064791647926479364794647956479664797647986479964800648016480264803648046480564806648076480864809648106481164812648136481464815648166481764818648196482064821648226482364824648256482664827648286482964830648316483264833648346483564836648376483864839648406484164842648436484464845648466484764848648496485064851648526485364854648556485664857648586485964860648616486264863648646486564866648676486864869648706487164872648736487464875648766487764878648796488064881648826488364884648856488664887648886488964890648916489264893648946489564896648976489864899649006490164902649036490464905649066490764908649096491064911649126491364914649156491664917649186491964920649216492264923649246492564926649276492864929649306493164932649336493464935649366493764938649396494064941649426494364944649456494664947649486494964950649516495264953649546495564956649576495864959649606496164962649636496464965649666496764968649696497064971649726497364974649756497664977649786497964980649816498264983649846498564986649876498864989649906499164992649936499464995649966499764998649996500065001650026500365004650056500665007650086500965010650116501265013650146501565016650176501865019650206502165022650236502465025650266502765028650296503065031650326503365034650356503665037650386503965040650416504265043650446504565046650476504865049650506505165052650536505465055650566505765058650596506065061650626506365064650656506665067650686506965070650716507265073650746507565076650776507865079650806508165082650836508465085650866508765088650896509065091650926509365094650956509665097650986509965100651016510265103651046510565106651076510865109651106511165112651136511465115651166511765118651196512065121651226512365124651256512665127651286512965130651316513265133651346513565136651376513865139651406514165142651436514465145651466514765148651496515065151651526515365154651556515665157651586515965160651616516265163651646516565166651676516865169651706517165172651736517465175651766517765178651796518065181651826518365184651856518665187651886518965190651916519265193651946519565196651976519865199652006520165202652036520465205652066520765208652096521065211652126521365214652156521665217652186521965220652216522265223652246522565226652276522865229652306523165232652336523465235652366523765238652396524065241652426524365244652456524665247652486524965250652516525265253652546525565256652576525865259652606526165262652636526465265652666526765268652696527065271652726527365274652756527665277652786527965280652816528265283652846528565286652876528865289652906529165292652936529465295652966529765298652996530065301653026530365304653056530665307653086530965310653116531265313653146531565316653176531865319653206532165322653236532465325653266532765328653296533065331653326533365334653356533665337653386533965340653416534265343653446534565346653476534865349653506535165352653536535465355653566535765358653596536065361653626536365364653656536665367653686536965370653716537265373653746537565376653776537865379653806538165382653836538465385653866538765388653896539065391653926539365394653956539665397653986539965400654016540265403654046540565406654076540865409654106541165412654136541465415654166541765418654196542065421654226542365424654256542665427654286542965430654316543265433654346543565436654376543865439654406544165442654436544465445654466544765448654496545065451654526545365454654556545665457654586545965460654616546265463654646546565466654676546865469654706547165472654736547465475654766547765478654796548065481654826548365484654856548665487654886548965490654916549265493654946549565496654976549865499655006550165502655036550465505655066550765508655096551065511655126551365514655156551665517655186551965520655216552265523655246552565526655276552865529655306553165532655336553465535655366553765538655396554065541655426554365544655456554665547655486554965550655516555265553655546555565556655576555865559655606556165562655636556465565655666556765568655696557065571655726557365574655756557665577655786557965580655816558265583655846558565586655876558865589655906559165592655936559465595655966559765598655996560065601656026560365604656056560665607656086560965610656116561265613656146561565616656176561865619656206562165622656236562465625656266562765628656296563065631656326563365634656356563665637656386563965640656416564265643656446564565646656476564865649656506565165652656536565465655656566565765658656596566065661656626566365664656656566665667656686566965670656716567265673656746567565676656776567865679656806568165682656836568465685656866568765688656896569065691656926569365694656956569665697656986569965700657016570265703657046570565706657076570865709657106571165712657136571465715657166571765718657196572065721657226572365724657256572665727657286572965730657316573265733657346573565736657376573865739657406574165742657436574465745657466574765748657496575065751657526575365754657556575665757657586575965760657616576265763657646576565766657676576865769657706577165772657736577465775657766577765778657796578065781657826578365784657856578665787657886578965790657916579265793657946579565796657976579865799658006580165802658036580465805658066580765808658096581065811658126581365814658156581665817658186581965820658216582265823658246582565826658276582865829658306583165832658336583465835658366583765838658396584065841658426584365844658456584665847658486584965850658516585265853658546585565856658576585865859658606586165862658636586465865658666586765868658696587065871658726587365874658756587665877658786587965880658816588265883658846588565886658876588865889658906589165892658936589465895658966589765898658996590065901659026590365904659056590665907659086590965910659116591265913659146591565916659176591865919659206592165922659236592465925659266592765928659296593065931659326593365934659356593665937659386593965940659416594265943659446594565946659476594865949659506595165952659536595465955659566595765958659596596065961659626596365964659656596665967659686596965970659716597265973659746597565976659776597865979659806598165982659836598465985659866598765988659896599065991659926599365994659956599665997659986599966000660016600266003660046600566006660076600866009660106601166012660136601466015660166601766018660196602066021660226602366024660256602666027660286602966030660316603266033660346603566036660376603866039660406604166042660436604466045660466604766048660496605066051660526605366054660556605666057660586605966060660616606266063660646606566066660676606866069660706607166072660736607466075660766607766078660796608066081660826608366084660856608666087660886608966090660916609266093660946609566096660976609866099661006610166102661036610466105661066610766108661096611066111661126611366114661156611666117661186611966120661216612266123661246612566126661276612866129661306613166132661336613466135661366613766138661396614066141661426614366144661456614666147661486614966150661516615266153661546615566156661576615866159661606616166162661636616466165661666616766168661696617066171661726617366174661756617666177661786617966180661816618266183661846618566186661876618866189661906619166192661936619466195661966619766198661996620066201662026620366204662056620666207662086620966210662116621266213662146621566216662176621866219662206622166222662236622466225662266622766228662296623066231662326623366234662356623666237662386623966240662416624266243662446624566246662476624866249662506625166252662536625466255662566625766258662596626066261662626626366264662656626666267662686626966270662716627266273662746627566276662776627866279662806628166282662836628466285662866628766288662896629066291662926629366294662956629666297662986629966300663016630266303663046630566306663076630866309663106631166312663136631466315663166631766318663196632066321663226632366324663256632666327663286632966330663316633266333663346633566336663376633866339663406634166342663436634466345663466634766348663496635066351663526635366354663556635666357663586635966360663616636266363663646636566366663676636866369663706637166372663736637466375663766637766378663796638066381663826638366384663856638666387663886638966390663916639266393663946639566396663976639866399664006640166402664036640466405664066640766408664096641066411664126641366414664156641666417664186641966420664216642266423664246642566426664276642866429664306643166432664336643466435664366643766438664396644066441664426644366444664456644666447664486644966450664516645266453664546645566456664576645866459664606646166462664636646466465664666646766468664696647066471664726647366474664756647666477664786647966480664816648266483664846648566486664876648866489664906649166492664936649466495664966649766498664996650066501665026650366504665056650666507665086650966510665116651266513665146651566516665176651866519665206652166522665236652466525665266652766528665296653066531665326653366534665356653666537665386653966540665416654266543665446654566546665476654866549665506655166552665536655466555665566655766558665596656066561665626656366564665656656666567665686656966570665716657266573665746657566576665776657866579665806658166582665836658466585665866658766588665896659066591665926659366594665956659666597665986659966600666016660266603666046660566606666076660866609666106661166612666136661466615666166661766618666196662066621666226662366624666256662666627666286662966630666316663266633666346663566636666376663866639666406664166642666436664466645666466664766648666496665066651666526665366654666556665666657666586665966660666616666266663666646666566666666676666866669666706667166672666736667466675666766667766678666796668066681666826668366684666856668666687666886668966690666916669266693666946669566696666976669866699667006670166702667036670466705667066670766708667096671066711667126671366714667156671666717667186671966720667216672266723667246672566726667276672866729667306673166732667336673466735667366673766738667396674066741667426674366744667456674666747667486674966750667516675266753667546675566756667576675866759667606676166762667636676466765667666676766768667696677066771667726677366774667756677666777667786677966780667816678266783667846678566786667876678866789667906679166792667936679466795667966679766798667996680066801668026680366804668056680666807668086680966810668116681266813668146681566816668176681866819668206682166822668236682466825668266682766828668296683066831668326683366834668356683666837668386683966840668416684266843668446684566846668476684866849668506685166852668536685466855668566685766858668596686066861668626686366864668656686666867668686686966870668716687266873668746687566876668776687866879668806688166882668836688466885668866688766888668896689066891668926689366894668956689666897668986689966900669016690266903669046690566906669076690866909669106691166912669136691466915669166691766918669196692066921669226692366924669256692666927669286692966930669316693266933669346693566936669376693866939669406694166942669436694466945669466694766948669496695066951669526695366954669556695666957669586695966960669616696266963669646696566966669676696866969669706697166972669736697466975669766697766978669796698066981669826698366984669856698666987669886698966990669916699266993669946699566996669976699866999670006700167002670036700467005670066700767008670096701067011670126701367014670156701667017670186701967020670216702267023670246702567026670276702867029670306703167032670336703467035670366703767038670396704067041670426704367044670456704667047670486704967050670516705267053670546705567056670576705867059670606706167062670636706467065670666706767068670696707067071670726707367074670756707667077670786707967080670816708267083670846708567086670876708867089670906709167092670936709467095670966709767098670996710067101671026710367104671056710667107671086710967110671116711267113671146711567116671176711867119671206712167122671236712467125671266712767128671296713067131671326713367134671356713667137671386713967140671416714267143671446714567146671476714867149671506715167152671536715467155671566715767158671596716067161671626716367164671656716667167671686716967170671716717267173671746717567176671776717867179671806718167182671836718467185671866718767188671896719067191671926719367194671956719667197671986719967200672016720267203672046720567206672076720867209672106721167212672136721467215672166721767218672196722067221672226722367224672256722667227672286722967230672316723267233672346723567236672376723867239672406724167242672436724467245672466724767248672496725067251672526725367254672556725667257672586725967260672616726267263672646726567266672676726867269672706727167272672736727467275672766727767278672796728067281672826728367284672856728667287672886728967290672916729267293672946729567296672976729867299673006730167302673036730467305673066730767308673096731067311673126731367314673156731667317673186731967320673216732267323673246732567326673276732867329673306733167332673336733467335673366733767338673396734067341673426734367344673456734667347673486734967350673516735267353673546735567356673576735867359673606736167362673636736467365673666736767368673696737067371673726737367374673756737667377673786737967380673816738267383673846738567386673876738867389673906739167392673936739467395673966739767398673996740067401674026740367404674056740667407674086740967410674116741267413674146741567416674176741867419674206742167422674236742467425674266742767428674296743067431674326743367434674356743667437674386743967440674416744267443674446744567446674476744867449674506745167452674536745467455674566745767458674596746067461674626746367464674656746667467674686746967470674716747267473674746747567476674776747867479674806748167482674836748467485674866748767488674896749067491674926749367494674956749667497674986749967500675016750267503675046750567506675076750867509675106751167512675136751467515675166751767518675196752067521675226752367524675256752667527675286752967530675316753267533675346753567536675376753867539675406754167542675436754467545675466754767548675496755067551675526755367554675556755667557675586755967560675616756267563675646756567566675676756867569675706757167572675736757467575675766757767578675796758067581675826758367584675856758667587675886758967590675916759267593675946759567596675976759867599676006760167602676036760467605676066760767608676096761067611676126761367614676156761667617676186761967620676216762267623676246762567626676276762867629676306763167632676336763467635676366763767638676396764067641676426764367644676456764667647676486764967650676516765267653676546765567656676576765867659676606766167662676636766467665676666766767668676696767067671676726767367674676756767667677676786767967680676816768267683676846768567686676876768867689676906769167692676936769467695676966769767698676996770067701677026770367704677056770667707677086770967710677116771267713677146771567716677176771867719677206772167722677236772467725677266772767728677296773067731677326773367734677356773667737677386773967740677416774267743677446774567746677476774867749677506775167752677536775467755677566775767758677596776067761677626776367764677656776667767677686776967770677716777267773677746777567776677776777867779677806778167782677836778467785677866778767788677896779067791677926779367794677956779667797677986779967800678016780267803678046780567806678076780867809678106781167812678136781467815678166781767818678196782067821678226782367824678256782667827678286782967830678316783267833678346783567836678376783867839678406784167842678436784467845678466784767848678496785067851678526785367854678556785667857678586785967860678616786267863678646786567866678676786867869678706787167872678736787467875678766787767878678796788067881678826788367884678856788667887678886788967890678916789267893678946789567896678976789867899679006790167902679036790467905679066790767908679096791067911679126791367914679156791667917679186791967920679216792267923679246792567926679276792867929679306793167932679336793467935679366793767938679396794067941679426794367944679456794667947679486794967950679516795267953679546795567956679576795867959679606796167962679636796467965679666796767968679696797067971679726797367974679756797667977679786797967980679816798267983679846798567986679876798867989679906799167992679936799467995679966799767998679996800068001680026800368004680056800668007680086800968010680116801268013680146801568016680176801868019680206802168022680236802468025680266802768028680296803068031680326803368034680356803668037680386803968040680416804268043680446804568046680476804868049680506805168052680536805468055680566805768058680596806068061680626806368064680656806668067680686806968070680716807268073680746807568076680776807868079680806808168082680836808468085680866808768088680896809068091680926809368094680956809668097680986809968100681016810268103681046810568106681076810868109681106811168112681136811468115681166811768118681196812068121681226812368124681256812668127681286812968130681316813268133681346813568136681376813868139681406814168142681436814468145681466814768148681496815068151681526815368154681556815668157681586815968160681616816268163681646816568166681676816868169681706817168172681736817468175681766817768178681796818068181681826818368184681856818668187681886818968190681916819268193681946819568196681976819868199682006820168202682036820468205682066820768208682096821068211682126821368214682156821668217682186821968220682216822268223682246822568226682276822868229682306823168232682336823468235682366823768238682396824068241682426824368244682456824668247682486824968250682516825268253682546825568256682576825868259682606826168262682636826468265682666826768268682696827068271682726827368274682756827668277682786827968280682816828268283682846828568286682876828868289682906829168292682936829468295682966829768298682996830068301683026830368304683056830668307683086830968310683116831268313683146831568316683176831868319683206832168322683236832468325683266832768328683296833068331683326833368334683356833668337683386833968340683416834268343683446834568346683476834868349683506835168352683536835468355683566835768358683596836068361683626836368364683656836668367683686836968370683716837268373683746837568376683776837868379683806838168382683836838468385683866838768388683896839068391683926839368394683956839668397683986839968400684016840268403684046840568406684076840868409684106841168412684136841468415684166841768418684196842068421684226842368424684256842668427684286842968430684316843268433684346843568436684376843868439684406844168442684436844468445684466844768448684496845068451684526845368454684556845668457684586845968460684616846268463684646846568466684676846868469684706847168472684736847468475684766847768478684796848068481684826848368484684856848668487684886848968490684916849268493684946849568496684976849868499685006850168502685036850468505685066850768508685096851068511685126851368514685156851668517685186851968520685216852268523685246852568526685276852868529685306853168532685336853468535685366853768538685396854068541685426854368544685456854668547685486854968550685516855268553685546855568556685576855868559685606856168562685636856468565685666856768568685696857068571685726857368574685756857668577685786857968580685816858268583685846858568586685876858868589685906859168592685936859468595685966859768598685996860068601686026860368604686056860668607686086860968610686116861268613686146861568616686176861868619686206862168622686236862468625686266862768628686296863068631686326863368634686356863668637686386863968640686416864268643686446864568646686476864868649686506865168652686536865468655686566865768658686596866068661686626866368664686656866668667686686866968670686716867268673686746867568676686776867868679686806868168682686836868468685686866868768688686896869068691686926869368694686956869668697686986869968700687016870268703687046870568706687076870868709687106871168712687136871468715687166871768718687196872068721687226872368724687256872668727687286872968730687316873268733687346873568736687376873868739687406874168742687436874468745687466874768748687496875068751687526875368754687556875668757687586875968760687616876268763687646876568766687676876868769687706877168772687736877468775687766877768778687796878068781687826878368784687856878668787687886878968790687916879268793687946879568796687976879868799688006880168802688036880468805688066880768808688096881068811688126881368814688156881668817688186881968820688216882268823688246882568826688276882868829688306883168832688336883468835688366883768838688396884068841688426884368844688456884668847688486884968850688516885268853688546885568856688576885868859688606886168862688636886468865688666886768868688696887068871688726887368874688756887668877688786887968880688816888268883688846888568886688876888868889688906889168892688936889468895688966889768898688996890068901689026890368904689056890668907689086890968910689116891268913689146891568916689176891868919689206892168922689236892468925689266892768928689296893068931689326893368934689356893668937689386893968940689416894268943689446894568946689476894868949689506895168952689536895468955689566895768958689596896068961689626896368964689656896668967689686896968970689716897268973689746897568976689776897868979689806898168982689836898468985689866898768988689896899068991689926899368994689956899668997689986899969000690016900269003690046900569006690076900869009690106901169012690136901469015690166901769018690196902069021690226902369024690256902669027690286902969030690316903269033690346903569036690376903869039690406904169042690436904469045690466904769048690496905069051690526905369054690556905669057690586905969060690616906269063690646906569066690676906869069690706907169072690736907469075690766907769078690796908069081690826908369084690856908669087690886908969090690916909269093690946909569096690976909869099691006910169102691036910469105691066910769108691096911069111691126911369114691156911669117691186911969120691216912269123691246912569126691276912869129691306913169132691336913469135691366913769138691396914069141691426914369144691456914669147691486914969150691516915269153691546915569156691576915869159691606916169162691636916469165691666916769168691696917069171691726917369174691756917669177691786917969180691816918269183691846918569186691876918869189691906919169192691936919469195691966919769198691996920069201692026920369204692056920669207692086920969210692116921269213692146921569216692176921869219692206922169222692236922469225692266922769228692296923069231692326923369234692356923669237692386923969240692416924269243692446924569246692476924869249692506925169252692536925469255692566925769258692596926069261692626926369264692656926669267692686926969270692716927269273692746927569276692776927869279692806928169282692836928469285692866928769288692896929069291692926929369294692956929669297692986929969300693016930269303693046930569306693076930869309693106931169312693136931469315693166931769318693196932069321693226932369324693256932669327693286932969330693316933269333693346933569336693376933869339693406934169342693436934469345693466934769348693496935069351693526935369354693556935669357693586935969360693616936269363693646936569366693676936869369693706937169372693736937469375693766937769378693796938069381693826938369384693856938669387693886938969390693916939269393693946939569396693976939869399694006940169402694036940469405694066940769408694096941069411694126941369414694156941669417694186941969420694216942269423694246942569426694276942869429694306943169432694336943469435694366943769438694396944069441694426944369444694456944669447694486944969450694516945269453694546945569456694576945869459694606946169462694636946469465694666946769468694696947069471694726947369474694756947669477694786947969480694816948269483694846948569486694876948869489694906949169492694936949469495694966949769498694996950069501695026950369504695056950669507695086950969510695116951269513695146951569516695176951869519695206952169522695236952469525695266952769528695296953069531695326953369534695356953669537695386953969540695416954269543695446954569546695476954869549695506955169552695536955469555695566955769558695596956069561695626956369564695656956669567695686956969570695716957269573695746957569576695776957869579695806958169582695836958469585695866958769588695896959069591695926959369594695956959669597695986959969600696016960269603696046960569606696076960869609696106961169612696136961469615696166961769618696196962069621696226962369624696256962669627696286962969630696316963269633696346963569636696376963869639696406964169642696436964469645696466964769648696496965069651696526965369654696556965669657696586965969660696616966269663696646966569666696676966869669696706967169672696736967469675696766967769678696796968069681696826968369684696856968669687696886968969690696916969269693696946969569696696976969869699697006970169702697036970469705697066970769708697096971069711697126971369714697156971669717697186971969720697216972269723697246972569726697276972869729697306973169732697336973469735697366973769738697396974069741697426974369744697456974669747697486974969750697516975269753697546975569756697576975869759697606976169762697636976469765697666976769768697696977069771697726977369774697756977669777697786977969780697816978269783697846978569786697876978869789697906979169792697936979469795697966979769798697996980069801698026980369804698056980669807698086980969810698116981269813698146981569816698176981869819698206982169822698236982469825698266982769828698296983069831698326983369834698356983669837698386983969840698416984269843698446984569846698476984869849698506985169852698536985469855698566985769858698596986069861698626986369864698656986669867698686986969870698716987269873698746987569876698776987869879698806988169882698836988469885698866988769888698896989069891698926989369894698956989669897698986989969900699016990269903699046990569906699076990869909699106991169912699136991469915699166991769918699196992069921699226992369924699256992669927699286992969930699316993269933699346993569936699376993869939699406994169942699436994469945699466994769948699496995069951699526995369954699556995669957699586995969960699616996269963699646996569966699676996869969699706997169972699736997469975699766997769978699796998069981699826998369984699856998669987699886998969990699916999269993699946999569996699976999869999700007000170002700037000470005700067000770008700097001070011700127001370014700157001670017700187001970020700217002270023700247002570026700277002870029700307003170032700337003470035700367003770038700397004070041700427004370044700457004670047700487004970050700517005270053700547005570056700577005870059700607006170062700637006470065700667006770068700697007070071700727007370074700757007670077700787007970080700817008270083700847008570086700877008870089700907009170092700937009470095700967009770098700997010070101701027010370104701057010670107701087010970110701117011270113701147011570116701177011870119701207012170122701237012470125701267012770128701297013070131701327013370134701357013670137701387013970140701417014270143701447014570146701477014870149701507015170152701537015470155701567015770158701597016070161701627016370164701657016670167701687016970170701717017270173701747017570176701777017870179701807018170182701837018470185701867018770188701897019070191701927019370194701957019670197701987019970200702017020270203702047020570206702077020870209702107021170212702137021470215702167021770218702197022070221702227022370224702257022670227702287022970230702317023270233702347023570236702377023870239702407024170242702437024470245702467024770248702497025070251702527025370254702557025670257702587025970260702617026270263702647026570266702677026870269702707027170272702737027470275702767027770278702797028070281702827028370284702857028670287702887028970290702917029270293702947029570296702977029870299703007030170302703037030470305703067030770308703097031070311703127031370314703157031670317703187031970320703217032270323703247032570326703277032870329703307033170332703337033470335703367033770338703397034070341703427034370344703457034670347703487034970350703517035270353703547035570356703577035870359703607036170362703637036470365703667036770368703697037070371703727037370374703757037670377703787037970380703817038270383703847038570386703877038870389703907039170392703937039470395703967039770398703997040070401704027040370404704057040670407704087040970410704117041270413704147041570416704177041870419704207042170422704237042470425704267042770428704297043070431704327043370434704357043670437704387043970440704417044270443704447044570446704477044870449704507045170452704537045470455704567045770458704597046070461704627046370464704657046670467704687046970470704717047270473704747047570476704777047870479704807048170482704837048470485704867048770488704897049070491704927049370494704957049670497704987049970500705017050270503705047050570506705077050870509705107051170512705137051470515705167051770518705197052070521705227052370524705257052670527705287052970530705317053270533705347053570536705377053870539705407054170542705437054470545705467054770548705497055070551705527055370554705557055670557705587055970560705617056270563705647056570566705677056870569705707057170572705737057470575705767057770578705797058070581705827058370584705857058670587705887058970590705917059270593705947059570596705977059870599706007060170602706037060470605706067060770608706097061070611706127061370614706157061670617706187061970620706217062270623706247062570626706277062870629706307063170632706337063470635706367063770638706397064070641706427064370644706457064670647706487064970650706517065270653706547065570656706577065870659706607066170662706637066470665706667066770668706697067070671706727067370674706757067670677706787067970680706817068270683706847068570686706877068870689706907069170692706937069470695706967069770698706997070070701707027070370704707057070670707707087070970710707117071270713707147071570716707177071870719707207072170722707237072470725707267072770728707297073070731707327073370734707357073670737707387073970740707417074270743707447074570746707477074870749707507075170752707537075470755707567075770758707597076070761707627076370764707657076670767707687076970770707717077270773707747077570776707777077870779707807078170782707837078470785707867078770788707897079070791707927079370794707957079670797707987079970800708017080270803708047080570806708077080870809708107081170812708137081470815708167081770818708197082070821708227082370824708257082670827708287082970830708317083270833708347083570836708377083870839708407084170842708437084470845708467084770848708497085070851708527085370854708557085670857708587085970860708617086270863708647086570866708677086870869708707087170872708737087470875708767087770878708797088070881708827088370884708857088670887708887088970890708917089270893708947089570896708977089870899709007090170902709037090470905709067090770908709097091070911709127091370914709157091670917709187091970920709217092270923709247092570926709277092870929709307093170932709337093470935709367093770938709397094070941709427094370944709457094670947709487094970950709517095270953709547095570956709577095870959709607096170962709637096470965709667096770968709697097070971709727097370974709757097670977709787097970980709817098270983709847098570986709877098870989709907099170992709937099470995709967099770998709997100071001710027100371004710057100671007710087100971010710117101271013710147101571016710177101871019710207102171022710237102471025710267102771028710297103071031710327103371034710357103671037710387103971040710417104271043710447104571046710477104871049710507105171052710537105471055710567105771058710597106071061710627106371064710657106671067710687106971070710717107271073710747107571076710777107871079710807108171082710837108471085710867108771088710897109071091710927109371094710957109671097710987109971100711017110271103711047110571106711077110871109711107111171112711137111471115711167111771118711197112071121711227112371124711257112671127711287112971130711317113271133711347113571136711377113871139711407114171142711437114471145711467114771148711497115071151711527115371154711557115671157711587115971160711617116271163711647116571166711677116871169711707117171172711737117471175711767117771178711797118071181711827118371184711857118671187711887118971190711917119271193711947119571196711977119871199712007120171202712037120471205712067120771208712097121071211712127121371214712157121671217712187121971220712217122271223712247122571226712277122871229712307123171232712337123471235712367123771238712397124071241712427124371244712457124671247712487124971250712517125271253712547125571256712577125871259712607126171262712637126471265712667126771268712697127071271712727127371274712757127671277712787127971280712817128271283712847128571286712877128871289712907129171292712937129471295712967129771298712997130071301713027130371304713057130671307713087130971310713117131271313713147131571316713177131871319713207132171322713237132471325713267132771328713297133071331713327133371334713357133671337713387133971340713417134271343713447134571346713477134871349713507135171352713537135471355713567135771358713597136071361713627136371364713657136671367713687136971370713717137271373713747137571376713777137871379713807138171382713837138471385713867138771388713897139071391713927139371394713957139671397713987139971400714017140271403714047140571406714077140871409714107141171412714137141471415714167141771418714197142071421714227142371424714257142671427714287142971430714317143271433714347143571436714377143871439714407144171442714437144471445714467144771448714497145071451714527145371454714557145671457714587145971460714617146271463714647146571466714677146871469714707147171472714737147471475714767147771478714797148071481714827148371484714857148671487714887148971490714917149271493714947149571496714977149871499715007150171502715037150471505715067150771508715097151071511715127151371514715157151671517715187151971520715217152271523715247152571526715277152871529715307153171532715337153471535715367153771538715397154071541715427154371544715457154671547715487154971550715517155271553715547155571556715577155871559715607156171562715637156471565715667156771568715697157071571715727157371574715757157671577715787157971580715817158271583715847158571586715877158871589715907159171592715937159471595715967159771598715997160071601716027160371604716057160671607716087160971610716117161271613716147161571616716177161871619716207162171622716237162471625716267162771628716297163071631716327163371634716357163671637716387163971640716417164271643716447164571646716477164871649716507165171652716537165471655716567165771658716597166071661716627166371664716657166671667716687166971670716717167271673716747167571676716777167871679716807168171682716837168471685716867168771688716897169071691716927169371694716957169671697716987169971700717017170271703717047170571706717077170871709717107171171712717137171471715717167171771718717197172071721717227172371724717257172671727717287172971730717317173271733717347173571736717377173871739717407174171742717437174471745717467174771748717497175071751717527175371754717557175671757717587175971760717617176271763717647176571766717677176871769717707177171772717737177471775717767177771778717797178071781717827178371784717857178671787717887178971790717917179271793717947179571796717977179871799718007180171802718037180471805718067180771808718097181071811718127181371814718157181671817718187181971820718217182271823718247182571826718277182871829718307183171832718337183471835718367183771838718397184071841718427184371844718457184671847718487184971850718517185271853718547185571856718577185871859718607186171862718637186471865718667186771868718697187071871718727187371874718757187671877718787187971880718817188271883718847188571886718877188871889718907189171892718937189471895718967189771898718997190071901719027190371904719057190671907719087190971910719117191271913719147191571916719177191871919719207192171922719237192471925719267192771928719297193071931719327193371934719357193671937719387193971940719417194271943719447194571946719477194871949719507195171952719537195471955719567195771958719597196071961719627196371964719657196671967719687196971970719717197271973719747197571976719777197871979719807198171982719837198471985719867198771988719897199071991719927199371994719957199671997719987199972000720017200272003720047200572006720077200872009720107201172012720137201472015720167201772018720197202072021720227202372024720257202672027720287202972030720317203272033720347203572036720377203872039720407204172042720437204472045720467204772048720497205072051720527205372054720557205672057720587205972060720617206272063720647206572066720677206872069720707207172072720737207472075720767207772078720797208072081720827208372084720857208672087720887208972090720917209272093720947209572096720977209872099721007210172102721037210472105721067210772108721097211072111721127211372114721157211672117721187211972120721217212272123721247212572126721277212872129721307213172132721337213472135721367213772138721397214072141721427214372144721457214672147721487214972150721517215272153721547215572156721577215872159721607216172162721637216472165721667216772168721697217072171721727217372174721757217672177721787217972180721817218272183721847218572186721877218872189721907219172192721937219472195721967219772198721997220072201722027220372204722057220672207722087220972210722117221272213722147221572216722177221872219722207222172222722237222472225722267222772228722297223072231722327223372234722357223672237722387223972240722417224272243722447224572246722477224872249722507225172252722537225472255722567225772258722597226072261722627226372264722657226672267722687226972270722717227272273722747227572276722777227872279722807228172282722837228472285722867228772288722897229072291722927229372294722957229672297722987229972300723017230272303723047230572306723077230872309723107231172312723137231472315723167231772318723197232072321723227232372324723257232672327723287232972330723317233272333723347233572336723377233872339723407234172342723437234472345723467234772348723497235072351723527235372354723557235672357723587235972360723617236272363723647236572366723677236872369723707237172372723737237472375723767237772378723797238072381723827238372384723857238672387723887238972390723917239272393723947239572396723977239872399724007240172402724037240472405724067240772408724097241072411724127241372414724157241672417724187241972420724217242272423724247242572426724277242872429724307243172432724337243472435724367243772438724397244072441724427244372444724457244672447724487244972450724517245272453724547245572456724577245872459724607246172462724637246472465724667246772468724697247072471724727247372474724757247672477724787247972480724817248272483724847248572486724877248872489724907249172492724937249472495724967249772498724997250072501725027250372504725057250672507725087250972510725117251272513725147251572516725177251872519725207252172522725237252472525725267252772528725297253072531725327253372534725357253672537725387253972540725417254272543725447254572546725477254872549725507255172552725537255472555725567255772558725597256072561725627256372564725657256672567725687256972570725717257272573725747257572576725777257872579725807258172582725837258472585725867258772588725897259072591725927259372594725957259672597725987259972600726017260272603726047260572606726077260872609726107261172612726137261472615726167261772618726197262072621726227262372624726257262672627726287262972630726317263272633726347263572636726377263872639726407264172642726437264472645726467264772648726497265072651726527265372654726557265672657726587265972660726617266272663726647266572666726677266872669726707267172672726737267472675726767267772678726797268072681726827268372684726857268672687726887268972690726917269272693726947269572696726977269872699727007270172702727037270472705727067270772708727097271072711727127271372714727157271672717727187271972720727217272272723727247272572726727277272872729727307273172732727337273472735727367273772738727397274072741727427274372744727457274672747727487274972750727517275272753727547275572756727577275872759727607276172762727637276472765727667276772768727697277072771727727277372774727757277672777727787277972780727817278272783727847278572786727877278872789727907279172792727937279472795727967279772798727997280072801728027280372804728057280672807728087280972810728117281272813728147281572816728177281872819728207282172822728237282472825728267282772828728297283072831728327283372834728357283672837728387283972840728417284272843728447284572846728477284872849728507285172852728537285472855728567285772858728597286072861728627286372864728657286672867728687286972870728717287272873728747287572876728777287872879728807288172882728837288472885728867288772888728897289072891728927289372894728957289672897728987289972900729017290272903729047290572906729077290872909729107291172912729137291472915729167291772918729197292072921729227292372924729257292672927729287292972930729317293272933729347293572936729377293872939729407294172942729437294472945729467294772948729497295072951729527295372954729557295672957729587295972960729617296272963729647296572966729677296872969729707297172972729737297472975729767297772978729797298072981729827298372984729857298672987729887298972990729917299272993729947299572996729977299872999730007300173002730037300473005730067300773008730097301073011730127301373014730157301673017730187301973020730217302273023730247302573026730277302873029730307303173032730337303473035730367303773038730397304073041730427304373044730457304673047730487304973050730517305273053730547305573056730577305873059730607306173062730637306473065730667306773068730697307073071730727307373074730757307673077730787307973080730817308273083730847308573086730877308873089730907309173092730937309473095730967309773098730997310073101731027310373104731057310673107731087310973110731117311273113731147311573116731177311873119731207312173122731237312473125731267312773128731297313073131731327313373134731357313673137731387313973140731417314273143731447314573146731477314873149731507315173152731537315473155731567315773158731597316073161731627316373164731657316673167731687316973170731717317273173731747317573176731777317873179731807318173182731837318473185731867318773188731897319073191731927319373194731957319673197731987319973200732017320273203732047320573206732077320873209732107321173212732137321473215732167321773218732197322073221732227322373224732257322673227732287322973230732317323273233732347323573236732377323873239732407324173242732437324473245732467324773248732497325073251732527325373254732557325673257732587325973260732617326273263732647326573266732677326873269732707327173272732737327473275732767327773278732797328073281732827328373284732857328673287732887328973290732917329273293732947329573296732977329873299733007330173302733037330473305733067330773308733097331073311733127331373314733157331673317733187331973320733217332273323733247332573326733277332873329733307333173332733337333473335733367333773338733397334073341733427334373344733457334673347733487334973350733517335273353733547335573356733577335873359733607336173362733637336473365733667336773368733697337073371733727337373374733757337673377733787337973380733817338273383733847338573386733877338873389733907339173392733937339473395733967339773398733997340073401734027340373404734057340673407734087340973410734117341273413734147341573416734177341873419734207342173422734237342473425734267342773428734297343073431734327343373434734357343673437734387343973440734417344273443734447344573446734477344873449734507345173452734537345473455734567345773458734597346073461734627346373464734657346673467734687346973470734717347273473734747347573476734777347873479734807348173482734837348473485734867348773488734897349073491734927349373494734957349673497734987349973500735017350273503735047350573506735077350873509735107351173512735137351473515735167351773518735197352073521735227352373524735257352673527735287352973530735317353273533735347353573536735377353873539735407354173542735437354473545735467354773548735497355073551735527355373554735557355673557735587355973560735617356273563735647356573566735677356873569735707357173572735737357473575735767357773578735797358073581735827358373584735857358673587735887358973590735917359273593735947359573596735977359873599736007360173602736037360473605736067360773608736097361073611736127361373614736157361673617736187361973620736217362273623736247362573626736277362873629736307363173632736337363473635736367363773638736397364073641736427364373644736457364673647736487364973650736517365273653736547365573656736577365873659736607366173662736637366473665736667366773668736697367073671736727367373674736757367673677736787367973680736817368273683736847368573686736877368873689736907369173692736937369473695736967369773698736997370073701737027370373704737057370673707737087370973710737117371273713737147371573716737177371873719737207372173722737237372473725737267372773728737297373073731737327373373734737357373673737737387373973740737417374273743737447374573746737477374873749737507375173752737537375473755737567375773758737597376073761737627376373764737657376673767737687376973770737717377273773737747377573776737777377873779737807378173782737837378473785737867378773788737897379073791737927379373794737957379673797737987379973800738017380273803738047380573806738077380873809738107381173812738137381473815738167381773818738197382073821738227382373824738257382673827738287382973830738317383273833738347383573836738377383873839738407384173842738437384473845738467384773848738497385073851738527385373854738557385673857738587385973860738617386273863738647386573866738677386873869738707387173872738737387473875738767387773878738797388073881738827388373884738857388673887738887388973890738917389273893738947389573896738977389873899739007390173902739037390473905739067390773908739097391073911739127391373914739157391673917739187391973920739217392273923739247392573926739277392873929739307393173932739337393473935739367393773938739397394073941739427394373944739457394673947739487394973950739517395273953739547395573956739577395873959739607396173962739637396473965739667396773968739697397073971739727397373974739757397673977739787397973980739817398273983739847398573986739877398873989739907399173992739937399473995739967399773998739997400074001740027400374004740057400674007740087400974010740117401274013740147401574016740177401874019740207402174022740237402474025740267402774028740297403074031740327403374034740357403674037740387403974040740417404274043740447404574046740477404874049740507405174052740537405474055740567405774058740597406074061740627406374064740657406674067740687406974070740717407274073740747407574076740777407874079740807408174082740837408474085740867408774088740897409074091740927409374094740957409674097740987409974100741017410274103741047410574106741077410874109741107411174112741137411474115741167411774118741197412074121741227412374124741257412674127741287412974130741317413274133741347413574136741377413874139741407414174142741437414474145741467414774148741497415074151741527415374154741557415674157741587415974160741617416274163741647416574166741677416874169741707417174172741737417474175741767417774178741797418074181741827418374184741857418674187741887418974190741917419274193741947419574196741977419874199742007420174202742037420474205742067420774208742097421074211742127421374214742157421674217742187421974220742217422274223742247422574226742277422874229742307423174232742337423474235742367423774238742397424074241742427424374244742457424674247742487424974250742517425274253742547425574256742577425874259742607426174262742637426474265742667426774268742697427074271742727427374274742757427674277742787427974280742817428274283742847428574286742877428874289742907429174292742937429474295742967429774298742997430074301743027430374304743057430674307743087430974310743117431274313743147431574316743177431874319743207432174322743237432474325743267432774328743297433074331743327433374334743357433674337743387433974340743417434274343743447434574346743477434874349743507435174352743537435474355743567435774358743597436074361743627436374364743657436674367743687436974370743717437274373743747437574376743777437874379743807438174382743837438474385743867438774388743897439074391743927439374394743957439674397743987439974400744017440274403744047440574406744077440874409744107441174412744137441474415744167441774418744197442074421744227442374424744257442674427744287442974430744317443274433744347443574436744377443874439744407444174442744437444474445744467444774448744497445074451744527445374454744557445674457744587445974460744617446274463744647446574466744677446874469744707447174472744737447474475744767447774478744797448074481744827448374484744857448674487744887448974490744917449274493744947449574496744977449874499745007450174502745037450474505745067450774508745097451074511745127451374514745157451674517745187451974520745217452274523745247452574526745277452874529745307453174532745337453474535745367453774538745397454074541745427454374544745457454674547745487454974550745517455274553745547455574556745577455874559745607456174562745637456474565745667456774568745697457074571745727457374574745757457674577745787457974580745817458274583745847458574586745877458874589745907459174592745937459474595745967459774598745997460074601746027460374604746057460674607746087460974610746117461274613746147461574616746177461874619746207462174622746237462474625746267462774628746297463074631746327463374634746357463674637746387463974640746417464274643746447464574646746477464874649746507465174652746537465474655746567465774658746597466074661746627466374664746657466674667746687466974670746717467274673746747467574676746777467874679746807468174682746837468474685746867468774688746897469074691746927469374694746957469674697746987469974700747017470274703747047470574706747077470874709747107471174712747137471474715747167471774718747197472074721747227472374724747257472674727747287472974730747317473274733747347473574736747377473874739747407474174742747437474474745747467474774748747497475074751747527475374754747557475674757747587475974760747617476274763747647476574766747677476874769747707477174772747737477474775747767477774778747797478074781747827478374784747857478674787747887478974790747917479274793747947479574796747977479874799748007480174802748037480474805748067480774808748097481074811748127481374814748157481674817748187481974820748217482274823748247482574826748277482874829748307483174832748337483474835748367483774838748397484074841748427484374844748457484674847748487484974850748517485274853748547485574856748577485874859748607486174862748637486474865748667486774868748697487074871748727487374874748757487674877748787487974880748817488274883748847488574886748877488874889748907489174892748937489474895748967489774898748997490074901749027490374904749057490674907749087490974910749117491274913749147491574916749177491874919749207492174922749237492474925749267492774928749297493074931749327493374934749357493674937749387493974940749417494274943749447494574946749477494874949749507495174952749537495474955749567495774958749597496074961749627496374964749657496674967749687496974970749717497274973749747497574976749777497874979749807498174982749837498474985749867498774988749897499074991749927499374994749957499674997749987499975000750017500275003750047500575006750077500875009750107501175012750137501475015750167501775018750197502075021750227502375024750257502675027750287502975030750317503275033750347503575036750377503875039750407504175042750437504475045750467504775048750497505075051750527505375054750557505675057750587505975060750617506275063750647506575066750677506875069750707507175072750737507475075750767507775078750797508075081750827508375084750857508675087750887508975090750917509275093750947509575096750977509875099751007510175102751037510475105751067510775108751097511075111751127511375114751157511675117751187511975120751217512275123751247512575126751277512875129751307513175132751337513475135751367513775138751397514075141751427514375144751457514675147751487514975150751517515275153751547515575156751577515875159751607516175162751637516475165751667516775168751697517075171751727517375174751757517675177751787517975180751817518275183751847518575186751877518875189751907519175192751937519475195751967519775198751997520075201752027520375204752057520675207752087520975210752117521275213752147521575216752177521875219752207522175222752237522475225752267522775228752297523075231752327523375234752357523675237752387523975240752417524275243752447524575246752477524875249752507525175252752537525475255752567525775258752597526075261752627526375264752657526675267752687526975270752717527275273752747527575276752777527875279752807528175282752837528475285752867528775288752897529075291752927529375294752957529675297752987529975300753017530275303753047530575306753077530875309753107531175312753137531475315753167531775318753197532075321753227532375324753257532675327753287532975330753317533275333753347533575336753377533875339753407534175342753437534475345753467534775348753497535075351753527535375354753557535675357753587535975360753617536275363753647536575366753677536875369753707537175372753737537475375753767537775378753797538075381753827538375384753857538675387753887538975390753917539275393753947539575396753977539875399754007540175402754037540475405754067540775408754097541075411754127541375414754157541675417754187541975420754217542275423754247542575426754277542875429754307543175432754337543475435754367543775438754397544075441754427544375444754457544675447754487544975450754517545275453754547545575456754577545875459754607546175462754637546475465754667546775468754697547075471754727547375474754757547675477754787547975480754817548275483754847548575486754877548875489754907549175492754937549475495754967549775498754997550075501755027550375504755057550675507755087550975510755117551275513755147551575516755177551875519755207552175522755237552475525755267552775528755297553075531755327553375534755357553675537755387553975540755417554275543755447554575546755477554875549755507555175552755537555475555755567555775558755597556075561755627556375564755657556675567755687556975570755717557275573755747557575576755777557875579755807558175582755837558475585755867558775588755897559075591755927559375594755957559675597755987559975600756017560275603756047560575606756077560875609756107561175612756137561475615756167561775618756197562075621756227562375624756257562675627756287562975630756317563275633756347563575636756377563875639756407564175642756437564475645756467564775648756497565075651756527565375654756557565675657756587565975660756617566275663756647566575666756677566875669756707567175672756737567475675756767567775678756797568075681756827568375684756857568675687756887568975690756917569275693756947569575696756977569875699757007570175702757037570475705757067570775708757097571075711757127571375714757157571675717757187571975720757217572275723757247572575726757277572875729757307573175732757337573475735757367573775738757397574075741757427574375744757457574675747757487574975750757517575275753757547575575756757577575875759757607576175762757637576475765757667576775768757697577075771757727577375774757757577675777757787577975780757817578275783757847578575786757877578875789757907579175792757937579475795757967579775798757997580075801758027580375804758057580675807758087580975810758117581275813758147581575816758177581875819758207582175822758237582475825758267582775828758297583075831758327583375834758357583675837758387583975840758417584275843758447584575846758477584875849758507585175852758537585475855758567585775858758597586075861758627586375864758657586675867758687586975870758717587275873758747587575876758777587875879758807588175882758837588475885758867588775888758897589075891758927589375894758957589675897758987589975900759017590275903759047590575906759077590875909759107591175912759137591475915759167591775918759197592075921759227592375924759257592675927759287592975930759317593275933759347593575936759377593875939759407594175942759437594475945759467594775948759497595075951759527595375954759557595675957759587595975960759617596275963759647596575966759677596875969759707597175972759737597475975759767597775978759797598075981759827598375984759857598675987759887598975990759917599275993759947599575996759977599875999760007600176002760037600476005760067600776008760097601076011760127601376014760157601676017760187601976020760217602276023760247602576026760277602876029760307603176032760337603476035760367603776038760397604076041760427604376044760457604676047760487604976050760517605276053760547605576056760577605876059760607606176062760637606476065760667606776068760697607076071760727607376074760757607676077760787607976080760817608276083760847608576086760877608876089760907609176092760937609476095760967609776098760997610076101761027610376104761057610676107761087610976110761117611276113761147611576116761177611876119761207612176122761237612476125761267612776128761297613076131761327613376134761357613676137761387613976140761417614276143761447614576146761477614876149761507615176152761537615476155761567615776158761597616076161761627616376164761657616676167761687616976170761717617276173761747617576176761777617876179761807618176182761837618476185761867618776188761897619076191761927619376194761957619676197761987619976200762017620276203762047620576206762077620876209762107621176212762137621476215762167621776218762197622076221762227622376224762257622676227762287622976230762317623276233762347623576236762377623876239762407624176242762437624476245762467624776248762497625076251762527625376254762557625676257762587625976260762617626276263762647626576266762677626876269762707627176272762737627476275762767627776278762797628076281762827628376284762857628676287762887628976290762917629276293762947629576296762977629876299763007630176302763037630476305763067630776308763097631076311763127631376314763157631676317763187631976320763217632276323763247632576326763277632876329763307633176332763337633476335763367633776338763397634076341763427634376344763457634676347763487634976350763517635276353763547635576356763577635876359763607636176362763637636476365763667636776368763697637076371763727637376374763757637676377763787637976380763817638276383763847638576386763877638876389763907639176392763937639476395763967639776398763997640076401764027640376404764057640676407764087640976410764117641276413764147641576416764177641876419764207642176422764237642476425764267642776428764297643076431764327643376434764357643676437764387643976440764417644276443764447644576446764477644876449764507645176452764537645476455764567645776458764597646076461764627646376464764657646676467764687646976470764717647276473764747647576476764777647876479764807648176482764837648476485764867648776488764897649076491764927649376494764957649676497764987649976500765017650276503765047650576506765077650876509765107651176512765137651476515765167651776518765197652076521765227652376524765257652676527765287652976530765317653276533765347653576536765377653876539765407654176542765437654476545765467654776548765497655076551765527655376554765557655676557765587655976560765617656276563765647656576566765677656876569765707657176572765737657476575765767657776578765797658076581765827658376584765857658676587765887658976590765917659276593765947659576596765977659876599766007660176602766037660476605766067660776608766097661076611766127661376614766157661676617766187661976620766217662276623766247662576626766277662876629766307663176632766337663476635766367663776638766397664076641766427664376644766457664676647766487664976650766517665276653766547665576656766577665876659766607666176662766637666476665766667666776668766697667076671766727667376674766757667676677766787667976680766817668276683766847668576686766877668876689766907669176692766937669476695766967669776698766997670076701767027670376704767057670676707767087670976710767117671276713767147671576716767177671876719767207672176722767237672476725767267672776728767297673076731767327673376734767357673676737767387673976740767417674276743767447674576746767477674876749767507675176752767537675476755767567675776758767597676076761767627676376764767657676676767767687676976770767717677276773767747677576776767777677876779767807678176782767837678476785767867678776788767897679076791767927679376794767957679676797767987679976800768017680276803768047680576806768077680876809768107681176812768137681476815768167681776818768197682076821768227682376824768257682676827768287682976830768317683276833768347683576836768377683876839768407684176842768437684476845768467684776848768497685076851768527685376854768557685676857768587685976860768617686276863768647686576866768677686876869768707687176872768737687476875768767687776878768797688076881768827688376884768857688676887768887688976890768917689276893768947689576896768977689876899769007690176902769037690476905769067690776908769097691076911769127691376914769157691676917769187691976920769217692276923769247692576926769277692876929769307693176932769337693476935769367693776938769397694076941769427694376944769457694676947769487694976950769517695276953769547695576956769577695876959769607696176962769637696476965769667696776968769697697076971769727697376974769757697676977769787697976980769817698276983769847698576986769877698876989769907699176992769937699476995769967699776998769997700077001770027700377004770057700677007770087700977010770117701277013770147701577016770177701877019770207702177022770237702477025770267702777028770297703077031770327703377034770357703677037770387703977040770417704277043770447704577046770477704877049770507705177052770537705477055770567705777058770597706077061770627706377064770657706677067770687706977070770717707277073770747707577076770777707877079770807708177082770837708477085770867708777088770897709077091770927709377094770957709677097770987709977100771017710277103771047710577106771077710877109771107711177112771137711477115771167711777118771197712077121771227712377124771257712677127771287712977130771317713277133771347713577136771377713877139771407714177142771437714477145771467714777148771497715077151771527715377154771557715677157771587715977160771617716277163771647716577166771677716877169771707717177172771737717477175771767717777178771797718077181771827718377184771857718677187771887718977190771917719277193771947719577196771977719877199772007720177202772037720477205772067720777208772097721077211772127721377214772157721677217772187721977220772217722277223772247722577226772277722877229772307723177232772337723477235772367723777238772397724077241772427724377244772457724677247772487724977250772517725277253772547725577256772577725877259772607726177262772637726477265772667726777268772697727077271772727727377274772757727677277772787727977280772817728277283772847728577286772877728877289772907729177292772937729477295772967729777298772997730077301773027730377304773057730677307773087730977310773117731277313773147731577316773177731877319773207732177322773237732477325773267732777328773297733077331773327733377334773357733677337773387733977340773417734277343773447734577346773477734877349773507735177352773537735477355773567735777358773597736077361773627736377364773657736677367773687736977370773717737277373773747737577376773777737877379773807738177382773837738477385773867738777388773897739077391773927739377394773957739677397773987739977400774017740277403774047740577406774077740877409774107741177412774137741477415774167741777418774197742077421774227742377424774257742677427774287742977430774317743277433774347743577436774377743877439774407744177442774437744477445774467744777448774497745077451774527745377454774557745677457774587745977460774617746277463774647746577466774677746877469774707747177472774737747477475774767747777478774797748077481774827748377484774857748677487774887748977490774917749277493774947749577496774977749877499775007750177502775037750477505775067750777508775097751077511775127751377514775157751677517775187751977520775217752277523775247752577526775277752877529775307753177532775337753477535775367753777538775397754077541775427754377544775457754677547775487754977550775517755277553775547755577556775577755877559775607756177562775637756477565775667756777568775697757077571775727757377574775757757677577775787757977580775817758277583775847758577586775877758877589775907759177592775937759477595775967759777598775997760077601776027760377604776057760677607776087760977610776117761277613776147761577616776177761877619776207762177622776237762477625776267762777628776297763077631776327763377634776357763677637776387763977640776417764277643776447764577646776477764877649776507765177652776537765477655776567765777658776597766077661776627766377664776657766677667776687766977670776717767277673776747767577676776777767877679776807768177682776837768477685776867768777688776897769077691776927769377694776957769677697776987769977700777017770277703777047770577706777077770877709777107771177712777137771477715777167771777718777197772077721777227772377724777257772677727777287772977730777317773277733777347773577736777377773877739777407774177742777437774477745777467774777748777497775077751777527775377754777557775677757777587775977760777617776277763777647776577766777677776877769777707777177772777737777477775777767777777778777797778077781777827778377784777857778677787777887778977790777917779277793777947779577796777977779877799778007780177802778037780477805778067780777808778097781077811778127781377814778157781677817778187781977820778217782277823778247782577826778277782877829778307783177832778337783477835778367783777838778397784077841778427784377844778457784677847778487784977850778517785277853778547785577856778577785877859778607786177862778637786477865778667786777868778697787077871778727787377874778757787677877778787787977880778817788277883778847788577886778877788877889778907789177892778937789477895778967789777898778997790077901779027790377904779057790677907779087790977910779117791277913779147791577916779177791877919779207792177922779237792477925779267792777928779297793077931779327793377934779357793677937779387793977940779417794277943779447794577946779477794877949779507795177952779537795477955779567795777958779597796077961779627796377964779657796677967779687796977970779717797277973779747797577976779777797877979779807798177982779837798477985779867798777988779897799077991779927799377994779957799677997779987799978000780017800278003780047800578006780077800878009780107801178012780137801478015780167801778018780197802078021780227802378024780257802678027780287802978030780317803278033780347803578036780377803878039780407804178042780437804478045780467804778048780497805078051780527805378054780557805678057780587805978060780617806278063780647806578066780677806878069780707807178072780737807478075780767807778078780797808078081780827808378084780857808678087780887808978090780917809278093780947809578096780977809878099781007810178102781037810478105781067810778108781097811078111781127811378114781157811678117781187811978120781217812278123781247812578126781277812878129781307813178132781337813478135781367813778138781397814078141781427814378144781457814678147781487814978150781517815278153781547815578156781577815878159781607816178162781637816478165781667816778168781697817078171781727817378174781757817678177781787817978180781817818278183781847818578186781877818878189781907819178192781937819478195781967819778198781997820078201782027820378204782057820678207782087820978210782117821278213782147821578216782177821878219782207822178222782237822478225782267822778228782297823078231782327823378234782357823678237782387823978240782417824278243782447824578246782477824878249782507825178252782537825478255782567825778258782597826078261782627826378264782657826678267782687826978270782717827278273782747827578276782777827878279782807828178282782837828478285782867828778288782897829078291782927829378294782957829678297782987829978300783017830278303783047830578306783077830878309783107831178312783137831478315783167831778318783197832078321783227832378324783257832678327783287832978330783317833278333783347833578336783377833878339783407834178342783437834478345783467834778348783497835078351783527835378354783557835678357783587835978360783617836278363783647836578366783677836878369783707837178372783737837478375783767837778378783797838078381783827838378384783857838678387783887838978390783917839278393783947839578396783977839878399784007840178402784037840478405784067840778408784097841078411784127841378414784157841678417784187841978420784217842278423784247842578426784277842878429784307843178432784337843478435784367843778438784397844078441784427844378444784457844678447784487844978450784517845278453784547845578456784577845878459784607846178462784637846478465784667846778468784697847078471784727847378474784757847678477784787847978480784817848278483784847848578486784877848878489784907849178492784937849478495784967849778498784997850078501785027850378504785057850678507785087850978510785117851278513785147851578516785177851878519785207852178522785237852478525785267852778528785297853078531785327853378534785357853678537785387853978540785417854278543785447854578546785477854878549785507855178552785537855478555785567855778558785597856078561785627856378564785657856678567785687856978570785717857278573785747857578576785777857878579785807858178582785837858478585785867858778588785897859078591785927859378594785957859678597785987859978600786017860278603786047860578606786077860878609786107861178612786137861478615786167861778618786197862078621786227862378624786257862678627786287862978630786317863278633786347863578636786377863878639786407864178642786437864478645786467864778648786497865078651786527865378654786557865678657786587865978660786617866278663786647866578666786677866878669786707867178672786737867478675786767867778678786797868078681786827868378684786857868678687786887868978690786917869278693786947869578696786977869878699787007870178702787037870478705787067870778708787097871078711787127871378714787157871678717787187871978720787217872278723787247872578726787277872878729787307873178732787337873478735787367873778738787397874078741787427874378744787457874678747787487874978750787517875278753787547875578756787577875878759787607876178762787637876478765787667876778768787697877078771787727877378774787757877678777787787877978780787817878278783787847878578786787877878878789787907879178792787937879478795787967879778798787997880078801788027880378804788057880678807788087880978810788117881278813788147881578816788177881878819788207882178822788237882478825788267882778828788297883078831788327883378834788357883678837788387883978840788417884278843788447884578846788477884878849788507885178852788537885478855788567885778858788597886078861788627886378864788657886678867788687886978870788717887278873788747887578876788777887878879788807888178882788837888478885788867888778888788897889078891788927889378894788957889678897788987889978900789017890278903789047890578906789077890878909789107891178912789137891478915789167891778918789197892078921789227892378924789257892678927789287892978930789317893278933789347893578936789377893878939789407894178942789437894478945789467894778948789497895078951789527895378954789557895678957789587895978960789617896278963789647896578966789677896878969789707897178972789737897478975789767897778978789797898078981789827898378984789857898678987789887898978990789917899278993789947899578996789977899878999790007900179002790037900479005790067900779008790097901079011790127901379014790157901679017790187901979020790217902279023790247902579026790277902879029790307903179032790337903479035790367903779038790397904079041790427904379044790457904679047790487904979050790517905279053790547905579056790577905879059790607906179062790637906479065790667906779068790697907079071790727907379074790757907679077790787907979080790817908279083790847908579086790877908879089790907909179092790937909479095790967909779098790997910079101791027910379104791057910679107791087910979110791117911279113791147911579116791177911879119791207912179122791237912479125791267912779128791297913079131791327913379134791357913679137791387913979140791417914279143791447914579146791477914879149791507915179152791537915479155791567915779158791597916079161791627916379164791657916679167791687916979170791717917279173791747917579176791777917879179791807918179182791837918479185791867918779188791897919079191791927919379194791957919679197791987919979200792017920279203792047920579206792077920879209792107921179212792137921479215792167921779218792197922079221792227922379224792257922679227792287922979230792317923279233792347923579236792377923879239792407924179242792437924479245792467924779248792497925079251792527925379254792557925679257792587925979260792617926279263792647926579266792677926879269792707927179272792737927479275792767927779278792797928079281792827928379284792857928679287792887928979290792917929279293792947929579296792977929879299793007930179302793037930479305793067930779308793097931079311793127931379314793157931679317793187931979320793217932279323793247932579326793277932879329793307933179332793337933479335793367933779338793397934079341793427934379344793457934679347793487934979350793517935279353793547935579356793577935879359793607936179362793637936479365793667936779368793697937079371793727937379374793757937679377793787937979380793817938279383793847938579386793877938879389793907939179392793937939479395793967939779398793997940079401794027940379404794057940679407794087940979410794117941279413794147941579416794177941879419794207942179422794237942479425794267942779428794297943079431794327943379434794357943679437794387943979440794417944279443794447944579446794477944879449794507945179452794537945479455794567945779458794597946079461794627946379464794657946679467794687946979470794717947279473794747947579476794777947879479794807948179482794837948479485794867948779488794897949079491794927949379494794957949679497794987949979500795017950279503795047950579506795077950879509795107951179512795137951479515795167951779518795197952079521795227952379524795257952679527795287952979530795317953279533795347953579536795377953879539795407954179542795437954479545795467954779548795497955079551795527955379554795557955679557795587955979560795617956279563795647956579566795677956879569795707957179572795737957479575795767957779578795797958079581795827958379584795857958679587795887958979590795917959279593795947959579596795977959879599796007960179602796037960479605796067960779608796097961079611796127961379614796157961679617796187961979620796217962279623796247962579626796277962879629796307963179632796337963479635796367963779638796397964079641796427964379644796457964679647796487964979650796517965279653796547965579656796577965879659796607966179662796637966479665796667966779668796697967079671796727967379674796757967679677796787967979680796817968279683796847968579686796877968879689796907969179692796937969479695796967969779698796997970079701797027970379704797057970679707797087970979710797117971279713797147971579716797177971879719797207972179722797237972479725797267972779728797297973079731797327973379734797357973679737797387973979740797417974279743797447974579746797477974879749797507975179752797537975479755797567975779758797597976079761797627976379764797657976679767797687976979770797717977279773797747977579776797777977879779797807978179782797837978479785797867978779788797897979079791797927979379794797957979679797797987979979800798017980279803798047980579806798077980879809798107981179812798137981479815798167981779818798197982079821798227982379824798257982679827798287982979830798317983279833798347983579836798377983879839798407984179842798437984479845798467984779848798497985079851798527985379854798557985679857798587985979860798617986279863798647986579866798677986879869798707987179872798737987479875798767987779878798797988079881798827988379884798857988679887798887988979890798917989279893798947989579896798977989879899799007990179902799037990479905799067990779908799097991079911799127991379914799157991679917799187991979920799217992279923799247992579926799277992879929799307993179932799337993479935799367993779938799397994079941799427994379944799457994679947799487994979950799517995279953799547995579956799577995879959799607996179962799637996479965799667996779968799697997079971799727997379974799757997679977799787997979980799817998279983799847998579986799877998879989799907999179992799937999479995799967999779998799998000080001800028000380004800058000680007800088000980010800118001280013800148001580016800178001880019800208002180022800238002480025800268002780028800298003080031800328003380034800358003680037800388003980040800418004280043800448004580046800478004880049800508005180052800538005480055800568005780058800598006080061800628006380064800658006680067800688006980070800718007280073800748007580076800778007880079800808008180082800838008480085800868008780088800898009080091800928009380094800958009680097800988009980100801018010280103801048010580106801078010880109801108011180112801138011480115801168011780118801198012080121801228012380124801258012680127801288012980130801318013280133801348013580136801378013880139801408014180142801438014480145801468014780148801498015080151801528015380154801558015680157801588015980160801618016280163801648016580166801678016880169801708017180172801738017480175801768017780178801798018080181801828018380184801858018680187801888018980190801918019280193801948019580196801978019880199802008020180202802038020480205802068020780208802098021080211802128021380214802158021680217802188021980220802218022280223802248022580226802278022880229802308023180232802338023480235802368023780238802398024080241802428024380244802458024680247802488024980250802518025280253802548025580256802578025880259802608026180262802638026480265802668026780268802698027080271802728027380274802758027680277802788027980280802818028280283802848028580286802878028880289802908029180292802938029480295802968029780298802998030080301803028030380304803058030680307803088030980310803118031280313803148031580316803178031880319803208032180322803238032480325803268032780328803298033080331803328033380334803358033680337803388033980340803418034280343803448034580346803478034880349803508035180352803538035480355803568035780358803598036080361803628036380364803658036680367803688036980370803718037280373803748037580376803778037880379803808038180382803838038480385803868038780388803898039080391803928039380394803958039680397803988039980400804018040280403804048040580406804078040880409804108041180412804138041480415804168041780418804198042080421804228042380424804258042680427804288042980430804318043280433804348043580436804378043880439804408044180442804438044480445804468044780448804498045080451804528045380454804558045680457804588045980460804618046280463804648046580466804678046880469804708047180472804738047480475804768047780478804798048080481804828048380484804858048680487804888048980490804918049280493804948049580496804978049880499805008050180502805038050480505805068050780508805098051080511805128051380514805158051680517805188051980520805218052280523805248052580526805278052880529805308053180532805338053480535805368053780538805398054080541805428054380544805458054680547805488054980550805518055280553805548055580556805578055880559805608056180562805638056480565805668056780568805698057080571805728057380574805758057680577805788057980580805818058280583805848058580586805878058880589805908059180592805938059480595805968059780598805998060080601806028060380604806058060680607806088060980610806118061280613806148061580616806178061880619806208062180622806238062480625806268062780628806298063080631806328063380634806358063680637806388063980640806418064280643806448064580646806478064880649806508065180652806538065480655806568065780658806598066080661806628066380664806658066680667806688066980670806718067280673806748067580676806778067880679806808068180682806838068480685806868068780688806898069080691806928069380694806958069680697806988069980700807018070280703807048070580706807078070880709807108071180712807138071480715807168071780718807198072080721807228072380724807258072680727807288072980730807318073280733807348073580736807378073880739807408074180742807438074480745807468074780748807498075080751807528075380754807558075680757807588075980760807618076280763807648076580766807678076880769807708077180772807738077480775807768077780778807798078080781807828078380784807858078680787807888078980790807918079280793807948079580796807978079880799808008080180802808038080480805808068080780808808098081080811808128081380814808158081680817808188081980820808218082280823808248082580826808278082880829808308083180832808338083480835808368083780838808398084080841808428084380844808458084680847808488084980850808518085280853808548085580856808578085880859808608086180862808638086480865808668086780868808698087080871808728087380874808758087680877808788087980880808818088280883808848088580886808878088880889808908089180892808938089480895808968089780898808998090080901809028090380904809058090680907809088090980910809118091280913809148091580916809178091880919809208092180922809238092480925809268092780928809298093080931809328093380934809358093680937809388093980940809418094280943809448094580946809478094880949809508095180952809538095480955809568095780958809598096080961809628096380964809658096680967809688096980970809718097280973809748097580976809778097880979809808098180982809838098480985809868098780988809898099080991809928099380994809958099680997809988099981000810018100281003810048100581006810078100881009810108101181012810138101481015810168101781018810198102081021810228102381024810258102681027810288102981030810318103281033810348103581036810378103881039810408104181042810438104481045810468104781048810498105081051810528105381054810558105681057810588105981060810618106281063810648106581066810678106881069810708107181072810738107481075810768107781078810798108081081810828108381084810858108681087810888108981090810918109281093810948109581096810978109881099811008110181102811038110481105811068110781108811098111081111811128111381114811158111681117811188111981120811218112281123811248112581126811278112881129811308113181132811338113481135811368113781138811398114081141811428114381144811458114681147811488114981150811518115281153811548115581156811578115881159811608116181162811638116481165811668116781168811698117081171811728117381174811758117681177811788117981180811818118281183811848118581186811878118881189811908119181192811938119481195811968119781198811998120081201812028120381204812058120681207812088120981210812118121281213812148121581216812178121881219812208122181222812238122481225812268122781228812298123081231812328123381234812358123681237812388123981240812418124281243812448124581246812478124881249812508125181252812538125481255812568125781258812598126081261812628126381264812658126681267812688126981270812718127281273812748127581276812778127881279812808128181282812838128481285812868128781288812898129081291812928129381294812958129681297812988129981300813018130281303813048130581306813078130881309813108131181312813138131481315813168131781318813198132081321813228132381324813258132681327813288132981330813318133281333813348133581336813378133881339813408134181342813438134481345813468134781348813498135081351813528135381354813558135681357813588135981360813618136281363813648136581366813678136881369813708137181372813738137481375813768137781378813798138081381813828138381384813858138681387813888138981390813918139281393813948139581396813978139881399814008140181402814038140481405814068140781408814098141081411814128141381414814158141681417814188141981420814218142281423814248142581426814278142881429814308143181432814338143481435814368143781438814398144081441814428144381444814458144681447814488144981450814518145281453814548145581456814578145881459814608146181462814638146481465814668146781468814698147081471814728147381474814758147681477814788147981480814818148281483814848148581486814878148881489814908149181492814938149481495814968149781498814998150081501815028150381504815058150681507815088150981510815118151281513815148151581516815178151881519815208152181522815238152481525815268152781528815298153081531815328153381534815358153681537815388153981540815418154281543815448154581546815478154881549815508155181552815538155481555815568155781558815598156081561815628156381564815658156681567815688156981570815718157281573815748157581576815778157881579815808158181582815838158481585815868158781588815898159081591815928159381594815958159681597815988159981600816018160281603816048160581606816078160881609816108161181612816138161481615816168161781618816198162081621816228162381624816258162681627816288162981630816318163281633816348163581636816378163881639816408164181642816438164481645816468164781648816498165081651816528165381654816558165681657816588165981660816618166281663816648166581666816678166881669816708167181672816738167481675816768167781678816798168081681816828168381684816858168681687816888168981690816918169281693816948169581696816978169881699817008170181702817038170481705817068170781708817098171081711817128171381714817158171681717817188171981720817218172281723817248172581726817278172881729817308173181732817338173481735817368173781738817398174081741817428174381744817458174681747817488174981750817518175281753817548175581756817578175881759817608176181762817638176481765817668176781768817698177081771817728177381774817758177681777817788177981780817818178281783817848178581786817878178881789817908179181792817938179481795817968179781798817998180081801818028180381804818058180681807818088180981810818118181281813818148181581816818178181881819818208182181822818238182481825818268182781828818298183081831818328183381834818358183681837818388183981840818418184281843818448184581846818478184881849818508185181852818538185481855818568185781858818598186081861818628186381864818658186681867818688186981870818718187281873818748187581876818778187881879818808188181882818838188481885818868188781888818898189081891818928189381894818958189681897818988189981900819018190281903819048190581906819078190881909819108191181912819138191481915819168191781918819198192081921819228192381924819258192681927819288192981930819318193281933819348193581936819378193881939819408194181942819438194481945819468194781948819498195081951819528195381954819558195681957819588195981960819618196281963819648196581966819678196881969819708197181972819738197481975819768197781978819798198081981819828198381984819858198681987819888198981990819918199281993819948199581996819978199881999820008200182002820038200482005820068200782008820098201082011820128201382014820158201682017820188201982020820218202282023820248202582026820278202882029820308203182032820338203482035820368203782038820398204082041820428204382044820458204682047820488204982050820518205282053820548205582056820578205882059820608206182062820638206482065820668206782068820698207082071820728207382074820758207682077820788207982080820818208282083820848208582086820878208882089820908209182092820938209482095820968209782098820998210082101821028210382104821058210682107821088210982110821118211282113821148211582116821178211882119821208212182122821238212482125821268212782128821298213082131821328213382134821358213682137821388213982140821418214282143821448214582146821478214882149821508215182152821538215482155821568215782158821598216082161821628216382164821658216682167821688216982170821718217282173821748217582176821778217882179821808218182182821838218482185821868218782188821898219082191821928219382194821958219682197821988219982200822018220282203822048220582206822078220882209822108221182212822138221482215822168221782218822198222082221822228222382224822258222682227822288222982230822318223282233822348223582236822378223882239822408224182242822438224482245822468224782248822498225082251822528225382254822558225682257822588225982260822618226282263822648226582266822678226882269822708227182272822738227482275822768227782278822798228082281822828228382284822858228682287822888228982290822918229282293822948229582296822978229882299823008230182302823038230482305823068230782308823098231082311823128231382314823158231682317823188231982320823218232282323823248232582326823278232882329823308233182332823338233482335823368233782338823398234082341823428234382344823458234682347823488234982350823518235282353823548235582356823578235882359823608236182362823638236482365823668236782368823698237082371823728237382374823758237682377823788237982380823818238282383823848238582386823878238882389823908239182392823938239482395823968239782398823998240082401824028240382404824058240682407824088240982410824118241282413824148241582416824178241882419824208242182422824238242482425824268242782428824298243082431824328243382434824358243682437824388243982440824418244282443824448244582446824478244882449824508245182452824538245482455824568245782458824598246082461824628246382464824658246682467824688246982470824718247282473824748247582476824778247882479824808248182482824838248482485824868248782488824898249082491824928249382494824958249682497824988249982500825018250282503825048250582506825078250882509825108251182512825138251482515825168251782518825198252082521825228252382524825258252682527825288252982530825318253282533825348253582536825378253882539825408254182542825438254482545825468254782548825498255082551825528255382554825558255682557825588255982560825618256282563825648256582566825678256882569825708257182572825738257482575825768257782578825798258082581825828258382584825858258682587825888258982590825918259282593825948259582596825978259882599826008260182602826038260482605826068260782608826098261082611826128261382614826158261682617826188261982620826218262282623826248262582626826278262882629826308263182632826338263482635826368263782638826398264082641826428264382644826458264682647826488264982650826518265282653826548265582656826578265882659826608266182662826638266482665826668266782668826698267082671826728267382674826758267682677826788267982680826818268282683826848268582686826878268882689826908269182692826938269482695826968269782698826998270082701827028270382704827058270682707827088270982710827118271282713827148271582716827178271882719827208272182722827238272482725827268272782728827298273082731827328273382734827358273682737827388273982740827418274282743827448274582746827478274882749827508275182752827538275482755827568275782758827598276082761827628276382764827658276682767827688276982770827718277282773827748277582776827778277882779827808278182782827838278482785827868278782788827898279082791827928279382794827958279682797827988279982800828018280282803828048280582806828078280882809828108281182812828138281482815828168281782818828198282082821828228282382824828258282682827828288282982830828318283282833828348283582836828378283882839828408284182842828438284482845828468284782848828498285082851828528285382854828558285682857828588285982860828618286282863828648286582866828678286882869828708287182872828738287482875828768287782878828798288082881828828288382884828858288682887828888288982890828918289282893828948289582896828978289882899829008290182902829038290482905829068290782908829098291082911829128291382914829158291682917829188291982920829218292282923829248292582926829278292882929829308293182932829338293482935829368293782938829398294082941829428294382944829458294682947829488294982950829518295282953829548295582956829578295882959829608296182962829638296482965829668296782968829698297082971829728297382974829758297682977829788297982980829818298282983829848298582986829878298882989829908299182992829938299482995829968299782998829998300083001830028300383004830058300683007830088300983010830118301283013830148301583016830178301883019830208302183022830238302483025830268302783028830298303083031830328303383034830358303683037830388303983040830418304283043830448304583046830478304883049830508305183052830538305483055830568305783058830598306083061830628306383064830658306683067830688306983070830718307283073830748307583076830778307883079830808308183082830838308483085830868308783088830898309083091830928309383094830958309683097830988309983100831018310283103831048310583106831078310883109831108311183112831138311483115831168311783118831198312083121831228312383124831258312683127831288312983130831318313283133831348313583136831378313883139831408314183142831438314483145831468314783148831498315083151831528315383154831558315683157831588315983160831618316283163831648316583166831678316883169831708317183172831738317483175831768317783178831798318083181831828318383184831858318683187831888318983190831918319283193831948319583196831978319883199832008320183202832038320483205832068320783208832098321083211832128321383214832158321683217832188321983220832218322283223832248322583226832278322883229832308323183232832338323483235832368323783238832398324083241832428324383244832458324683247832488324983250832518325283253832548325583256832578325883259832608326183262832638326483265832668326783268832698327083271832728327383274832758327683277832788327983280832818328283283832848328583286832878328883289832908329183292832938329483295832968329783298832998330083301833028330383304833058330683307833088330983310833118331283313833148331583316833178331883319833208332183322833238332483325833268332783328833298333083331833328333383334833358333683337833388333983340833418334283343833448334583346833478334883349833508335183352833538335483355833568335783358833598336083361833628336383364833658336683367833688336983370833718337283373833748337583376833778337883379833808338183382833838338483385833868338783388833898339083391833928339383394833958339683397833988339983400834018340283403834048340583406834078340883409834108341183412834138341483415834168341783418834198342083421834228342383424834258342683427834288342983430834318343283433834348343583436834378343883439834408344183442834438344483445834468344783448834498345083451834528345383454834558345683457834588345983460834618346283463834648346583466834678346883469834708347183472834738347483475834768347783478834798348083481834828348383484834858348683487834888348983490834918349283493834948349583496834978349883499835008350183502835038350483505835068350783508835098351083511835128351383514835158351683517835188351983520835218352283523835248352583526835278352883529835308353183532835338353483535835368353783538835398354083541835428354383544835458354683547835488354983550835518355283553835548355583556835578355883559835608356183562835638356483565835668356783568835698357083571835728357383574835758357683577835788357983580835818358283583835848358583586835878358883589835908359183592835938359483595835968359783598835998360083601836028360383604836058360683607836088360983610836118361283613836148361583616836178361883619836208362183622836238362483625836268362783628836298363083631836328363383634836358363683637836388363983640836418364283643836448364583646836478364883649836508365183652836538365483655836568365783658836598366083661836628366383664836658366683667836688366983670836718367283673836748367583676836778367883679836808368183682836838368483685836868368783688836898369083691836928369383694836958369683697836988369983700837018370283703837048370583706837078370883709837108371183712837138371483715837168371783718837198372083721837228372383724837258372683727837288372983730837318373283733837348373583736837378373883739837408374183742837438374483745837468374783748837498375083751837528375383754837558375683757837588375983760837618376283763837648376583766837678376883769837708377183772837738377483775837768377783778837798378083781837828378383784837858378683787837888378983790837918379283793837948379583796837978379883799838008380183802838038380483805838068380783808838098381083811838128381383814838158381683817838188381983820838218382283823838248382583826838278382883829838308383183832838338383483835838368383783838838398384083841838428384383844838458384683847838488384983850838518385283853838548385583856838578385883859838608386183862838638386483865838668386783868838698387083871838728387383874838758387683877838788387983880838818388283883838848388583886838878388883889838908389183892838938389483895838968389783898838998390083901839028390383904839058390683907839088390983910839118391283913839148391583916839178391883919839208392183922839238392483925839268392783928839298393083931839328393383934839358393683937839388393983940839418394283943839448394583946839478394883949839508395183952839538395483955839568395783958839598396083961839628396383964839658396683967839688396983970839718397283973839748397583976839778397883979839808398183982839838398483985839868398783988839898399083991839928399383994839958399683997839988399984000840018400284003840048400584006840078400884009840108401184012840138401484015840168401784018840198402084021840228402384024840258402684027840288402984030840318403284033840348403584036840378403884039840408404184042840438404484045840468404784048840498405084051840528405384054840558405684057840588405984060840618406284063840648406584066840678406884069840708407184072840738407484075840768407784078840798408084081840828408384084840858408684087840888408984090840918409284093840948409584096840978409884099841008410184102841038410484105841068410784108841098411084111841128411384114841158411684117841188411984120841218412284123841248412584126841278412884129841308413184132841338413484135841368413784138841398414084141841428414384144841458414684147841488414984150841518415284153841548415584156841578415884159841608416184162841638416484165841668416784168841698417084171841728417384174841758417684177841788417984180841818418284183841848418584186841878418884189841908419184192841938419484195841968419784198841998420084201842028420384204842058420684207842088420984210842118421284213842148421584216842178421884219842208422184222842238422484225842268422784228842298423084231842328423384234842358423684237842388423984240842418424284243842448424584246842478424884249842508425184252842538425484255842568425784258842598426084261842628426384264842658426684267842688426984270842718427284273842748427584276842778427884279842808428184282842838428484285842868428784288842898429084291842928429384294842958429684297842988429984300843018430284303843048430584306843078430884309843108431184312843138431484315843168431784318843198432084321843228432384324843258432684327843288432984330843318433284333843348433584336843378433884339843408434184342843438434484345843468434784348843498435084351843528435384354843558435684357843588435984360843618436284363843648436584366843678436884369843708437184372843738437484375843768437784378843798438084381843828438384384843858438684387843888438984390843918439284393843948439584396843978439884399844008440184402844038440484405844068440784408844098441084411844128441384414844158441684417844188441984420844218442284423844248442584426844278442884429844308443184432844338443484435844368443784438844398444084441844428444384444844458444684447844488444984450844518445284453844548445584456844578445884459844608446184462844638446484465844668446784468844698447084471844728447384474844758447684477844788447984480844818448284483844848448584486844878448884489844908449184492844938449484495844968449784498844998450084501845028450384504845058450684507845088450984510845118451284513845148451584516845178451884519845208452184522845238452484525845268452784528845298453084531845328453384534845358453684537845388453984540845418454284543845448454584546845478454884549845508455184552845538455484555845568455784558845598456084561845628456384564845658456684567845688456984570845718457284573845748457584576845778457884579845808458184582845838458484585845868458784588845898459084591845928459384594845958459684597845988459984600846018460284603846048460584606846078460884609846108461184612846138461484615846168461784618846198462084621846228462384624846258462684627846288462984630846318463284633846348463584636846378463884639846408464184642846438464484645846468464784648846498465084651846528465384654846558465684657846588465984660846618466284663846648466584666846678466884669846708467184672846738467484675846768467784678846798468084681846828468384684846858468684687846888468984690846918469284693846948469584696846978469884699847008470184702847038470484705847068470784708847098471084711847128471384714847158471684717847188471984720847218472284723847248472584726847278472884729847308473184732847338473484735847368473784738847398474084741847428474384744847458474684747847488474984750847518475284753847548475584756847578475884759847608476184762847638476484765847668476784768847698477084771847728477384774847758477684777847788477984780847818478284783847848478584786847878478884789847908479184792847938479484795847968479784798847998480084801848028480384804848058480684807848088480984810848118481284813848148481584816848178481884819848208482184822848238482484825848268482784828848298483084831848328483384834848358483684837848388483984840848418484284843848448484584846848478484884849848508485184852848538485484855848568485784858848598486084861848628486384864848658486684867848688486984870848718487284873848748487584876848778487884879848808488184882848838488484885848868488784888848898489084891848928489384894848958489684897848988489984900849018490284903849048490584906849078490884909849108491184912849138491484915849168491784918849198492084921849228492384924849258492684927849288492984930849318493284933849348493584936849378493884939849408494184942849438494484945849468494784948849498495084951849528495384954849558495684957849588495984960849618496284963849648496584966849678496884969849708497184972849738497484975849768497784978849798498084981849828498384984849858498684987849888498984990849918499284993849948499584996849978499884999850008500185002850038500485005850068500785008850098501085011850128501385014850158501685017850188501985020850218502285023850248502585026850278502885029850308503185032850338503485035850368503785038850398504085041850428504385044850458504685047850488504985050850518505285053850548505585056850578505885059850608506185062850638506485065850668506785068850698507085071850728507385074850758507685077850788507985080850818508285083850848508585086850878508885089850908509185092850938509485095850968509785098850998510085101851028510385104851058510685107851088510985110851118511285113851148511585116851178511885119851208512185122851238512485125851268512785128851298513085131851328513385134851358513685137851388513985140851418514285143851448514585146851478514885149851508515185152851538515485155851568515785158851598516085161851628516385164851658516685167851688516985170851718517285173851748517585176851778517885179851808518185182851838518485185851868518785188851898519085191851928519385194851958519685197
  1. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  2. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  3. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  4. else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  5. return c > 3 && r && Object.defineProperty(target, key, r), r;
  6. };
  7. var __extends = (this && this.__extends) || (function () {
  8. var extendStatics = Object.setPrototypeOf ||
  9. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  10. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  11. return function (d, b) {
  12. extendStatics(d, b);
  13. function __() { this.constructor = d; }
  14. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  15. };
  16. })();
  17. var BABYLON;
  18. (function (BABYLON) {
  19. var EffectFallbacks = /** @class */ (function () {
  20. function EffectFallbacks() {
  21. this._defines = {};
  22. this._currentRank = 32;
  23. this._maxRank = -1;
  24. }
  25. EffectFallbacks.prototype.unBindMesh = function () {
  26. this._mesh = null;
  27. };
  28. EffectFallbacks.prototype.addFallback = function (rank, define) {
  29. if (!this._defines[rank]) {
  30. if (rank < this._currentRank) {
  31. this._currentRank = rank;
  32. }
  33. if (rank > this._maxRank) {
  34. this._maxRank = rank;
  35. }
  36. this._defines[rank] = new Array();
  37. }
  38. this._defines[rank].push(define);
  39. };
  40. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  41. this._mesh = mesh;
  42. if (rank < this._currentRank) {
  43. this._currentRank = rank;
  44. }
  45. if (rank > this._maxRank) {
  46. this._maxRank = rank;
  47. }
  48. };
  49. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  50. get: function () {
  51. return this._currentRank <= this._maxRank;
  52. },
  53. enumerable: true,
  54. configurable: true
  55. });
  56. EffectFallbacks.prototype.reduce = function (currentDefines) {
  57. // First we try to switch to CPU skinning
  58. if (this._mesh && this._mesh.computeBonesUsingShaders && this._mesh.numBoneInfluencers > 0) {
  59. this._mesh.computeBonesUsingShaders = false;
  60. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  61. BABYLON.Tools.Log("Falling back to CPU skinning for " + this._mesh.name);
  62. var scene = this._mesh.getScene();
  63. for (var index = 0; index < scene.meshes.length; index++) {
  64. var otherMesh = scene.meshes[index];
  65. if (otherMesh.material === this._mesh.material && otherMesh.computeBonesUsingShaders && otherMesh.numBoneInfluencers > 0) {
  66. otherMesh.computeBonesUsingShaders = false;
  67. }
  68. }
  69. }
  70. else {
  71. var currentFallbacks = this._defines[this._currentRank];
  72. if (currentFallbacks) {
  73. for (var index = 0; index < currentFallbacks.length; index++) {
  74. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  75. }
  76. }
  77. this._currentRank++;
  78. }
  79. return currentDefines;
  80. };
  81. return EffectFallbacks;
  82. }());
  83. BABYLON.EffectFallbacks = EffectFallbacks;
  84. var EffectCreationOptions = /** @class */ (function () {
  85. function EffectCreationOptions() {
  86. }
  87. return EffectCreationOptions;
  88. }());
  89. BABYLON.EffectCreationOptions = EffectCreationOptions;
  90. var Effect = /** @class */ (function () {
  91. function Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, engine, defines, fallbacks, onCompiled, onError, indexParameters) {
  92. if (samplers === void 0) { samplers = null; }
  93. if (defines === void 0) { defines = null; }
  94. if (fallbacks === void 0) { fallbacks = null; }
  95. if (onCompiled === void 0) { onCompiled = null; }
  96. if (onError === void 0) { onError = null; }
  97. var _this = this;
  98. this.uniqueId = 0;
  99. this.onCompileObservable = new BABYLON.Observable();
  100. this.onErrorObservable = new BABYLON.Observable();
  101. this.onBindObservable = new BABYLON.Observable();
  102. this._uniformBuffersNames = {};
  103. this._isReady = false;
  104. this._compilationError = "";
  105. this.name = baseName;
  106. if (attributesNamesOrOptions.attributes) {
  107. var options = attributesNamesOrOptions;
  108. this._engine = uniformsNamesOrEngine;
  109. this._attributesNames = options.attributes;
  110. this._uniformsNames = options.uniformsNames.concat(options.samplers);
  111. this._samplers = options.samplers;
  112. this.defines = options.defines;
  113. this.onError = options.onError;
  114. this.onCompiled = options.onCompiled;
  115. this._fallbacks = options.fallbacks;
  116. this._indexParameters = options.indexParameters;
  117. this._transformFeedbackVaryings = options.transformFeedbackVaryings;
  118. if (options.uniformBuffersNames) {
  119. for (var i = 0; i < options.uniformBuffersNames.length; i++) {
  120. this._uniformBuffersNames[options.uniformBuffersNames[i]] = i;
  121. }
  122. }
  123. }
  124. else {
  125. this._engine = engine;
  126. this.defines = defines;
  127. this._uniformsNames = uniformsNamesOrEngine.concat(samplers);
  128. this._samplers = samplers;
  129. this._attributesNames = attributesNamesOrOptions;
  130. this.onError = onError;
  131. this.onCompiled = onCompiled;
  132. this._indexParameters = indexParameters;
  133. this._fallbacks = fallbacks;
  134. }
  135. this.uniqueId = Effect._uniqueIdSeed++;
  136. var vertexSource;
  137. var fragmentSource;
  138. if (baseName.vertexElement) {
  139. vertexSource = document.getElementById(baseName.vertexElement);
  140. if (!vertexSource) {
  141. vertexSource = baseName.vertexElement;
  142. }
  143. }
  144. else {
  145. vertexSource = baseName.vertex || baseName;
  146. }
  147. if (baseName.fragmentElement) {
  148. fragmentSource = document.getElementById(baseName.fragmentElement);
  149. if (!fragmentSource) {
  150. fragmentSource = baseName.fragmentElement;
  151. }
  152. }
  153. else {
  154. fragmentSource = baseName.fragment || baseName;
  155. }
  156. var finalVertexCode;
  157. this._loadVertexShaderAsync(vertexSource)
  158. .then(function (vertexCode) {
  159. return _this._processIncludesAsync(vertexCode);
  160. })
  161. .then(function (vertexCodeWithIncludes) {
  162. finalVertexCode = _this._processShaderConversion(vertexCodeWithIncludes, false);
  163. return _this._loadFragmentShaderAsync(fragmentSource);
  164. })
  165. .then(function (fragmentCode) {
  166. return _this._processIncludesAsync(fragmentCode);
  167. })
  168. .then(function (fragmentCodeWithIncludes) {
  169. var migratedFragmentCode = _this._processShaderConversion(fragmentCodeWithIncludes, true);
  170. if (baseName) {
  171. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  172. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  173. _this._vertexSourceCode = "#define SHADER_NAME vertex:" + vertex + "\n" + finalVertexCode;
  174. _this._fragmentSourceCode = "#define SHADER_NAME fragment:" + fragment + "\n" + migratedFragmentCode;
  175. }
  176. else {
  177. _this._vertexSourceCode = finalVertexCode;
  178. _this._fragmentSourceCode = migratedFragmentCode;
  179. }
  180. _this._prepareEffect();
  181. });
  182. }
  183. Object.defineProperty(Effect.prototype, "key", {
  184. get: function () {
  185. return this._key;
  186. },
  187. enumerable: true,
  188. configurable: true
  189. });
  190. // Properties
  191. Effect.prototype.isReady = function () {
  192. return this._isReady;
  193. };
  194. Effect.prototype.getEngine = function () {
  195. return this._engine;
  196. };
  197. Effect.prototype.getProgram = function () {
  198. return this._program;
  199. };
  200. Effect.prototype.getAttributesNames = function () {
  201. return this._attributesNames;
  202. };
  203. Effect.prototype.getAttributeLocation = function (index) {
  204. return this._attributes[index];
  205. };
  206. Effect.prototype.getAttributeLocationByName = function (name) {
  207. var index = this._attributesNames.indexOf(name);
  208. return this._attributes[index];
  209. };
  210. Effect.prototype.getAttributesCount = function () {
  211. return this._attributes.length;
  212. };
  213. Effect.prototype.getUniformIndex = function (uniformName) {
  214. return this._uniformsNames.indexOf(uniformName);
  215. };
  216. Effect.prototype.getUniform = function (uniformName) {
  217. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  218. };
  219. Effect.prototype.getSamplers = function () {
  220. return this._samplers;
  221. };
  222. Effect.prototype.getCompilationError = function () {
  223. return this._compilationError;
  224. };
  225. // Methods
  226. Effect.prototype.executeWhenCompiled = function (func) {
  227. if (this.isReady()) {
  228. func(this);
  229. return;
  230. }
  231. this.onCompileObservable.add(function (effect) {
  232. func(effect);
  233. });
  234. };
  235. /** @ignore */
  236. Effect.prototype._loadVertexShaderAsync = function (vertex) {
  237. if (BABYLON.Tools.IsWindowObjectExist()) {
  238. // DOM element ?
  239. if (vertex instanceof HTMLElement) {
  240. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  241. return Promise.resolve(vertexCode);
  242. }
  243. }
  244. // Base64 encoded ?
  245. if (vertex.substr(0, 7) === "base64:") {
  246. var vertexBinary = window.atob(vertex.substr(7));
  247. return Promise.resolve(vertexBinary);
  248. }
  249. // Is in local store ?
  250. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  251. return Promise.resolve(Effect.ShadersStore[vertex + "VertexShader"]);
  252. }
  253. var vertexShaderUrl;
  254. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  255. vertexShaderUrl = vertex;
  256. }
  257. else {
  258. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  259. }
  260. // Vertex shader
  261. return this._engine._loadFileAsync(vertexShaderUrl + ".vertex.fx");
  262. };
  263. /** @ignore */
  264. Effect.prototype._loadFragmentShaderAsync = function (fragment) {
  265. if (BABYLON.Tools.IsWindowObjectExist()) {
  266. // DOM element ?
  267. if (fragment instanceof HTMLElement) {
  268. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  269. return Promise.resolve(fragmentCode);
  270. }
  271. }
  272. // Base64 encoded ?
  273. if (fragment.substr(0, 7) === "base64:") {
  274. var fragmentBinary = window.atob(fragment.substr(7));
  275. return Promise.resolve(fragmentBinary);
  276. }
  277. // Is in local store ?
  278. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  279. return Promise.resolve(Effect.ShadersStore[fragment + "PixelShader"]);
  280. }
  281. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  282. return Promise.resolve(Effect.ShadersStore[fragment + "FragmentShader"]);
  283. }
  284. var fragmentShaderUrl;
  285. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  286. fragmentShaderUrl = fragment;
  287. }
  288. else {
  289. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  290. }
  291. // Fragment shader
  292. return this._engine._loadFileAsync(fragmentShaderUrl + ".fragment.fx");
  293. };
  294. Effect.prototype._dumpShadersSource = function (vertexCode, fragmentCode, defines) {
  295. // Rebuild shaders source code
  296. var shaderVersion = (this._engine.webGLVersion > 1) ? "#version 300 es\n" : "";
  297. var prefix = shaderVersion + (defines ? defines + "\n" : "");
  298. vertexCode = prefix + vertexCode;
  299. fragmentCode = prefix + fragmentCode;
  300. // Number lines of shaders source code
  301. var i = 2;
  302. var regex = /\n/gm;
  303. var formattedVertexCode = "\n1\t" + vertexCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  304. i = 2;
  305. var formattedFragmentCode = "\n1\t" + fragmentCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  306. // Dump shaders name and formatted source code
  307. if (this.name.vertexElement) {
  308. BABYLON.Tools.Error("Vertex shader: " + this.name.vertexElement + formattedVertexCode);
  309. BABYLON.Tools.Error("Fragment shader: " + this.name.fragmentElement + formattedFragmentCode);
  310. }
  311. else if (this.name.vertex) {
  312. BABYLON.Tools.Error("Vertex shader: " + this.name.vertex + formattedVertexCode);
  313. BABYLON.Tools.Error("Fragment shader: " + this.name.fragment + formattedFragmentCode);
  314. }
  315. else {
  316. BABYLON.Tools.Error("Vertex shader: " + this.name + formattedVertexCode);
  317. BABYLON.Tools.Error("Fragment shader: " + this.name + formattedFragmentCode);
  318. }
  319. };
  320. ;
  321. Effect.prototype._processShaderConversion = function (sourceCode, isFragment) {
  322. var preparedSourceCode = this._processPrecision(sourceCode);
  323. if (this._engine.webGLVersion == 1) {
  324. return preparedSourceCode;
  325. }
  326. // Already converted
  327. if (preparedSourceCode.indexOf("#version 3") !== -1) {
  328. return preparedSourceCode.replace("#version 300 es", "");
  329. }
  330. var hasDrawBuffersExtension = preparedSourceCode.search(/#extension.+GL_EXT_draw_buffers.+require/) !== -1;
  331. // Remove extensions
  332. // #extension GL_OES_standard_derivatives : enable
  333. // #extension GL_EXT_shader_texture_lod : enable
  334. // #extension GL_EXT_frag_depth : enable
  335. // #extension GL_EXT_draw_buffers : require
  336. var regex = /#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth|GL_EXT_draw_buffers).+(enable|require)/g;
  337. var result = preparedSourceCode.replace(regex, "");
  338. // Migrate to GLSL v300
  339. result = result.replace(/varying(?![\n\r])\s/g, isFragment ? "in " : "out ");
  340. result = result.replace(/attribute[ \t]/g, "in ");
  341. result = result.replace(/[ \t]attribute/g, " in");
  342. if (isFragment) {
  343. result = result.replace(/texture2DLodEXT\s*\(/g, "textureLod(");
  344. result = result.replace(/textureCubeLodEXT\s*\(/g, "textureLod(");
  345. result = result.replace(/texture2D\s*\(/g, "texture(");
  346. result = result.replace(/textureCube\s*\(/g, "texture(");
  347. result = result.replace(/gl_FragDepthEXT/g, "gl_FragDepth");
  348. result = result.replace(/gl_FragColor/g, "glFragColor");
  349. result = result.replace(/gl_FragData/g, "glFragData");
  350. result = result.replace(/void\s+?main\s*\(/g, (hasDrawBuffersExtension ? "" : "out vec4 glFragColor;\n") + "void main(");
  351. }
  352. return result;
  353. };
  354. Effect.prototype._processIncludesAsync = function (sourceCode) {
  355. var _this = this;
  356. return new Promise(function (resolve, reject) {
  357. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  358. var match = regex.exec(sourceCode);
  359. var returnValue = sourceCode;
  360. while (match != null) {
  361. var includeFile = match[1];
  362. // Uniform declaration
  363. if (includeFile.indexOf("__decl__") !== -1) {
  364. includeFile = includeFile.replace(/__decl__/, "");
  365. if (_this._engine.supportsUniformBuffers) {
  366. includeFile = includeFile.replace(/Vertex/, "Ubo");
  367. includeFile = includeFile.replace(/Fragment/, "Ubo");
  368. }
  369. includeFile = includeFile + "Declaration";
  370. }
  371. if (Effect.IncludesShadersStore[includeFile]) {
  372. // Substitution
  373. var includeContent = Effect.IncludesShadersStore[includeFile];
  374. if (match[2]) {
  375. var splits = match[3].split(",");
  376. for (var index = 0; index < splits.length; index += 2) {
  377. var source = new RegExp(splits[index], "g");
  378. var dest = splits[index + 1];
  379. includeContent = includeContent.replace(source, dest);
  380. }
  381. }
  382. if (match[4]) {
  383. var indexString = match[5];
  384. if (indexString.indexOf("..") !== -1) {
  385. var indexSplits = indexString.split("..");
  386. var minIndex = parseInt(indexSplits[0]);
  387. var maxIndex = parseInt(indexSplits[1]);
  388. var sourceIncludeContent = includeContent.slice(0);
  389. includeContent = "";
  390. if (isNaN(maxIndex)) {
  391. maxIndex = _this._indexParameters[indexSplits[1]];
  392. }
  393. for (var i = minIndex; i < maxIndex; i++) {
  394. if (!_this._engine.supportsUniformBuffers) {
  395. // Ubo replacement
  396. sourceIncludeContent = sourceIncludeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  397. return p1 + "{X}";
  398. });
  399. }
  400. includeContent += sourceIncludeContent.replace(/\{X\}/g, i.toString()) + "\n";
  401. }
  402. }
  403. else {
  404. if (!_this._engine.supportsUniformBuffers) {
  405. // Ubo replacement
  406. includeContent = includeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  407. return p1 + "{X}";
  408. });
  409. }
  410. includeContent = includeContent.replace(/\{X\}/g, indexString);
  411. }
  412. }
  413. // Replace
  414. returnValue = returnValue.replace(match[0], includeContent);
  415. }
  416. else {
  417. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  418. _this._engine._loadFileAsync(includeShaderUrl)
  419. .then(function (fileContent) {
  420. Effect.IncludesShadersStore[includeFile] = fileContent;
  421. return _this._processIncludesAsync(returnValue);
  422. })
  423. .then(function (returnValue) {
  424. resolve(returnValue);
  425. });
  426. return;
  427. }
  428. match = regex.exec(sourceCode);
  429. }
  430. resolve(returnValue);
  431. });
  432. };
  433. Effect.prototype._processPrecision = function (source) {
  434. if (source.indexOf("precision highp float") === -1) {
  435. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  436. source = "precision mediump float;\n" + source;
  437. }
  438. else {
  439. source = "precision highp float;\n" + source;
  440. }
  441. }
  442. else {
  443. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  444. source = source.replace("precision highp float", "precision mediump float");
  445. }
  446. }
  447. return source;
  448. };
  449. Effect.prototype._rebuildProgram = function (vertexSourceCode, fragmentSourceCode, onCompiled, onError) {
  450. var _this = this;
  451. this._isReady = false;
  452. this._vertexSourceCodeOverride = vertexSourceCode;
  453. this._fragmentSourceCodeOverride = fragmentSourceCode;
  454. this.onError = function (effect, error) {
  455. if (onError) {
  456. onError(error);
  457. }
  458. };
  459. this.onCompiled = function () {
  460. var scenes = _this.getEngine().scenes;
  461. for (var i = 0; i < scenes.length; i++) {
  462. scenes[i].markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  463. }
  464. if (onCompiled) {
  465. onCompiled(_this._program);
  466. }
  467. };
  468. this._fallbacks = null;
  469. this._prepareEffect();
  470. };
  471. Effect.prototype.getSpecificUniformLocations = function (names) {
  472. var engine = this._engine;
  473. return engine.getUniforms(this._program, names);
  474. };
  475. Effect.prototype._prepareEffect = function () {
  476. var attributesNames = this._attributesNames;
  477. var defines = this.defines;
  478. var fallbacks = this._fallbacks;
  479. this._valueCache = {};
  480. var previousProgram = this._program;
  481. try {
  482. var engine = this._engine;
  483. if (this._vertexSourceCodeOverride && this._fragmentSourceCodeOverride) {
  484. this._program = engine.createRawShaderProgram(this._vertexSourceCodeOverride, this._fragmentSourceCodeOverride, undefined, this._transformFeedbackVaryings);
  485. }
  486. else {
  487. this._program = engine.createShaderProgram(this._vertexSourceCode, this._fragmentSourceCode, defines, undefined, this._transformFeedbackVaryings);
  488. }
  489. this._program.__SPECTOR_rebuildProgram = this._rebuildProgram.bind(this);
  490. if (engine.supportsUniformBuffers) {
  491. for (var name in this._uniformBuffersNames) {
  492. this.bindUniformBlock(name, this._uniformBuffersNames[name]);
  493. }
  494. }
  495. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  496. this._attributes = engine.getAttributes(this._program, attributesNames);
  497. var index;
  498. for (index = 0; index < this._samplers.length; index++) {
  499. var sampler = this.getUniform(this._samplers[index]);
  500. if (sampler == null) {
  501. this._samplers.splice(index, 1);
  502. index--;
  503. }
  504. }
  505. engine.bindSamplers(this);
  506. this._compilationError = "";
  507. this._isReady = true;
  508. if (this.onCompiled) {
  509. this.onCompiled(this);
  510. }
  511. this.onCompileObservable.notifyObservers(this);
  512. this.onCompileObservable.clear();
  513. // Unbind mesh reference in fallbacks
  514. if (this._fallbacks) {
  515. this._fallbacks.unBindMesh();
  516. }
  517. if (previousProgram) {
  518. this.getEngine()._deleteProgram(previousProgram);
  519. }
  520. }
  521. catch (e) {
  522. this._compilationError = e.message;
  523. // Let's go through fallbacks then
  524. BABYLON.Tools.Error("Unable to compile effect:");
  525. BABYLON.Tools.Error("Uniforms: " + this._uniformsNames.map(function (uniform) {
  526. return " " + uniform;
  527. }));
  528. BABYLON.Tools.Error("Attributes: " + attributesNames.map(function (attribute) {
  529. return " " + attribute;
  530. }));
  531. this._dumpShadersSource(this._vertexSourceCode, this._fragmentSourceCode, defines);
  532. BABYLON.Tools.Error("Error: " + this._compilationError);
  533. if (previousProgram) {
  534. this._program = previousProgram;
  535. this._isReady = true;
  536. if (this.onError) {
  537. this.onError(this, this._compilationError);
  538. }
  539. this.onErrorObservable.notifyObservers(this);
  540. }
  541. if (fallbacks && fallbacks.isMoreFallbacks) {
  542. BABYLON.Tools.Error("Trying next fallback.");
  543. this.defines = fallbacks.reduce(this.defines);
  544. this._prepareEffect();
  545. }
  546. else {
  547. if (this.onError) {
  548. this.onError(this, this._compilationError);
  549. }
  550. this.onErrorObservable.notifyObservers(this);
  551. this.onErrorObservable.clear();
  552. // Unbind mesh reference in fallbacks
  553. if (this._fallbacks) {
  554. this._fallbacks.unBindMesh();
  555. }
  556. }
  557. }
  558. };
  559. Object.defineProperty(Effect.prototype, "isSupported", {
  560. get: function () {
  561. return this._compilationError === "";
  562. },
  563. enumerable: true,
  564. configurable: true
  565. });
  566. Effect.prototype._bindTexture = function (channel, texture) {
  567. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  568. };
  569. Effect.prototype.setTexture = function (channel, texture) {
  570. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  571. };
  572. Effect.prototype.setTextureArray = function (channel, textures) {
  573. if (this._samplers.indexOf(channel + "Ex") === -1) {
  574. var initialPos = this._samplers.indexOf(channel);
  575. for (var index = 1; index < textures.length; index++) {
  576. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  577. }
  578. }
  579. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  580. };
  581. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  582. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  583. };
  584. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  585. var cache = this._valueCache[uniformName];
  586. var flag = matrix.updateFlag;
  587. if (cache !== undefined && cache === flag) {
  588. return false;
  589. }
  590. this._valueCache[uniformName] = flag;
  591. return true;
  592. };
  593. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  594. var cache = this._valueCache[uniformName];
  595. if (!cache) {
  596. cache = [x, y];
  597. this._valueCache[uniformName] = cache;
  598. return true;
  599. }
  600. var changed = false;
  601. if (cache[0] !== x) {
  602. cache[0] = x;
  603. changed = true;
  604. }
  605. if (cache[1] !== y) {
  606. cache[1] = y;
  607. changed = true;
  608. }
  609. return changed;
  610. };
  611. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  612. var cache = this._valueCache[uniformName];
  613. if (!cache) {
  614. cache = [x, y, z];
  615. this._valueCache[uniformName] = cache;
  616. return true;
  617. }
  618. var changed = false;
  619. if (cache[0] !== x) {
  620. cache[0] = x;
  621. changed = true;
  622. }
  623. if (cache[1] !== y) {
  624. cache[1] = y;
  625. changed = true;
  626. }
  627. if (cache[2] !== z) {
  628. cache[2] = z;
  629. changed = true;
  630. }
  631. return changed;
  632. };
  633. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  634. var cache = this._valueCache[uniformName];
  635. if (!cache) {
  636. cache = [x, y, z, w];
  637. this._valueCache[uniformName] = cache;
  638. return true;
  639. }
  640. var changed = false;
  641. if (cache[0] !== x) {
  642. cache[0] = x;
  643. changed = true;
  644. }
  645. if (cache[1] !== y) {
  646. cache[1] = y;
  647. changed = true;
  648. }
  649. if (cache[2] !== z) {
  650. cache[2] = z;
  651. changed = true;
  652. }
  653. if (cache[3] !== w) {
  654. cache[3] = w;
  655. changed = true;
  656. }
  657. return changed;
  658. };
  659. Effect.prototype.bindUniformBuffer = function (buffer, name) {
  660. var bufferName = this._uniformBuffersNames[name];
  661. if (bufferName === undefined || Effect._baseCache[bufferName] === buffer) {
  662. return;
  663. }
  664. Effect._baseCache[bufferName] = buffer;
  665. this._engine.bindUniformBufferBase(buffer, bufferName);
  666. };
  667. Effect.prototype.bindUniformBlock = function (blockName, index) {
  668. this._engine.bindUniformBlock(this._program, blockName, index);
  669. };
  670. Effect.prototype.setInt = function (uniformName, value) {
  671. var cache = this._valueCache[uniformName];
  672. if (cache !== undefined && cache === value)
  673. return this;
  674. this._valueCache[uniformName] = value;
  675. this._engine.setInt(this.getUniform(uniformName), value);
  676. return this;
  677. };
  678. Effect.prototype.setIntArray = function (uniformName, array) {
  679. this._valueCache[uniformName] = null;
  680. this._engine.setIntArray(this.getUniform(uniformName), array);
  681. return this;
  682. };
  683. Effect.prototype.setIntArray2 = function (uniformName, array) {
  684. this._valueCache[uniformName] = null;
  685. this._engine.setIntArray2(this.getUniform(uniformName), array);
  686. return this;
  687. };
  688. Effect.prototype.setIntArray3 = function (uniformName, array) {
  689. this._valueCache[uniformName] = null;
  690. this._engine.setIntArray3(this.getUniform(uniformName), array);
  691. return this;
  692. };
  693. Effect.prototype.setIntArray4 = function (uniformName, array) {
  694. this._valueCache[uniformName] = null;
  695. this._engine.setIntArray4(this.getUniform(uniformName), array);
  696. return this;
  697. };
  698. Effect.prototype.setFloatArray = function (uniformName, array) {
  699. this._valueCache[uniformName] = null;
  700. this._engine.setFloatArray(this.getUniform(uniformName), array);
  701. return this;
  702. };
  703. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  704. this._valueCache[uniformName] = null;
  705. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  706. return this;
  707. };
  708. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  709. this._valueCache[uniformName] = null;
  710. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  711. return this;
  712. };
  713. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  714. this._valueCache[uniformName] = null;
  715. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  716. return this;
  717. };
  718. Effect.prototype.setArray = function (uniformName, array) {
  719. this._valueCache[uniformName] = null;
  720. this._engine.setArray(this.getUniform(uniformName), array);
  721. return this;
  722. };
  723. Effect.prototype.setArray2 = function (uniformName, array) {
  724. this._valueCache[uniformName] = null;
  725. this._engine.setArray2(this.getUniform(uniformName), array);
  726. return this;
  727. };
  728. Effect.prototype.setArray3 = function (uniformName, array) {
  729. this._valueCache[uniformName] = null;
  730. this._engine.setArray3(this.getUniform(uniformName), array);
  731. return this;
  732. };
  733. Effect.prototype.setArray4 = function (uniformName, array) {
  734. this._valueCache[uniformName] = null;
  735. this._engine.setArray4(this.getUniform(uniformName), array);
  736. return this;
  737. };
  738. Effect.prototype.setMatrices = function (uniformName, matrices) {
  739. if (!matrices) {
  740. return this;
  741. }
  742. this._valueCache[uniformName] = null;
  743. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  744. return this;
  745. };
  746. Effect.prototype.setMatrix = function (uniformName, matrix) {
  747. if (this._cacheMatrix(uniformName, matrix)) {
  748. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  749. }
  750. return this;
  751. };
  752. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  753. this._valueCache[uniformName] = null;
  754. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  755. return this;
  756. };
  757. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  758. this._valueCache[uniformName] = null;
  759. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  760. return this;
  761. };
  762. Effect.prototype.setFloat = function (uniformName, value) {
  763. var cache = this._valueCache[uniformName];
  764. if (cache !== undefined && cache === value)
  765. return this;
  766. this._valueCache[uniformName] = value;
  767. this._engine.setFloat(this.getUniform(uniformName), value);
  768. return this;
  769. };
  770. Effect.prototype.setBool = function (uniformName, bool) {
  771. var cache = this._valueCache[uniformName];
  772. if (cache !== undefined && cache === bool)
  773. return this;
  774. this._valueCache[uniformName] = bool;
  775. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  776. return this;
  777. };
  778. Effect.prototype.setVector2 = function (uniformName, vector2) {
  779. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  780. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  781. }
  782. return this;
  783. };
  784. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  785. if (this._cacheFloat2(uniformName, x, y)) {
  786. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  787. }
  788. return this;
  789. };
  790. Effect.prototype.setVector3 = function (uniformName, vector3) {
  791. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  792. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  793. }
  794. return this;
  795. };
  796. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  797. if (this._cacheFloat3(uniformName, x, y, z)) {
  798. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  799. }
  800. return this;
  801. };
  802. Effect.prototype.setVector4 = function (uniformName, vector4) {
  803. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  804. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  805. }
  806. return this;
  807. };
  808. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  809. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  810. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  811. }
  812. return this;
  813. };
  814. Effect.prototype.setColor3 = function (uniformName, color3) {
  815. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  816. this._engine.setColor3(this.getUniform(uniformName), color3);
  817. }
  818. return this;
  819. };
  820. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  821. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  822. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  823. }
  824. return this;
  825. };
  826. Effect.ResetCache = function () {
  827. Effect._baseCache = {};
  828. };
  829. Effect._uniqueIdSeed = 0;
  830. Effect._baseCache = {};
  831. // Statics
  832. Effect.ShadersStore = {};
  833. Effect.IncludesShadersStore = {};
  834. return Effect;
  835. }());
  836. BABYLON.Effect = Effect;
  837. })(BABYLON || (BABYLON = {}));
  838. //# sourceMappingURL=babylon.effect.js.map
  839. //# sourceMappingURL=babylon.types.js.map
  840. var BABYLON;
  841. (function (BABYLON) {
  842. var KeyboardEventTypes = /** @class */ (function () {
  843. function KeyboardEventTypes() {
  844. }
  845. Object.defineProperty(KeyboardEventTypes, "KEYDOWN", {
  846. get: function () {
  847. return KeyboardEventTypes._KEYDOWN;
  848. },
  849. enumerable: true,
  850. configurable: true
  851. });
  852. Object.defineProperty(KeyboardEventTypes, "KEYUP", {
  853. get: function () {
  854. return KeyboardEventTypes._KEYUP;
  855. },
  856. enumerable: true,
  857. configurable: true
  858. });
  859. KeyboardEventTypes._KEYDOWN = 0x01;
  860. KeyboardEventTypes._KEYUP = 0x02;
  861. return KeyboardEventTypes;
  862. }());
  863. BABYLON.KeyboardEventTypes = KeyboardEventTypes;
  864. var KeyboardInfo = /** @class */ (function () {
  865. function KeyboardInfo(type, event) {
  866. this.type = type;
  867. this.event = event;
  868. }
  869. return KeyboardInfo;
  870. }());
  871. BABYLON.KeyboardInfo = KeyboardInfo;
  872. /**
  873. * This class is used to store keyboard related info for the onPreKeyboardObservable event.
  874. * Set the skipOnKeyboardObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onKeyboardObservable
  875. */
  876. var KeyboardInfoPre = /** @class */ (function (_super) {
  877. __extends(KeyboardInfoPre, _super);
  878. function KeyboardInfoPre(type, event) {
  879. var _this = _super.call(this, type, event) || this;
  880. _this.skipOnPointerObservable = false;
  881. return _this;
  882. }
  883. return KeyboardInfoPre;
  884. }(KeyboardInfo));
  885. BABYLON.KeyboardInfoPre = KeyboardInfoPre;
  886. })(BABYLON || (BABYLON = {}));
  887. //# sourceMappingURL=babylon.keyboardEvents.js.map
  888. var BABYLON;
  889. (function (BABYLON) {
  890. var PointerEventTypes = /** @class */ (function () {
  891. function PointerEventTypes() {
  892. }
  893. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  894. get: function () {
  895. return PointerEventTypes._POINTERDOWN;
  896. },
  897. enumerable: true,
  898. configurable: true
  899. });
  900. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  901. get: function () {
  902. return PointerEventTypes._POINTERUP;
  903. },
  904. enumerable: true,
  905. configurable: true
  906. });
  907. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  908. get: function () {
  909. return PointerEventTypes._POINTERMOVE;
  910. },
  911. enumerable: true,
  912. configurable: true
  913. });
  914. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  915. get: function () {
  916. return PointerEventTypes._POINTERWHEEL;
  917. },
  918. enumerable: true,
  919. configurable: true
  920. });
  921. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  922. get: function () {
  923. return PointerEventTypes._POINTERPICK;
  924. },
  925. enumerable: true,
  926. configurable: true
  927. });
  928. Object.defineProperty(PointerEventTypes, "POINTERTAP", {
  929. get: function () {
  930. return PointerEventTypes._POINTERTAP;
  931. },
  932. enumerable: true,
  933. configurable: true
  934. });
  935. Object.defineProperty(PointerEventTypes, "POINTERDOUBLETAP", {
  936. get: function () {
  937. return PointerEventTypes._POINTERDOUBLETAP;
  938. },
  939. enumerable: true,
  940. configurable: true
  941. });
  942. PointerEventTypes._POINTERDOWN = 0x01;
  943. PointerEventTypes._POINTERUP = 0x02;
  944. PointerEventTypes._POINTERMOVE = 0x04;
  945. PointerEventTypes._POINTERWHEEL = 0x08;
  946. PointerEventTypes._POINTERPICK = 0x10;
  947. PointerEventTypes._POINTERTAP = 0x20;
  948. PointerEventTypes._POINTERDOUBLETAP = 0x40;
  949. return PointerEventTypes;
  950. }());
  951. BABYLON.PointerEventTypes = PointerEventTypes;
  952. var PointerInfoBase = /** @class */ (function () {
  953. function PointerInfoBase(type, event) {
  954. this.type = type;
  955. this.event = event;
  956. }
  957. return PointerInfoBase;
  958. }());
  959. BABYLON.PointerInfoBase = PointerInfoBase;
  960. /**
  961. * This class is used to store pointer related info for the onPrePointerObservable event.
  962. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  963. */
  964. var PointerInfoPre = /** @class */ (function (_super) {
  965. __extends(PointerInfoPre, _super);
  966. function PointerInfoPre(type, event, localX, localY) {
  967. var _this = _super.call(this, type, event) || this;
  968. _this.skipOnPointerObservable = false;
  969. _this.localPosition = new BABYLON.Vector2(localX, localY);
  970. return _this;
  971. }
  972. return PointerInfoPre;
  973. }(PointerInfoBase));
  974. BABYLON.PointerInfoPre = PointerInfoPre;
  975. /**
  976. * This type contains all the data related to a pointer event in Babylon.js.
  977. * 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.
  978. */
  979. var PointerInfo = /** @class */ (function (_super) {
  980. __extends(PointerInfo, _super);
  981. function PointerInfo(type, event, pickInfo) {
  982. var _this = _super.call(this, type, event) || this;
  983. _this.pickInfo = pickInfo;
  984. return _this;
  985. }
  986. return PointerInfo;
  987. }(PointerInfoBase));
  988. BABYLON.PointerInfo = PointerInfo;
  989. })(BABYLON || (BABYLON = {}));
  990. //# sourceMappingURL=babylon.pointerEvents.js.map
  991. var BABYLON;
  992. (function (BABYLON) {
  993. BABYLON.ToGammaSpace = 1 / 2.2;
  994. BABYLON.ToLinearSpace = 2.2;
  995. BABYLON.Epsilon = 0.001;
  996. var Color3 = /** @class */ (function () {
  997. /**
  998. * Creates a new Color3 object from red, green, blue values, all between 0 and 1.
  999. */
  1000. function Color3(r, g, b) {
  1001. if (r === void 0) { r = 0; }
  1002. if (g === void 0) { g = 0; }
  1003. if (b === void 0) { b = 0; }
  1004. this.r = r;
  1005. this.g = g;
  1006. this.b = b;
  1007. }
  1008. /**
  1009. * Returns a string with the Color3 current values.
  1010. */
  1011. Color3.prototype.toString = function () {
  1012. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  1013. };
  1014. /**
  1015. * Returns the string "Color3".
  1016. */
  1017. Color3.prototype.getClassName = function () {
  1018. return "Color3";
  1019. };
  1020. /**
  1021. * Returns the Color3 hash code.
  1022. */
  1023. Color3.prototype.getHashCode = function () {
  1024. var hash = this.r || 0;
  1025. hash = (hash * 397) ^ (this.g || 0);
  1026. hash = (hash * 397) ^ (this.b || 0);
  1027. return hash;
  1028. };
  1029. // Operators
  1030. /**
  1031. * Stores in the passed array from the passed starting index the red, green, blue values as successive elements.
  1032. * Returns the Color3.
  1033. */
  1034. Color3.prototype.toArray = function (array, index) {
  1035. if (index === undefined) {
  1036. index = 0;
  1037. }
  1038. array[index] = this.r;
  1039. array[index + 1] = this.g;
  1040. array[index + 2] = this.b;
  1041. return this;
  1042. };
  1043. /**
  1044. * Returns a new Color4 object from the current Color3 and the passed alpha.
  1045. */
  1046. Color3.prototype.toColor4 = function (alpha) {
  1047. if (alpha === void 0) { alpha = 1; }
  1048. return new Color4(this.r, this.g, this.b, alpha);
  1049. };
  1050. /**
  1051. * Returns a new array populated with 3 numeric elements : red, green and blue values.
  1052. */
  1053. Color3.prototype.asArray = function () {
  1054. var result = new Array();
  1055. this.toArray(result, 0);
  1056. return result;
  1057. };
  1058. /**
  1059. * Returns the luminance value (float).
  1060. */
  1061. Color3.prototype.toLuminance = function () {
  1062. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  1063. };
  1064. /**
  1065. * Multiply each Color3 rgb values by the passed Color3 rgb values in a new Color3 object.
  1066. * Returns this new object.
  1067. */
  1068. Color3.prototype.multiply = function (otherColor) {
  1069. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  1070. };
  1071. /**
  1072. * Multiply the rgb values of the Color3 and the passed Color3 and stores the result in the object "result".
  1073. * Returns the current Color3.
  1074. */
  1075. Color3.prototype.multiplyToRef = function (otherColor, result) {
  1076. result.r = this.r * otherColor.r;
  1077. result.g = this.g * otherColor.g;
  1078. result.b = this.b * otherColor.b;
  1079. return this;
  1080. };
  1081. /**
  1082. * Boolean : True if the rgb values are equal to the passed ones.
  1083. */
  1084. Color3.prototype.equals = function (otherColor) {
  1085. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  1086. };
  1087. /**
  1088. * Boolean : True if the rgb values are equal to the passed ones.
  1089. */
  1090. Color3.prototype.equalsFloats = function (r, g, b) {
  1091. return this.r === r && this.g === g && this.b === b;
  1092. };
  1093. /**
  1094. * Multiplies in place each rgb value by scale.
  1095. * Returns the updated Color3.
  1096. */
  1097. Color3.prototype.scale = function (scale) {
  1098. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  1099. };
  1100. /**
  1101. * Multiplies the rgb values by scale and stores the result into "result".
  1102. * Returns the unmodified current Color3.
  1103. */
  1104. Color3.prototype.scaleToRef = function (scale, result) {
  1105. result.r = this.r * scale;
  1106. result.g = this.g * scale;
  1107. result.b = this.b * scale;
  1108. return this;
  1109. };
  1110. /**
  1111. * Clamps the rgb values by the min and max values and stores the result into "result".
  1112. * Returns the unmodified current Color3.
  1113. * @param min - minimum clamping value. Defaults to 0
  1114. * @param max - maximum clamping value. Defaults to 1
  1115. * @param result - color to store the result into.
  1116. * @returns - the original Color3
  1117. */
  1118. Color3.prototype.clampToRef = function (min, max, result) {
  1119. if (min === void 0) { min = 0; }
  1120. if (max === void 0) { max = 1; }
  1121. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1122. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1123. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1124. return this;
  1125. };
  1126. /**
  1127. * Returns a new Color3 set with the added values of the current Color3 and of the passed one.
  1128. */
  1129. Color3.prototype.add = function (otherColor) {
  1130. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  1131. };
  1132. /**
  1133. * Stores the result of the addition of the current Color3 and passed one rgb values into "result".
  1134. * Returns the unmodified current Color3.
  1135. */
  1136. Color3.prototype.addToRef = function (otherColor, result) {
  1137. result.r = this.r + otherColor.r;
  1138. result.g = this.g + otherColor.g;
  1139. result.b = this.b + otherColor.b;
  1140. return this;
  1141. };
  1142. /**
  1143. * Returns a new Color3 set with the subtracted values of the passed one from the current Color3 .
  1144. */
  1145. Color3.prototype.subtract = function (otherColor) {
  1146. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  1147. };
  1148. /**
  1149. * Stores the result of the subtraction of passed one from the current Color3 rgb values into "result".
  1150. * Returns the unmodified current Color3.
  1151. */
  1152. Color3.prototype.subtractToRef = function (otherColor, result) {
  1153. result.r = this.r - otherColor.r;
  1154. result.g = this.g - otherColor.g;
  1155. result.b = this.b - otherColor.b;
  1156. return this;
  1157. };
  1158. /**
  1159. * Returns a new Color3 copied the current one.
  1160. */
  1161. Color3.prototype.clone = function () {
  1162. return new Color3(this.r, this.g, this.b);
  1163. };
  1164. /**
  1165. * Copies the rgb values from the source in the current Color3.
  1166. * Returns the updated Color3.
  1167. */
  1168. Color3.prototype.copyFrom = function (source) {
  1169. this.r = source.r;
  1170. this.g = source.g;
  1171. this.b = source.b;
  1172. return this;
  1173. };
  1174. /**
  1175. * Updates the Color3 rgb values from the passed floats.
  1176. * Returns the Color3.
  1177. */
  1178. Color3.prototype.copyFromFloats = function (r, g, b) {
  1179. this.r = r;
  1180. this.g = g;
  1181. this.b = b;
  1182. return this;
  1183. };
  1184. /**
  1185. * Updates the Color3 rgb values from the passed floats.
  1186. * Returns the Color3.
  1187. */
  1188. Color3.prototype.set = function (r, g, b) {
  1189. return this.copyFromFloats(r, g, b);
  1190. };
  1191. /**
  1192. * Returns the Color3 hexadecimal code as a string.
  1193. */
  1194. Color3.prototype.toHexString = function () {
  1195. var intR = (this.r * 255) | 0;
  1196. var intG = (this.g * 255) | 0;
  1197. var intB = (this.b * 255) | 0;
  1198. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB);
  1199. };
  1200. /**
  1201. * Returns a new Color3 converted to linear space.
  1202. */
  1203. Color3.prototype.toLinearSpace = function () {
  1204. var convertedColor = new Color3();
  1205. this.toLinearSpaceToRef(convertedColor);
  1206. return convertedColor;
  1207. };
  1208. /**
  1209. * Converts the Color3 values to linear space and stores the result in "convertedColor".
  1210. * Returns the unmodified Color3.
  1211. */
  1212. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  1213. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  1214. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  1215. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  1216. return this;
  1217. };
  1218. /**
  1219. * Returns a new Color3 converted to gamma space.
  1220. */
  1221. Color3.prototype.toGammaSpace = function () {
  1222. var convertedColor = new Color3();
  1223. this.toGammaSpaceToRef(convertedColor);
  1224. return convertedColor;
  1225. };
  1226. /**
  1227. * Converts the Color3 values to gamma space and stores the result in "convertedColor".
  1228. * Returns the unmodified Color3.
  1229. */
  1230. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  1231. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  1232. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  1233. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  1234. return this;
  1235. };
  1236. // Statics
  1237. /**
  1238. * Creates a new Color3 from the string containing valid hexadecimal values.
  1239. */
  1240. Color3.FromHexString = function (hex) {
  1241. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  1242. //Tools.Warn("Color3.FromHexString must be called with a string like #FFFFFF");
  1243. return new Color3(0, 0, 0);
  1244. }
  1245. var r = parseInt(hex.substring(1, 3), 16);
  1246. var g = parseInt(hex.substring(3, 5), 16);
  1247. var b = parseInt(hex.substring(5, 7), 16);
  1248. return Color3.FromInts(r, g, b);
  1249. };
  1250. /**
  1251. * Creates a new Vector3 from the startind index of the passed array.
  1252. */
  1253. Color3.FromArray = function (array, offset) {
  1254. if (offset === void 0) { offset = 0; }
  1255. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  1256. };
  1257. /**
  1258. * Creates a new Color3 from integer values ( < 256).
  1259. */
  1260. Color3.FromInts = function (r, g, b) {
  1261. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  1262. };
  1263. /**
  1264. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3.
  1265. */
  1266. Color3.Lerp = function (start, end, amount) {
  1267. var r = start.r + ((end.r - start.r) * amount);
  1268. var g = start.g + ((end.g - start.g) * amount);
  1269. var b = start.b + ((end.b - start.b) * amount);
  1270. return new Color3(r, g, b);
  1271. };
  1272. Color3.Red = function () { return new Color3(1, 0, 0); };
  1273. Color3.Green = function () { return new Color3(0, 1, 0); };
  1274. Color3.Blue = function () { return new Color3(0, 0, 1); };
  1275. Color3.Black = function () { return new Color3(0, 0, 0); };
  1276. Color3.White = function () { return new Color3(1, 1, 1); };
  1277. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  1278. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  1279. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  1280. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  1281. Color3.Teal = function () { return new Color3(0, 1.0, 1.0); };
  1282. Color3.Random = function () { return new Color3(Math.random(), Math.random(), Math.random()); };
  1283. return Color3;
  1284. }());
  1285. BABYLON.Color3 = Color3;
  1286. var Color4 = /** @class */ (function () {
  1287. /**
  1288. * Creates a new Color4 object from the passed float values ( < 1) : red, green, blue, alpha.
  1289. */
  1290. function Color4(r, g, b, a) {
  1291. if (r === void 0) { r = 0; }
  1292. if (g === void 0) { g = 0; }
  1293. if (b === void 0) { b = 0; }
  1294. if (a === void 0) { a = 1; }
  1295. this.r = r;
  1296. this.g = g;
  1297. this.b = b;
  1298. this.a = a;
  1299. }
  1300. // Operators
  1301. /**
  1302. * Adds in place the passed Color4 values to the current Color4.
  1303. * Returns the updated Color4.
  1304. */
  1305. Color4.prototype.addInPlace = function (right) {
  1306. this.r += right.r;
  1307. this.g += right.g;
  1308. this.b += right.b;
  1309. this.a += right.a;
  1310. return this;
  1311. };
  1312. /**
  1313. * Returns a new array populated with 4 numeric elements : red, green, blue, alpha values.
  1314. */
  1315. Color4.prototype.asArray = function () {
  1316. var result = new Array();
  1317. this.toArray(result, 0);
  1318. return result;
  1319. };
  1320. /**
  1321. * Stores from the starting index in the passed array the Color4 successive values.
  1322. * Returns the Color4.
  1323. */
  1324. Color4.prototype.toArray = function (array, index) {
  1325. if (index === undefined) {
  1326. index = 0;
  1327. }
  1328. array[index] = this.r;
  1329. array[index + 1] = this.g;
  1330. array[index + 2] = this.b;
  1331. array[index + 3] = this.a;
  1332. return this;
  1333. };
  1334. /**
  1335. * Returns a new Color4 set with the added values of the current Color4 and of the passed one.
  1336. */
  1337. Color4.prototype.add = function (right) {
  1338. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  1339. };
  1340. /**
  1341. * Returns a new Color4 set with the subtracted values of the passed one from the current Color4.
  1342. */
  1343. Color4.prototype.subtract = function (right) {
  1344. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  1345. };
  1346. /**
  1347. * Subtracts the passed ones from the current Color4 values and stores the results in "result".
  1348. * Returns the Color4.
  1349. */
  1350. Color4.prototype.subtractToRef = function (right, result) {
  1351. result.r = this.r - right.r;
  1352. result.g = this.g - right.g;
  1353. result.b = this.b - right.b;
  1354. result.a = this.a - right.a;
  1355. return this;
  1356. };
  1357. /**
  1358. * Creates a new Color4 with the current Color4 values multiplied by scale.
  1359. */
  1360. Color4.prototype.scale = function (scale) {
  1361. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  1362. };
  1363. /**
  1364. * Multiplies the current Color4 values by scale and stores the result in "result".
  1365. * Returns the Color4.
  1366. */
  1367. Color4.prototype.scaleToRef = function (scale, result) {
  1368. result.r = this.r * scale;
  1369. result.g = this.g * scale;
  1370. result.b = this.b * scale;
  1371. result.a = this.a * scale;
  1372. return this;
  1373. };
  1374. /**
  1375. * Clamps the rgb values by the min and max values and stores the result into "result".
  1376. * Returns the unmodified current Color4.
  1377. * @param min - minimum clamping value. Defaults to 0
  1378. * @param max - maximum clamping value. Defaults to 1
  1379. * @param result - color to store the result into.
  1380. * @returns - the original Color4
  1381. */
  1382. Color4.prototype.clampToRef = function (min, max, result) {
  1383. if (min === void 0) { min = 0; }
  1384. if (max === void 0) { max = 1; }
  1385. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1386. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1387. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1388. result.a = BABYLON.Scalar.Clamp(this.a, min, max);
  1389. return this;
  1390. };
  1391. /**
  1392. * Multipy an RGBA Color4 value by another and return a new Color4 object
  1393. * @param color The Color4 (RGBA) value to multiply by
  1394. * @returns A new Color4.
  1395. */
  1396. Color4.prototype.multiply = function (color) {
  1397. return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
  1398. };
  1399. /**
  1400. * Multipy an RGBA Color4 value by another and push the result in a reference value
  1401. * @param color The Color4 (RGBA) value to multiply by
  1402. * @param result The Color4 (RGBA) to fill the result in
  1403. * @returns the result Color4.
  1404. */
  1405. Color4.prototype.multiplyToRef = function (color, result) {
  1406. result.r = this.r * color.r;
  1407. result.g = this.g * color.g;
  1408. result.b = this.b * color.b;
  1409. result.a = this.a * color.a;
  1410. return result;
  1411. };
  1412. /**
  1413. * Returns a string with the Color4 values.
  1414. */
  1415. Color4.prototype.toString = function () {
  1416. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  1417. };
  1418. /**
  1419. * Returns the string "Color4"
  1420. */
  1421. Color4.prototype.getClassName = function () {
  1422. return "Color4";
  1423. };
  1424. /**
  1425. * Return the Color4 hash code as a number.
  1426. */
  1427. Color4.prototype.getHashCode = function () {
  1428. var hash = this.r || 0;
  1429. hash = (hash * 397) ^ (this.g || 0);
  1430. hash = (hash * 397) ^ (this.b || 0);
  1431. hash = (hash * 397) ^ (this.a || 0);
  1432. return hash;
  1433. };
  1434. /**
  1435. * Creates a new Color4 copied from the current one.
  1436. */
  1437. Color4.prototype.clone = function () {
  1438. return new Color4(this.r, this.g, this.b, this.a);
  1439. };
  1440. /**
  1441. * Copies the passed Color4 values into the current one.
  1442. * Returns the updated Color4.
  1443. */
  1444. Color4.prototype.copyFrom = function (source) {
  1445. this.r = source.r;
  1446. this.g = source.g;
  1447. this.b = source.b;
  1448. this.a = source.a;
  1449. return this;
  1450. };
  1451. /**
  1452. * Copies the passed float values into the current one.
  1453. * Returns the updated Color4.
  1454. */
  1455. Color4.prototype.copyFromFloats = function (r, g, b, a) {
  1456. this.r = r;
  1457. this.g = g;
  1458. this.b = b;
  1459. this.a = a;
  1460. return this;
  1461. };
  1462. /**
  1463. * Copies the passed float values into the current one.
  1464. * Returns the updated Color4.
  1465. */
  1466. Color4.prototype.set = function (r, g, b, a) {
  1467. return this.copyFromFloats(r, g, b, a);
  1468. };
  1469. /**
  1470. * Returns a string containing the hexadecimal Color4 code.
  1471. */
  1472. Color4.prototype.toHexString = function () {
  1473. var intR = (this.r * 255) | 0;
  1474. var intG = (this.g * 255) | 0;
  1475. var intB = (this.b * 255) | 0;
  1476. var intA = (this.a * 255) | 0;
  1477. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB) + BABYLON.Scalar.ToHex(intA);
  1478. };
  1479. /**
  1480. * Returns a new Color4 converted to linear space.
  1481. */
  1482. Color4.prototype.toLinearSpace = function () {
  1483. var convertedColor = new Color4();
  1484. this.toLinearSpaceToRef(convertedColor);
  1485. return convertedColor;
  1486. };
  1487. /**
  1488. * Converts the Color4 values to linear space and stores the result in "convertedColor".
  1489. * Returns the unmodified Color4.
  1490. */
  1491. Color4.prototype.toLinearSpaceToRef = function (convertedColor) {
  1492. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  1493. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  1494. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  1495. convertedColor.a = this.a;
  1496. return this;
  1497. };
  1498. /**
  1499. * Returns a new Color4 converted to gamma space.
  1500. */
  1501. Color4.prototype.toGammaSpace = function () {
  1502. var convertedColor = new Color4();
  1503. this.toGammaSpaceToRef(convertedColor);
  1504. return convertedColor;
  1505. };
  1506. /**
  1507. * Converts the Color4 values to gamma space and stores the result in "convertedColor".
  1508. * Returns the unmodified Color4.
  1509. */
  1510. Color4.prototype.toGammaSpaceToRef = function (convertedColor) {
  1511. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  1512. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  1513. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  1514. convertedColor.a = this.a;
  1515. return this;
  1516. };
  1517. // Statics
  1518. /**
  1519. * Creates a new Color4 from the valid hexadecimal value contained in the passed string.
  1520. */
  1521. Color4.FromHexString = function (hex) {
  1522. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  1523. //Tools.Warn("Color4.FromHexString must be called with a string like #FFFFFFFF");
  1524. return new Color4(0.0, 0.0, 0.0, 0.0);
  1525. }
  1526. var r = parseInt(hex.substring(1, 3), 16);
  1527. var g = parseInt(hex.substring(3, 5), 16);
  1528. var b = parseInt(hex.substring(5, 7), 16);
  1529. var a = parseInt(hex.substring(7, 9), 16);
  1530. return Color4.FromInts(r, g, b, a);
  1531. };
  1532. /**
  1533. * Creates a new Color4 object set with the linearly interpolated values of "amount" between the left Color4 and the right Color4.
  1534. */
  1535. Color4.Lerp = function (left, right, amount) {
  1536. var result = new Color4(0.0, 0.0, 0.0, 0.0);
  1537. Color4.LerpToRef(left, right, amount, result);
  1538. return result;
  1539. };
  1540. /**
  1541. * Set the passed "result" with the linearly interpolated values of "amount" between the left Color4 and the right Color4.
  1542. */
  1543. Color4.LerpToRef = function (left, right, amount, result) {
  1544. result.r = left.r + (right.r - left.r) * amount;
  1545. result.g = left.g + (right.g - left.g) * amount;
  1546. result.b = left.b + (right.b - left.b) * amount;
  1547. result.a = left.a + (right.a - left.a) * amount;
  1548. };
  1549. /**
  1550. * Creates a new Color4 from the starting index element of the passed array.
  1551. */
  1552. Color4.FromArray = function (array, offset) {
  1553. if (offset === void 0) { offset = 0; }
  1554. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  1555. };
  1556. /**
  1557. * Creates a new Color4 from the passed integers ( < 256 ).
  1558. */
  1559. Color4.FromInts = function (r, g, b, a) {
  1560. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  1561. };
  1562. Color4.CheckColors4 = function (colors, count) {
  1563. // Check if color3 was used
  1564. if (colors.length === count * 3) {
  1565. var colors4 = [];
  1566. for (var index = 0; index < colors.length; index += 3) {
  1567. var newIndex = (index / 3) * 4;
  1568. colors4[newIndex] = colors[index];
  1569. colors4[newIndex + 1] = colors[index + 1];
  1570. colors4[newIndex + 2] = colors[index + 2];
  1571. colors4[newIndex + 3] = 1.0;
  1572. }
  1573. return colors4;
  1574. }
  1575. return colors;
  1576. };
  1577. return Color4;
  1578. }());
  1579. BABYLON.Color4 = Color4;
  1580. var Vector2 = /** @class */ (function () {
  1581. /**
  1582. * Creates a new Vector2 from the passed x and y coordinates.
  1583. */
  1584. function Vector2(x, y) {
  1585. this.x = x;
  1586. this.y = y;
  1587. }
  1588. /**
  1589. * Returns a string with the Vector2 coordinates.
  1590. */
  1591. Vector2.prototype.toString = function () {
  1592. return "{X: " + this.x + " Y:" + this.y + "}";
  1593. };
  1594. /**
  1595. * Returns the string "Vector2"
  1596. */
  1597. Vector2.prototype.getClassName = function () {
  1598. return "Vector2";
  1599. };
  1600. /**
  1601. * Returns the Vector2 hash code as a number.
  1602. */
  1603. Vector2.prototype.getHashCode = function () {
  1604. var hash = this.x || 0;
  1605. hash = (hash * 397) ^ (this.y || 0);
  1606. return hash;
  1607. };
  1608. // Operators
  1609. /**
  1610. * Sets the Vector2 coordinates in the passed array or Float32Array from the passed index.
  1611. * Returns the Vector2.
  1612. */
  1613. Vector2.prototype.toArray = function (array, index) {
  1614. if (index === void 0) { index = 0; }
  1615. array[index] = this.x;
  1616. array[index + 1] = this.y;
  1617. return this;
  1618. };
  1619. /**
  1620. * Returns a new array with 2 elements : the Vector2 coordinates.
  1621. */
  1622. Vector2.prototype.asArray = function () {
  1623. var result = new Array();
  1624. this.toArray(result, 0);
  1625. return result;
  1626. };
  1627. /**
  1628. * Sets the Vector2 coordinates with the passed Vector2 coordinates.
  1629. * Returns the updated Vector2.
  1630. */
  1631. Vector2.prototype.copyFrom = function (source) {
  1632. this.x = source.x;
  1633. this.y = source.y;
  1634. return this;
  1635. };
  1636. /**
  1637. * Sets the Vector2 coordinates with the passed floats.
  1638. * Returns the updated Vector2.
  1639. */
  1640. Vector2.prototype.copyFromFloats = function (x, y) {
  1641. this.x = x;
  1642. this.y = y;
  1643. return this;
  1644. };
  1645. /**
  1646. * Sets the Vector2 coordinates with the passed floats.
  1647. * Returns the updated Vector2.
  1648. */
  1649. Vector2.prototype.set = function (x, y) {
  1650. return this.copyFromFloats(x, y);
  1651. };
  1652. /**
  1653. * Returns a new Vector2 set with the addition of the current Vector2 and the passed one coordinates.
  1654. */
  1655. Vector2.prototype.add = function (otherVector) {
  1656. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  1657. };
  1658. /**
  1659. * Sets the "result" coordinates with the addition of the current Vector2 and the passed one coordinates.
  1660. * Returns the Vector2.
  1661. */
  1662. Vector2.prototype.addToRef = function (otherVector, result) {
  1663. result.x = this.x + otherVector.x;
  1664. result.y = this.y + otherVector.y;
  1665. return this;
  1666. };
  1667. /**
  1668. * Set the Vector2 coordinates by adding the passed Vector2 coordinates.
  1669. * Returns the updated Vector2.
  1670. */
  1671. Vector2.prototype.addInPlace = function (otherVector) {
  1672. this.x += otherVector.x;
  1673. this.y += otherVector.y;
  1674. return this;
  1675. };
  1676. /**
  1677. * Returns a new Vector2 by adding the current Vector2 coordinates to the passed Vector3 x, y coordinates.
  1678. */
  1679. Vector2.prototype.addVector3 = function (otherVector) {
  1680. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  1681. };
  1682. /**
  1683. * Returns a new Vector2 set with the subtracted coordinates of the passed one from the current Vector2.
  1684. */
  1685. Vector2.prototype.subtract = function (otherVector) {
  1686. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  1687. };
  1688. /**
  1689. * Sets the "result" coordinates with the subtraction of the passed one from the current Vector2 coordinates.
  1690. * Returns the Vector2.
  1691. */
  1692. Vector2.prototype.subtractToRef = function (otherVector, result) {
  1693. result.x = this.x - otherVector.x;
  1694. result.y = this.y - otherVector.y;
  1695. return this;
  1696. };
  1697. /**
  1698. * Sets the current Vector2 coordinates by subtracting from it the passed one coordinates.
  1699. * Returns the updated Vector2.
  1700. */
  1701. Vector2.prototype.subtractInPlace = function (otherVector) {
  1702. this.x -= otherVector.x;
  1703. this.y -= otherVector.y;
  1704. return this;
  1705. };
  1706. /**
  1707. * Multiplies in place the current Vector2 coordinates by the passed ones.
  1708. * Returns the updated Vector2.
  1709. */
  1710. Vector2.prototype.multiplyInPlace = function (otherVector) {
  1711. this.x *= otherVector.x;
  1712. this.y *= otherVector.y;
  1713. return this;
  1714. };
  1715. /**
  1716. * Returns a new Vector2 set with the multiplication of the current Vector2 and the passed one coordinates.
  1717. */
  1718. Vector2.prototype.multiply = function (otherVector) {
  1719. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  1720. };
  1721. /**
  1722. * Sets "result" coordinates with the multiplication of the current Vector2 and the passed one coordinates.
  1723. * Returns the Vector2.
  1724. */
  1725. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  1726. result.x = this.x * otherVector.x;
  1727. result.y = this.y * otherVector.y;
  1728. return this;
  1729. };
  1730. /**
  1731. * Returns a new Vector2 set with the Vector2 coordinates multiplied by the passed floats.
  1732. */
  1733. Vector2.prototype.multiplyByFloats = function (x, y) {
  1734. return new Vector2(this.x * x, this.y * y);
  1735. };
  1736. /**
  1737. * Returns a new Vector2 set with the Vector2 coordinates divided by the passed one coordinates.
  1738. */
  1739. Vector2.prototype.divide = function (otherVector) {
  1740. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  1741. };
  1742. /**
  1743. * Sets the "result" coordinates with the Vector2 divided by the passed one coordinates.
  1744. * Returns the Vector2.
  1745. */
  1746. Vector2.prototype.divideToRef = function (otherVector, result) {
  1747. result.x = this.x / otherVector.x;
  1748. result.y = this.y / otherVector.y;
  1749. return this;
  1750. };
  1751. /**
  1752. * Divides the current Vector3 coordinates by the passed ones.
  1753. * Returns the updated Vector3.
  1754. */
  1755. Vector2.prototype.divideInPlace = function (otherVector) {
  1756. return this.divideToRef(otherVector, this);
  1757. };
  1758. /**
  1759. * Returns a new Vector2 with current Vector2 negated coordinates.
  1760. */
  1761. Vector2.prototype.negate = function () {
  1762. return new Vector2(-this.x, -this.y);
  1763. };
  1764. /**
  1765. * Multiply the Vector2 coordinates by scale.
  1766. * Returns the updated Vector2.
  1767. */
  1768. Vector2.prototype.scaleInPlace = function (scale) {
  1769. this.x *= scale;
  1770. this.y *= scale;
  1771. return this;
  1772. };
  1773. /**
  1774. * Returns a new Vector2 scaled by "scale" from the current Vector2.
  1775. */
  1776. Vector2.prototype.scale = function (scale) {
  1777. return new Vector2(this.x * scale, this.y * scale);
  1778. };
  1779. /**
  1780. * Boolean : True if the passed vector coordinates strictly equal the current Vector2 ones.
  1781. */
  1782. Vector2.prototype.equals = function (otherVector) {
  1783. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  1784. };
  1785. /**
  1786. * Boolean : True if the passed vector coordinates are close to the current ones by a distance of epsilon.
  1787. */
  1788. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  1789. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  1790. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon);
  1791. };
  1792. // Properties
  1793. /**
  1794. * Returns the vector length (float).
  1795. */
  1796. Vector2.prototype.length = function () {
  1797. return Math.sqrt(this.x * this.x + this.y * this.y);
  1798. };
  1799. /**
  1800. * Returns the vector squared length (float);
  1801. */
  1802. Vector2.prototype.lengthSquared = function () {
  1803. return (this.x * this.x + this.y * this.y);
  1804. };
  1805. // Methods
  1806. /**
  1807. * Normalize the vector.
  1808. * Returns the updated Vector2.
  1809. */
  1810. Vector2.prototype.normalize = function () {
  1811. var len = this.length();
  1812. if (len === 0)
  1813. return this;
  1814. var num = 1.0 / len;
  1815. this.x *= num;
  1816. this.y *= num;
  1817. return this;
  1818. };
  1819. /**
  1820. * Returns a new Vector2 copied from the Vector2.
  1821. */
  1822. Vector2.prototype.clone = function () {
  1823. return new Vector2(this.x, this.y);
  1824. };
  1825. // Statics
  1826. /**
  1827. * Returns a new Vector2(0, 0)
  1828. */
  1829. Vector2.Zero = function () {
  1830. return new Vector2(0, 0);
  1831. };
  1832. /**
  1833. * Returns a new Vector2(1, 1)
  1834. */
  1835. Vector2.One = function () {
  1836. return new Vector2(1, 1);
  1837. };
  1838. /**
  1839. * Returns a new Vector2 set from the passed index element of the passed array.
  1840. */
  1841. Vector2.FromArray = function (array, offset) {
  1842. if (offset === void 0) { offset = 0; }
  1843. return new Vector2(array[offset], array[offset + 1]);
  1844. };
  1845. /**
  1846. * Sets "result" from the passed index element of the passed array.
  1847. */
  1848. Vector2.FromArrayToRef = function (array, offset, result) {
  1849. result.x = array[offset];
  1850. result.y = array[offset + 1];
  1851. };
  1852. /**
  1853. * Retuns a new Vector2 located for "amount" (float) on the CatmullRom spline defined by the passed four Vector2.
  1854. */
  1855. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  1856. var squared = amount * amount;
  1857. var cubed = amount * squared;
  1858. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  1859. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  1860. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  1861. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  1862. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  1863. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  1864. return new Vector2(x, y);
  1865. };
  1866. /**
  1867. * 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".
  1868. * If a coordinate of "value" is lower than "min" coordinates, the returned Vector2 is given this "min" coordinate.
  1869. * If a coordinate of "value" is greater than "max" coordinates, the returned Vector2 is given this "max" coordinate.
  1870. */
  1871. Vector2.Clamp = function (value, min, max) {
  1872. var x = value.x;
  1873. x = (x > max.x) ? max.x : x;
  1874. x = (x < min.x) ? min.x : x;
  1875. var y = value.y;
  1876. y = (y > max.y) ? max.y : y;
  1877. y = (y < min.y) ? min.y : y;
  1878. return new Vector2(x, y);
  1879. };
  1880. /**
  1881. * Returns a new Vector2 located for "amount" (float) on the Hermite spline defined by the vectors "value1", "value3", "tangent1", "tangent2".
  1882. */
  1883. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  1884. var squared = amount * amount;
  1885. var cubed = amount * squared;
  1886. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  1887. var part2 = (-2.0 * cubed) + (3.0 * squared);
  1888. var part3 = (cubed - (2.0 * squared)) + amount;
  1889. var part4 = cubed - squared;
  1890. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  1891. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  1892. return new Vector2(x, y);
  1893. };
  1894. /**
  1895. * Returns a new Vector2 located for "amount" (float) on the linear interpolation between the vector "start" adn the vector "end".
  1896. */
  1897. Vector2.Lerp = function (start, end, amount) {
  1898. var x = start.x + ((end.x - start.x) * amount);
  1899. var y = start.y + ((end.y - start.y) * amount);
  1900. return new Vector2(x, y);
  1901. };
  1902. /**
  1903. * Returns the dot product (float) of the vector "left" and the vector "right".
  1904. */
  1905. Vector2.Dot = function (left, right) {
  1906. return left.x * right.x + left.y * right.y;
  1907. };
  1908. /**
  1909. * Returns a new Vector2 equal to the normalized passed vector.
  1910. */
  1911. Vector2.Normalize = function (vector) {
  1912. var newVector = vector.clone();
  1913. newVector.normalize();
  1914. return newVector;
  1915. };
  1916. /**
  1917. * Returns a new Vecto2 set with the minimal coordinate values from the "left" and "right" vectors.
  1918. */
  1919. Vector2.Minimize = function (left, right) {
  1920. var x = (left.x < right.x) ? left.x : right.x;
  1921. var y = (left.y < right.y) ? left.y : right.y;
  1922. return new Vector2(x, y);
  1923. };
  1924. /**
  1925. * Returns a new Vecto2 set with the maximal coordinate values from the "left" and "right" vectors.
  1926. */
  1927. Vector2.Maximize = function (left, right) {
  1928. var x = (left.x > right.x) ? left.x : right.x;
  1929. var y = (left.y > right.y) ? left.y : right.y;
  1930. return new Vector2(x, y);
  1931. };
  1932. /**
  1933. * Returns a new Vecto2 set with the transformed coordinates of the passed vector by the passed transformation matrix.
  1934. */
  1935. Vector2.Transform = function (vector, transformation) {
  1936. var r = Vector2.Zero();
  1937. Vector2.TransformToRef(vector, transformation, r);
  1938. return r;
  1939. };
  1940. /**
  1941. * Transforms the passed vector coordinates by the passed transformation matrix and stores the result in the vector "result" coordinates.
  1942. */
  1943. Vector2.TransformToRef = function (vector, transformation, result) {
  1944. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
  1945. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
  1946. result.x = x;
  1947. result.y = y;
  1948. };
  1949. /**
  1950. * Boolean : True if the point "p" is in the triangle defined by the vertors "p0", "p1", "p2"
  1951. */
  1952. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  1953. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  1954. var sign = a < 0 ? -1 : 1;
  1955. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  1956. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  1957. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  1958. };
  1959. /**
  1960. * Returns the distance (float) between the vectors "value1" and "value2".
  1961. */
  1962. Vector2.Distance = function (value1, value2) {
  1963. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  1964. };
  1965. /**
  1966. * Returns the squared distance (float) between the vectors "value1" and "value2".
  1967. */
  1968. Vector2.DistanceSquared = function (value1, value2) {
  1969. var x = value1.x - value2.x;
  1970. var y = value1.y - value2.y;
  1971. return (x * x) + (y * y);
  1972. };
  1973. /**
  1974. * Returns a new Vecto2 located at the center of the vectors "value1" and "value2".
  1975. */
  1976. Vector2.Center = function (value1, value2) {
  1977. var center = value1.add(value2);
  1978. center.scaleInPlace(0.5);
  1979. return center;
  1980. };
  1981. /**
  1982. * Returns the shortest distance (float) between the point "p" and the segment defined by the two points "segA" and "segB".
  1983. */
  1984. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  1985. var l2 = Vector2.DistanceSquared(segA, segB);
  1986. if (l2 === 0.0) {
  1987. return Vector2.Distance(p, segA);
  1988. }
  1989. var v = segB.subtract(segA);
  1990. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  1991. var proj = segA.add(v.multiplyByFloats(t, t));
  1992. return Vector2.Distance(p, proj);
  1993. };
  1994. return Vector2;
  1995. }());
  1996. BABYLON.Vector2 = Vector2;
  1997. var Vector3 = /** @class */ (function () {
  1998. /**
  1999. * Creates a new Vector3 object from the passed x, y, z (floats) coordinates.
  2000. * A Vector3 is the main object used in 3D geometry.
  2001. * It can represent etiher the coordinates of a point the space, either a direction.
  2002. */
  2003. function Vector3(x, y, z) {
  2004. this.x = x;
  2005. this.y = y;
  2006. this.z = z;
  2007. }
  2008. /**
  2009. * Returns a string with the Vector3 coordinates.
  2010. */
  2011. Vector3.prototype.toString = function () {
  2012. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  2013. };
  2014. /**
  2015. * Returns the string "Vector3"
  2016. */
  2017. Vector3.prototype.getClassName = function () {
  2018. return "Vector3";
  2019. };
  2020. /**
  2021. * Returns the Vector hash code.
  2022. */
  2023. Vector3.prototype.getHashCode = function () {
  2024. var hash = this.x || 0;
  2025. hash = (hash * 397) ^ (this.y || 0);
  2026. hash = (hash * 397) ^ (this.z || 0);
  2027. return hash;
  2028. };
  2029. // Operators
  2030. /**
  2031. * Returns a new array with three elements : the coordinates the Vector3.
  2032. */
  2033. Vector3.prototype.asArray = function () {
  2034. var result = [];
  2035. this.toArray(result, 0);
  2036. return result;
  2037. };
  2038. /**
  2039. * Populates the passed array or Float32Array from the passed index with the successive coordinates of the Vector3.
  2040. * Returns the Vector3.
  2041. */
  2042. Vector3.prototype.toArray = function (array, index) {
  2043. if (index === void 0) { index = 0; }
  2044. array[index] = this.x;
  2045. array[index + 1] = this.y;
  2046. array[index + 2] = this.z;
  2047. return this;
  2048. };
  2049. /**
  2050. * Returns a new Quaternion object, computed from the Vector3 coordinates.
  2051. */
  2052. Vector3.prototype.toQuaternion = function () {
  2053. var result = new Quaternion(0.0, 0.0, 0.0, 1.0);
  2054. var cosxPlusz = Math.cos((this.x + this.z) * 0.5);
  2055. var sinxPlusz = Math.sin((this.x + this.z) * 0.5);
  2056. var coszMinusx = Math.cos((this.z - this.x) * 0.5);
  2057. var sinzMinusx = Math.sin((this.z - this.x) * 0.5);
  2058. var cosy = Math.cos(this.y * 0.5);
  2059. var siny = Math.sin(this.y * 0.5);
  2060. result.x = coszMinusx * siny;
  2061. result.y = -sinzMinusx * siny;
  2062. result.z = sinxPlusz * cosy;
  2063. result.w = cosxPlusz * cosy;
  2064. return result;
  2065. };
  2066. /**
  2067. * Adds the passed vector to the current Vector3.
  2068. * Returns the updated Vector3.
  2069. */
  2070. Vector3.prototype.addInPlace = function (otherVector) {
  2071. this.x += otherVector.x;
  2072. this.y += otherVector.y;
  2073. this.z += otherVector.z;
  2074. return this;
  2075. };
  2076. /**
  2077. * Returns a new Vector3, result of the addition the current Vector3 and the passed vector.
  2078. */
  2079. Vector3.prototype.add = function (otherVector) {
  2080. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  2081. };
  2082. /**
  2083. * Adds the current Vector3 to the passed one and stores the result in the vector "result".
  2084. * Returns the current Vector3.
  2085. */
  2086. Vector3.prototype.addToRef = function (otherVector, result) {
  2087. result.x = this.x + otherVector.x;
  2088. result.y = this.y + otherVector.y;
  2089. result.z = this.z + otherVector.z;
  2090. return this;
  2091. };
  2092. /**
  2093. * Subtract the passed vector from the current Vector3.
  2094. * Returns the updated Vector3.
  2095. */
  2096. Vector3.prototype.subtractInPlace = function (otherVector) {
  2097. this.x -= otherVector.x;
  2098. this.y -= otherVector.y;
  2099. this.z -= otherVector.z;
  2100. return this;
  2101. };
  2102. /**
  2103. * Returns a new Vector3, result of the subtraction of the passed vector from the current Vector3.
  2104. */
  2105. Vector3.prototype.subtract = function (otherVector) {
  2106. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  2107. };
  2108. /**
  2109. * Subtracts the passed vector from the current Vector3 and stores the result in the vector "result".
  2110. * Returns the current Vector3.
  2111. */
  2112. Vector3.prototype.subtractToRef = function (otherVector, result) {
  2113. result.x = this.x - otherVector.x;
  2114. result.y = this.y - otherVector.y;
  2115. result.z = this.z - otherVector.z;
  2116. return this;
  2117. };
  2118. /**
  2119. * Returns a new Vector3 set with the subtraction of the passed floats from the current Vector3 coordinates.
  2120. */
  2121. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  2122. return new Vector3(this.x - x, this.y - y, this.z - z);
  2123. };
  2124. /**
  2125. * Subtracts the passed floats from the current Vector3 coordinates and set the passed vector "result" with this result.
  2126. * Returns the current Vector3.
  2127. */
  2128. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  2129. result.x = this.x - x;
  2130. result.y = this.y - y;
  2131. result.z = this.z - z;
  2132. return this;
  2133. };
  2134. /**
  2135. * Returns a new Vector3 set with the current Vector3 negated coordinates.
  2136. */
  2137. Vector3.prototype.negate = function () {
  2138. return new Vector3(-this.x, -this.y, -this.z);
  2139. };
  2140. /**
  2141. * Multiplies the Vector3 coordinates by the float "scale".
  2142. * Returns the updated Vector3.
  2143. */
  2144. Vector3.prototype.scaleInPlace = function (scale) {
  2145. this.x *= scale;
  2146. this.y *= scale;
  2147. this.z *= scale;
  2148. return this;
  2149. };
  2150. /**
  2151. * Returns a new Vector3 set with the current Vector3 coordinates multiplied by the float "scale".
  2152. */
  2153. Vector3.prototype.scale = function (scale) {
  2154. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  2155. };
  2156. /**
  2157. * Multiplies the current Vector3 coordinates by the float "scale" and stores the result in the passed vector "result" coordinates.
  2158. * Returns the current Vector3.
  2159. */
  2160. Vector3.prototype.scaleToRef = function (scale, result) {
  2161. result.x = this.x * scale;
  2162. result.y = this.y * scale;
  2163. result.z = this.z * scale;
  2164. return this;
  2165. };
  2166. /**
  2167. * Boolean : True if the current Vector3 and the passed vector coordinates are strictly equal.
  2168. */
  2169. Vector3.prototype.equals = function (otherVector) {
  2170. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  2171. };
  2172. /**
  2173. * Boolean : True if the current Vector3 and the passed vector coordinates are distant less than epsilon.
  2174. */
  2175. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2176. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2177. 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);
  2178. };
  2179. /**
  2180. * Boolean : True if the current Vector3 coordinate equal the passed floats.
  2181. */
  2182. Vector3.prototype.equalsToFloats = function (x, y, z) {
  2183. return this.x === x && this.y === y && this.z === z;
  2184. };
  2185. /**
  2186. * Muliplies the current Vector3 coordinates by the passed ones.
  2187. * Returns the updated Vector3.
  2188. */
  2189. Vector3.prototype.multiplyInPlace = function (otherVector) {
  2190. this.x *= otherVector.x;
  2191. this.y *= otherVector.y;
  2192. this.z *= otherVector.z;
  2193. return this;
  2194. };
  2195. /**
  2196. * Returns a new Vector3, result of the multiplication of the current Vector3 by the passed vector.
  2197. */
  2198. Vector3.prototype.multiply = function (otherVector) {
  2199. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  2200. };
  2201. /**
  2202. * Multiplies the current Vector3 by the passed one and stores the result in the passed vector "result".
  2203. * Returns the current Vector3.
  2204. */
  2205. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  2206. result.x = this.x * otherVector.x;
  2207. result.y = this.y * otherVector.y;
  2208. result.z = this.z * otherVector.z;
  2209. return this;
  2210. };
  2211. /**
  2212. * Returns a new Vector3 set witth the result of the mulliplication of the current Vector3 coordinates by the passed floats.
  2213. */
  2214. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  2215. return new Vector3(this.x * x, this.y * y, this.z * z);
  2216. };
  2217. /**
  2218. * Returns a new Vector3 set witth the result of the division of the current Vector3 coordinates by the passed ones.
  2219. */
  2220. Vector3.prototype.divide = function (otherVector) {
  2221. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  2222. };
  2223. /**
  2224. * Divides the current Vector3 coordinates by the passed ones and stores the result in the passed vector "result".
  2225. * Returns the current Vector3.
  2226. */
  2227. Vector3.prototype.divideToRef = function (otherVector, result) {
  2228. result.x = this.x / otherVector.x;
  2229. result.y = this.y / otherVector.y;
  2230. result.z = this.z / otherVector.z;
  2231. return this;
  2232. };
  2233. /**
  2234. * Divides the current Vector3 coordinates by the passed ones.
  2235. * Returns the updated Vector3.
  2236. */
  2237. Vector3.prototype.divideInPlace = function (otherVector) {
  2238. return this.divideToRef(otherVector, this);
  2239. };
  2240. /**
  2241. * Updates the current Vector3 with the minimal coordinate values between its and the passed vector ones.
  2242. * Returns the updated Vector3.
  2243. */
  2244. Vector3.prototype.MinimizeInPlace = function (other) {
  2245. if (other.x < this.x)
  2246. this.x = other.x;
  2247. if (other.y < this.y)
  2248. this.y = other.y;
  2249. if (other.z < this.z)
  2250. this.z = other.z;
  2251. return this;
  2252. };
  2253. /**
  2254. * Updates the current Vector3 with the maximal coordinate values between its and the passed vector ones.
  2255. * Returns the updated Vector3.
  2256. */
  2257. Vector3.prototype.MaximizeInPlace = function (other) {
  2258. if (other.x > this.x)
  2259. this.x = other.x;
  2260. if (other.y > this.y)
  2261. this.y = other.y;
  2262. if (other.z > this.z)
  2263. this.z = other.z;
  2264. return this;
  2265. };
  2266. Object.defineProperty(Vector3.prototype, "isNonUniform", {
  2267. /**
  2268. * Return true is the vector is non uniform meaning x, y or z are not all the same.
  2269. */
  2270. get: function () {
  2271. var absX = Math.abs(this.x);
  2272. var absY = Math.abs(this.y);
  2273. if (absX !== absY) {
  2274. return true;
  2275. }
  2276. var absZ = Math.abs(this.z);
  2277. if (absX !== absZ) {
  2278. return true;
  2279. }
  2280. if (absY !== absZ) {
  2281. return true;
  2282. }
  2283. return false;
  2284. },
  2285. enumerable: true,
  2286. configurable: true
  2287. });
  2288. // Properties
  2289. /**
  2290. * Returns the length of the Vector3 (float).
  2291. */
  2292. Vector3.prototype.length = function () {
  2293. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  2294. };
  2295. /**
  2296. * Returns the squared length of the Vector3 (float).
  2297. */
  2298. Vector3.prototype.lengthSquared = function () {
  2299. return (this.x * this.x + this.y * this.y + this.z * this.z);
  2300. };
  2301. /**
  2302. * Normalize the current Vector3.
  2303. * Returns the updated Vector3.
  2304. * /!\ In place operation.
  2305. */
  2306. Vector3.prototype.normalize = function () {
  2307. var len = this.length();
  2308. if (len === 0 || len === 1.0)
  2309. return this;
  2310. var num = 1.0 / len;
  2311. this.x *= num;
  2312. this.y *= num;
  2313. this.z *= num;
  2314. return this;
  2315. };
  2316. /**
  2317. * Normalize the current Vector3 to a new vector.
  2318. * @returns the new Vector3.
  2319. */
  2320. Vector3.prototype.normalizeToNew = function () {
  2321. var normalized = new Vector3(0, 0, 0);
  2322. this.normalizeToRef(normalized);
  2323. return normalized;
  2324. };
  2325. /**
  2326. * Normalize the current Vector3 to the reference.
  2327. * @param the reference to update.
  2328. * @returns the updated Vector3.
  2329. */
  2330. Vector3.prototype.normalizeToRef = function (reference) {
  2331. var len = this.length();
  2332. if (len === 0 || len === 1.0) {
  2333. reference.set(this.x, this.y, this.z);
  2334. return reference;
  2335. }
  2336. var scale = 1.0 / len;
  2337. this.scaleToRef(scale, reference);
  2338. return reference;
  2339. };
  2340. /**
  2341. * Returns a new Vector3 copied from the current Vector3.
  2342. */
  2343. Vector3.prototype.clone = function () {
  2344. return new Vector3(this.x, this.y, this.z);
  2345. };
  2346. /**
  2347. * Copies the passed vector coordinates to the current Vector3 ones.
  2348. * Returns the updated Vector3.
  2349. */
  2350. Vector3.prototype.copyFrom = function (source) {
  2351. this.x = source.x;
  2352. this.y = source.y;
  2353. this.z = source.z;
  2354. return this;
  2355. };
  2356. /**
  2357. * Copies the passed floats to the current Vector3 coordinates.
  2358. * Returns the updated Vector3.
  2359. */
  2360. Vector3.prototype.copyFromFloats = function (x, y, z) {
  2361. this.x = x;
  2362. this.y = y;
  2363. this.z = z;
  2364. return this;
  2365. };
  2366. /**
  2367. * Copies the passed floats to the current Vector3 coordinates.
  2368. * Returns the updated Vector3.
  2369. */
  2370. Vector3.prototype.set = function (x, y, z) {
  2371. return this.copyFromFloats(x, y, z);
  2372. };
  2373. // Statics
  2374. /**
  2375. *
  2376. */
  2377. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  2378. var d0 = Vector3.Dot(vector0, axis) - size;
  2379. var d1 = Vector3.Dot(vector1, axis) - size;
  2380. var s = d0 / (d0 - d1);
  2381. return s;
  2382. };
  2383. /**
  2384. * Get angle between two vectors.
  2385. * @param vector0 angle between vector0 and vector1
  2386. * @param vector1 angle between vector0 and vector1
  2387. * @param normal direction of the normal.
  2388. * @return the angle between vector0 and vector1.
  2389. */
  2390. Vector3.GetAngleBetweenVectors = function (vector0, vector1, normal) {
  2391. var v0 = vector0.clone().normalize();
  2392. var v1 = vector1.clone().normalize();
  2393. var dot = Vector3.Dot(v0, v1);
  2394. var n = Vector3.Cross(v0, v1);
  2395. if (Vector3.Dot(n, normal) > 0) {
  2396. return Math.acos(dot);
  2397. }
  2398. return -Math.acos(dot);
  2399. };
  2400. /**
  2401. * Returns a new Vector3 set from the index "offset" of the passed array.
  2402. */
  2403. Vector3.FromArray = function (array, offset) {
  2404. if (!offset) {
  2405. offset = 0;
  2406. }
  2407. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  2408. };
  2409. /**
  2410. * Returns a new Vector3 set from the index "offset" of the passed Float32Array.
  2411. * This function is deprecated. Use FromArray instead.
  2412. */
  2413. Vector3.FromFloatArray = function (array, offset) {
  2414. return Vector3.FromArray(array, offset);
  2415. };
  2416. /**
  2417. * Sets the passed vector "result" with the element values from the index "offset" of the passed array.
  2418. */
  2419. Vector3.FromArrayToRef = function (array, offset, result) {
  2420. result.x = array[offset];
  2421. result.y = array[offset + 1];
  2422. result.z = array[offset + 2];
  2423. };
  2424. /**
  2425. * Sets the passed vector "result" with the element values from the index "offset" of the passed Float32Array.
  2426. * This function is deprecated. Use FromArrayToRef instead.
  2427. */
  2428. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  2429. return Vector3.FromArrayToRef(array, offset, result);
  2430. };
  2431. /**
  2432. * Sets the passed vector "result" with the passed floats.
  2433. */
  2434. Vector3.FromFloatsToRef = function (x, y, z, result) {
  2435. result.x = x;
  2436. result.y = y;
  2437. result.z = z;
  2438. };
  2439. /**
  2440. * Returns a new Vector3 set to (0.0, 0.0, 0.0).
  2441. */
  2442. Vector3.Zero = function () {
  2443. return new Vector3(0.0, 0.0, 0.0);
  2444. };
  2445. /**
  2446. * Returns a new Vector3 set to (1.0, 1.0, 1.0).
  2447. */
  2448. Vector3.One = function () {
  2449. return new Vector3(1.0, 1.0, 1.0);
  2450. };
  2451. /**
  2452. * Returns a new Vector3 set to (0.0, 1.0, 0.0)
  2453. */
  2454. Vector3.Up = function () {
  2455. return new Vector3(0.0, 1.0, 0.0);
  2456. };
  2457. /**
  2458. * Returns a new Vector3 set to (0.0, 0.0, 1.0)
  2459. */
  2460. Vector3.Forward = function () {
  2461. return new Vector3(0.0, 0.0, 1.0);
  2462. };
  2463. /**
  2464. * Returns a new Vector3 set to (1.0, 0.0, 0.0)
  2465. */
  2466. Vector3.Right = function () {
  2467. return new Vector3(1.0, 0.0, 0.0);
  2468. };
  2469. /**
  2470. * Returns a new Vector3 set to (-1.0, 0.0, 0.0)
  2471. */
  2472. Vector3.Left = function () {
  2473. return new Vector3(-1.0, 0.0, 0.0);
  2474. };
  2475. /**
  2476. * Returns a new Vector3 set with the result of the transformation by the passed matrix of the passed vector.
  2477. * This method computes tranformed coordinates only, not transformed direction vectors.
  2478. */
  2479. Vector3.TransformCoordinates = function (vector, transformation) {
  2480. var result = Vector3.Zero();
  2481. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  2482. return result;
  2483. };
  2484. /**
  2485. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed vector.
  2486. * This method computes tranformed coordinates only, not transformed direction vectors.
  2487. */
  2488. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  2489. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  2490. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  2491. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  2492. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  2493. result.x = x / w;
  2494. result.y = y / w;
  2495. result.z = z / w;
  2496. };
  2497. /**
  2498. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed floats (x, y, z).
  2499. * This method computes tranformed coordinates only, not transformed direction vectors.
  2500. */
  2501. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  2502. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  2503. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  2504. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  2505. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  2506. result.x = rx / rw;
  2507. result.y = ry / rw;
  2508. result.z = rz / rw;
  2509. };
  2510. /**
  2511. * Returns a new Vector3 set with the result of the normal transformation by the passed matrix of the passed vector.
  2512. * This methods computes transformed normalized direction vectors only.
  2513. */
  2514. Vector3.TransformNormal = function (vector, transformation) {
  2515. var result = Vector3.Zero();
  2516. Vector3.TransformNormalToRef(vector, transformation, result);
  2517. return result;
  2518. };
  2519. /**
  2520. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector.
  2521. * This methods computes transformed normalized direction vectors only.
  2522. */
  2523. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  2524. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  2525. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  2526. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  2527. result.x = x;
  2528. result.y = y;
  2529. result.z = z;
  2530. };
  2531. /**
  2532. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z).
  2533. * This methods computes transformed normalized direction vectors only.
  2534. */
  2535. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  2536. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  2537. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  2538. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  2539. };
  2540. /**
  2541. * Returns a new Vector3 located for "amount" on the CatmullRom interpolation spline defined by the vectors "value1", "value2", "value3", "value4".
  2542. */
  2543. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  2544. var squared = amount * amount;
  2545. var cubed = amount * squared;
  2546. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  2547. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  2548. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  2549. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  2550. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  2551. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  2552. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  2553. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  2554. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  2555. return new Vector3(x, y, z);
  2556. };
  2557. /**
  2558. * 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".
  2559. * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one.
  2560. * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one.
  2561. */
  2562. Vector3.Clamp = function (value, min, max) {
  2563. var x = value.x;
  2564. x = (x > max.x) ? max.x : x;
  2565. x = (x < min.x) ? min.x : x;
  2566. var y = value.y;
  2567. y = (y > max.y) ? max.y : y;
  2568. y = (y < min.y) ? min.y : y;
  2569. var z = value.z;
  2570. z = (z > max.z) ? max.z : z;
  2571. z = (z < min.z) ? min.z : z;
  2572. return new Vector3(x, y, z);
  2573. };
  2574. /**
  2575. * Returns a new Vector3 located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2".
  2576. */
  2577. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  2578. var squared = amount * amount;
  2579. var cubed = amount * squared;
  2580. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  2581. var part2 = (-2.0 * cubed) + (3.0 * squared);
  2582. var part3 = (cubed - (2.0 * squared)) + amount;
  2583. var part4 = cubed - squared;
  2584. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  2585. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  2586. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  2587. return new Vector3(x, y, z);
  2588. };
  2589. /**
  2590. * Returns a new Vector3 located for "amount" (float) on the linear interpolation between the vectors "start" and "end".
  2591. */
  2592. Vector3.Lerp = function (start, end, amount) {
  2593. var result = new Vector3(0, 0, 0);
  2594. Vector3.LerpToRef(start, end, amount, result);
  2595. return result;
  2596. };
  2597. /**
  2598. * Sets the passed vector "result" with the result of the linear interpolation from the vector "start" for "amount" to the vector "end".
  2599. */
  2600. Vector3.LerpToRef = function (start, end, amount, result) {
  2601. result.x = start.x + ((end.x - start.x) * amount);
  2602. result.y = start.y + ((end.y - start.y) * amount);
  2603. result.z = start.z + ((end.z - start.z) * amount);
  2604. };
  2605. /**
  2606. * Returns the dot product (float) between the vectors "left" and "right".
  2607. */
  2608. Vector3.Dot = function (left, right) {
  2609. return (left.x * right.x + left.y * right.y + left.z * right.z);
  2610. };
  2611. /**
  2612. * Returns a new Vector3 as the cross product of the vectors "left" and "right".
  2613. * The cross product is then orthogonal to both "left" and "right".
  2614. */
  2615. Vector3.Cross = function (left, right) {
  2616. var result = Vector3.Zero();
  2617. Vector3.CrossToRef(left, right, result);
  2618. return result;
  2619. };
  2620. /**
  2621. * Sets the passed vector "result" with the cross product of "left" and "right".
  2622. * The cross product is then orthogonal to both "left" and "right".
  2623. */
  2624. Vector3.CrossToRef = function (left, right, result) {
  2625. MathTmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  2626. MathTmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  2627. MathTmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  2628. result.copyFrom(MathTmp.Vector3[0]);
  2629. };
  2630. /**
  2631. * Returns a new Vector3 as the normalization of the passed vector.
  2632. */
  2633. Vector3.Normalize = function (vector) {
  2634. var result = Vector3.Zero();
  2635. Vector3.NormalizeToRef(vector, result);
  2636. return result;
  2637. };
  2638. /**
  2639. * Sets the passed vector "result" with the normalization of the passed first vector.
  2640. */
  2641. Vector3.NormalizeToRef = function (vector, result) {
  2642. result.copyFrom(vector);
  2643. result.normalize();
  2644. };
  2645. Vector3.Project = function (vector, world, transform, viewport) {
  2646. var cw = viewport.width;
  2647. var ch = viewport.height;
  2648. var cx = viewport.x;
  2649. var cy = viewport.y;
  2650. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  2651. 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);
  2652. var matrix = MathTmp.Matrix[0];
  2653. world.multiplyToRef(transform, matrix);
  2654. matrix.multiplyToRef(viewportMatrix, matrix);
  2655. return Vector3.TransformCoordinates(vector, matrix);
  2656. };
  2657. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  2658. var matrix = MathTmp.Matrix[0];
  2659. world.multiplyToRef(transform, matrix);
  2660. matrix.invert();
  2661. source.x = source.x / viewportWidth * 2 - 1;
  2662. source.y = -(source.y / viewportHeight * 2 - 1);
  2663. var vector = Vector3.TransformCoordinates(source, matrix);
  2664. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  2665. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  2666. vector = vector.scale(1.0 / num);
  2667. }
  2668. return vector;
  2669. };
  2670. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  2671. var result = Vector3.Zero();
  2672. Vector3.UnprojectToRef(source, viewportWidth, viewportHeight, world, view, projection, result);
  2673. return result;
  2674. };
  2675. Vector3.UnprojectToRef = function (source, viewportWidth, viewportHeight, world, view, projection, result) {
  2676. Vector3.UnprojectFloatsToRef(source.x, source.y, source.z, viewportWidth, viewportHeight, world, view, projection, result);
  2677. };
  2678. Vector3.UnprojectFloatsToRef = function (sourceX, sourceY, sourceZ, viewportWidth, viewportHeight, world, view, projection, result) {
  2679. var matrix = MathTmp.Matrix[0];
  2680. world.multiplyToRef(view, matrix);
  2681. matrix.multiplyToRef(projection, matrix);
  2682. matrix.invert();
  2683. var screenSource = MathTmp.Vector3[0];
  2684. screenSource.x = sourceX / viewportWidth * 2 - 1;
  2685. screenSource.y = -(sourceY / viewportHeight * 2 - 1);
  2686. screenSource.z = 2 * sourceZ - 1.0;
  2687. Vector3.TransformCoordinatesToRef(screenSource, matrix, result);
  2688. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  2689. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  2690. result.scaleInPlace(1.0 / num);
  2691. }
  2692. };
  2693. Vector3.Minimize = function (left, right) {
  2694. var min = left.clone();
  2695. min.MinimizeInPlace(right);
  2696. return min;
  2697. };
  2698. Vector3.Maximize = function (left, right) {
  2699. var max = left.clone();
  2700. max.MaximizeInPlace(right);
  2701. return max;
  2702. };
  2703. /**
  2704. * Returns the distance (float) between the vectors "value1" and "value2".
  2705. */
  2706. Vector3.Distance = function (value1, value2) {
  2707. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  2708. };
  2709. /**
  2710. * Returns the squared distance (float) between the vectors "value1" and "value2".
  2711. */
  2712. Vector3.DistanceSquared = function (value1, value2) {
  2713. var x = value1.x - value2.x;
  2714. var y = value1.y - value2.y;
  2715. var z = value1.z - value2.z;
  2716. return (x * x) + (y * y) + (z * z);
  2717. };
  2718. /**
  2719. * Returns a new Vector3 located at the center between "value1" and "value2".
  2720. */
  2721. Vector3.Center = function (value1, value2) {
  2722. var center = value1.add(value2);
  2723. center.scaleInPlace(0.5);
  2724. return center;
  2725. };
  2726. /**
  2727. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  2728. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  2729. * to something in order to rotate it from its local system to the given target system.
  2730. * Note : axis1, axis2 and axis3 are normalized during this operation.
  2731. * Returns a new Vector3.
  2732. */
  2733. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  2734. var rotation = Vector3.Zero();
  2735. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  2736. return rotation;
  2737. };
  2738. /**
  2739. * The same than RotationFromAxis but updates the passed ref Vector3 parameter instead of returning a new Vector3.
  2740. */
  2741. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  2742. var quat = MathTmp.Quaternion[0];
  2743. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  2744. quat.toEulerAnglesToRef(ref);
  2745. };
  2746. return Vector3;
  2747. }());
  2748. BABYLON.Vector3 = Vector3;
  2749. //Vector4 class created for EulerAngle class conversion to Quaternion
  2750. var Vector4 = /** @class */ (function () {
  2751. /**
  2752. * Creates a Vector4 object from the passed floats.
  2753. */
  2754. function Vector4(x, y, z, w) {
  2755. this.x = x;
  2756. this.y = y;
  2757. this.z = z;
  2758. this.w = w;
  2759. }
  2760. /**
  2761. * Returns the string with the Vector4 coordinates.
  2762. */
  2763. Vector4.prototype.toString = function () {
  2764. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  2765. };
  2766. /**
  2767. * Returns the string "Vector4".
  2768. */
  2769. Vector4.prototype.getClassName = function () {
  2770. return "Vector4";
  2771. };
  2772. /**
  2773. * Returns the Vector4 hash code.
  2774. */
  2775. Vector4.prototype.getHashCode = function () {
  2776. var hash = this.x || 0;
  2777. hash = (hash * 397) ^ (this.y || 0);
  2778. hash = (hash * 397) ^ (this.z || 0);
  2779. hash = (hash * 397) ^ (this.w || 0);
  2780. return hash;
  2781. };
  2782. // Operators
  2783. /**
  2784. * Returns a new array populated with 4 elements : the Vector4 coordinates.
  2785. */
  2786. Vector4.prototype.asArray = function () {
  2787. var result = new Array();
  2788. this.toArray(result, 0);
  2789. return result;
  2790. };
  2791. /**
  2792. * Populates the passed array from the passed index with the Vector4 coordinates.
  2793. * Returns the Vector4.
  2794. */
  2795. Vector4.prototype.toArray = function (array, index) {
  2796. if (index === undefined) {
  2797. index = 0;
  2798. }
  2799. array[index] = this.x;
  2800. array[index + 1] = this.y;
  2801. array[index + 2] = this.z;
  2802. array[index + 3] = this.w;
  2803. return this;
  2804. };
  2805. /**
  2806. * Adds the passed vector to the current Vector4.
  2807. * Returns the updated Vector4.
  2808. */
  2809. Vector4.prototype.addInPlace = function (otherVector) {
  2810. this.x += otherVector.x;
  2811. this.y += otherVector.y;
  2812. this.z += otherVector.z;
  2813. this.w += otherVector.w;
  2814. return this;
  2815. };
  2816. /**
  2817. * Returns a new Vector4 as the result of the addition of the current Vector4 and the passed one.
  2818. */
  2819. Vector4.prototype.add = function (otherVector) {
  2820. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  2821. };
  2822. /**
  2823. * Updates the passed vector "result" with the result of the addition of the current Vector4 and the passed one.
  2824. * Returns the current Vector4.
  2825. */
  2826. Vector4.prototype.addToRef = function (otherVector, result) {
  2827. result.x = this.x + otherVector.x;
  2828. result.y = this.y + otherVector.y;
  2829. result.z = this.z + otherVector.z;
  2830. result.w = this.w + otherVector.w;
  2831. return this;
  2832. };
  2833. /**
  2834. * Subtract in place the passed vector from the current Vector4.
  2835. * Returns the updated Vector4.
  2836. */
  2837. Vector4.prototype.subtractInPlace = function (otherVector) {
  2838. this.x -= otherVector.x;
  2839. this.y -= otherVector.y;
  2840. this.z -= otherVector.z;
  2841. this.w -= otherVector.w;
  2842. return this;
  2843. };
  2844. /**
  2845. * Returns a new Vector4 with the result of the subtraction of the passed vector from the current Vector4.
  2846. */
  2847. Vector4.prototype.subtract = function (otherVector) {
  2848. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  2849. };
  2850. /**
  2851. * Sets the passed vector "result" with the result of the subtraction of the passed vector from the current Vector4.
  2852. * Returns the current Vector4.
  2853. */
  2854. Vector4.prototype.subtractToRef = function (otherVector, result) {
  2855. result.x = this.x - otherVector.x;
  2856. result.y = this.y - otherVector.y;
  2857. result.z = this.z - otherVector.z;
  2858. result.w = this.w - otherVector.w;
  2859. return this;
  2860. };
  2861. /**
  2862. * Returns a new Vector4 set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  2863. */
  2864. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  2865. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  2866. };
  2867. /**
  2868. * Sets the passed vector "result" set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  2869. * Returns the current Vector4.
  2870. */
  2871. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  2872. result.x = this.x - x;
  2873. result.y = this.y - y;
  2874. result.z = this.z - z;
  2875. result.w = this.w - w;
  2876. return this;
  2877. };
  2878. /**
  2879. * Returns a new Vector4 set with the current Vector4 negated coordinates.
  2880. */
  2881. Vector4.prototype.negate = function () {
  2882. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  2883. };
  2884. /**
  2885. * Multiplies the current Vector4 coordinates by scale (float).
  2886. * Returns the updated Vector4.
  2887. */
  2888. Vector4.prototype.scaleInPlace = function (scale) {
  2889. this.x *= scale;
  2890. this.y *= scale;
  2891. this.z *= scale;
  2892. this.w *= scale;
  2893. return this;
  2894. };
  2895. /**
  2896. * Returns a new Vector4 set with the current Vector4 coordinates multiplied by scale (float).
  2897. */
  2898. Vector4.prototype.scale = function (scale) {
  2899. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  2900. };
  2901. /**
  2902. * Sets the passed vector "result" with the current Vector4 coordinates multiplied by scale (float).
  2903. * Returns the current Vector4.
  2904. */
  2905. Vector4.prototype.scaleToRef = function (scale, result) {
  2906. result.x = this.x * scale;
  2907. result.y = this.y * scale;
  2908. result.z = this.z * scale;
  2909. result.w = this.w * scale;
  2910. return this;
  2911. };
  2912. /**
  2913. * Boolean : True if the current Vector4 coordinates are stricly equal to the passed ones.
  2914. */
  2915. Vector4.prototype.equals = function (otherVector) {
  2916. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  2917. };
  2918. /**
  2919. * Boolean : True if the current Vector4 coordinates are each beneath the distance "epsilon" from the passed vector ones.
  2920. */
  2921. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2922. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2923. return otherVector
  2924. && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon)
  2925. && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon)
  2926. && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon)
  2927. && BABYLON.Scalar.WithinEpsilon(this.w, otherVector.w, epsilon);
  2928. };
  2929. /**
  2930. * Boolean : True if the passed floats are strictly equal to the current Vector4 coordinates.
  2931. */
  2932. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  2933. return this.x === x && this.y === y && this.z === z && this.w === w;
  2934. };
  2935. /**
  2936. * Multiplies in place the current Vector4 by the passed one.
  2937. * Returns the updated Vector4.
  2938. */
  2939. Vector4.prototype.multiplyInPlace = function (otherVector) {
  2940. this.x *= otherVector.x;
  2941. this.y *= otherVector.y;
  2942. this.z *= otherVector.z;
  2943. this.w *= otherVector.w;
  2944. return this;
  2945. };
  2946. /**
  2947. * Returns a new Vector4 set with the multiplication result of the current Vector4 and the passed one.
  2948. */
  2949. Vector4.prototype.multiply = function (otherVector) {
  2950. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  2951. };
  2952. /**
  2953. * Updates the passed vector "result" with the multiplication result of the current Vector4 and the passed one.
  2954. * Returns the current Vector4.
  2955. */
  2956. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  2957. result.x = this.x * otherVector.x;
  2958. result.y = this.y * otherVector.y;
  2959. result.z = this.z * otherVector.z;
  2960. result.w = this.w * otherVector.w;
  2961. return this;
  2962. };
  2963. /**
  2964. * Returns a new Vector4 set with the multiplication result of the passed floats and the current Vector4 coordinates.
  2965. */
  2966. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  2967. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  2968. };
  2969. /**
  2970. * Returns a new Vector4 set with the division result of the current Vector4 by the passed one.
  2971. */
  2972. Vector4.prototype.divide = function (otherVector) {
  2973. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  2974. };
  2975. /**
  2976. * Updates the passed vector "result" with the division result of the current Vector4 by the passed one.
  2977. * Returns the current Vector4.
  2978. */
  2979. Vector4.prototype.divideToRef = function (otherVector, result) {
  2980. result.x = this.x / otherVector.x;
  2981. result.y = this.y / otherVector.y;
  2982. result.z = this.z / otherVector.z;
  2983. result.w = this.w / otherVector.w;
  2984. return this;
  2985. };
  2986. /**
  2987. * Divides the current Vector3 coordinates by the passed ones.
  2988. * Returns the updated Vector3.
  2989. */
  2990. Vector4.prototype.divideInPlace = function (otherVector) {
  2991. return this.divideToRef(otherVector, this);
  2992. };
  2993. /**
  2994. * Updates the Vector4 coordinates with the minimum values between its own and the passed vector ones.
  2995. */
  2996. Vector4.prototype.MinimizeInPlace = function (other) {
  2997. if (other.x < this.x)
  2998. this.x = other.x;
  2999. if (other.y < this.y)
  3000. this.y = other.y;
  3001. if (other.z < this.z)
  3002. this.z = other.z;
  3003. if (other.w < this.w)
  3004. this.w = other.w;
  3005. return this;
  3006. };
  3007. /**
  3008. * Updates the Vector4 coordinates with the maximum values between its own and the passed vector ones.
  3009. */
  3010. Vector4.prototype.MaximizeInPlace = function (other) {
  3011. if (other.x > this.x)
  3012. this.x = other.x;
  3013. if (other.y > this.y)
  3014. this.y = other.y;
  3015. if (other.z > this.z)
  3016. this.z = other.z;
  3017. if (other.w > this.w)
  3018. this.w = other.w;
  3019. return this;
  3020. };
  3021. // Properties
  3022. /**
  3023. * Returns the Vector4 length (float).
  3024. */
  3025. Vector4.prototype.length = function () {
  3026. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  3027. };
  3028. /**
  3029. * Returns the Vector4 squared length (float).
  3030. */
  3031. Vector4.prototype.lengthSquared = function () {
  3032. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  3033. };
  3034. // Methods
  3035. /**
  3036. * Normalizes in place the Vector4.
  3037. * Returns the updated Vector4.
  3038. */
  3039. Vector4.prototype.normalize = function () {
  3040. var len = this.length();
  3041. if (len === 0)
  3042. return this;
  3043. var num = 1.0 / len;
  3044. this.x *= num;
  3045. this.y *= num;
  3046. this.z *= num;
  3047. this.w *= num;
  3048. return this;
  3049. };
  3050. /**
  3051. * Returns a new Vector3 from the Vector4 (x, y, z) coordinates.
  3052. */
  3053. Vector4.prototype.toVector3 = function () {
  3054. return new Vector3(this.x, this.y, this.z);
  3055. };
  3056. /**
  3057. * Returns a new Vector4 copied from the current one.
  3058. */
  3059. Vector4.prototype.clone = function () {
  3060. return new Vector4(this.x, this.y, this.z, this.w);
  3061. };
  3062. /**
  3063. * Updates the current Vector4 with the passed one coordinates.
  3064. * Returns the updated Vector4.
  3065. */
  3066. Vector4.prototype.copyFrom = function (source) {
  3067. this.x = source.x;
  3068. this.y = source.y;
  3069. this.z = source.z;
  3070. this.w = source.w;
  3071. return this;
  3072. };
  3073. /**
  3074. * Updates the current Vector4 coordinates with the passed floats.
  3075. * Returns the updated Vector4.
  3076. */
  3077. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  3078. this.x = x;
  3079. this.y = y;
  3080. this.z = z;
  3081. this.w = w;
  3082. return this;
  3083. };
  3084. /**
  3085. * Updates the current Vector4 coordinates with the passed floats.
  3086. * Returns the updated Vector4.
  3087. */
  3088. Vector4.prototype.set = function (x, y, z, w) {
  3089. return this.copyFromFloats(x, y, z, w);
  3090. };
  3091. // Statics
  3092. /**
  3093. * Returns a new Vector4 set from the starting index of the passed array.
  3094. */
  3095. Vector4.FromArray = function (array, offset) {
  3096. if (!offset) {
  3097. offset = 0;
  3098. }
  3099. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  3100. };
  3101. /**
  3102. * Updates the passed vector "result" from the starting index of the passed array.
  3103. */
  3104. Vector4.FromArrayToRef = function (array, offset, result) {
  3105. result.x = array[offset];
  3106. result.y = array[offset + 1];
  3107. result.z = array[offset + 2];
  3108. result.w = array[offset + 3];
  3109. };
  3110. /**
  3111. * Updates the passed vector "result" from the starting index of the passed Float32Array.
  3112. */
  3113. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  3114. Vector4.FromArrayToRef(array, offset, result);
  3115. };
  3116. /**
  3117. * Updates the passed vector "result" coordinates from the passed floats.
  3118. */
  3119. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  3120. result.x = x;
  3121. result.y = y;
  3122. result.z = z;
  3123. result.w = w;
  3124. };
  3125. /**
  3126. * Returns a new Vector4 set to (0.0, 0.0, 0.0, 0.0)
  3127. */
  3128. Vector4.Zero = function () {
  3129. return new Vector4(0.0, 0.0, 0.0, 0.0);
  3130. };
  3131. /**
  3132. * Returns a new Vector4 set to (1.0, 1.0, 1.0, 1.0)
  3133. */
  3134. Vector4.One = function () {
  3135. return new Vector4(1.0, 1.0, 1.0, 1.0);
  3136. };
  3137. /**
  3138. * Returns a new normalized Vector4 from the passed one.
  3139. */
  3140. Vector4.Normalize = function (vector) {
  3141. var result = Vector4.Zero();
  3142. Vector4.NormalizeToRef(vector, result);
  3143. return result;
  3144. };
  3145. /**
  3146. * Updates the passed vector "result" from the normalization of the passed one.
  3147. */
  3148. Vector4.NormalizeToRef = function (vector, result) {
  3149. result.copyFrom(vector);
  3150. result.normalize();
  3151. };
  3152. Vector4.Minimize = function (left, right) {
  3153. var min = left.clone();
  3154. min.MinimizeInPlace(right);
  3155. return min;
  3156. };
  3157. Vector4.Maximize = function (left, right) {
  3158. var max = left.clone();
  3159. max.MaximizeInPlace(right);
  3160. return max;
  3161. };
  3162. /**
  3163. * Returns the distance (float) between the vectors "value1" and "value2".
  3164. */
  3165. Vector4.Distance = function (value1, value2) {
  3166. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  3167. };
  3168. /**
  3169. * Returns the squared distance (float) between the vectors "value1" and "value2".
  3170. */
  3171. Vector4.DistanceSquared = function (value1, value2) {
  3172. var x = value1.x - value2.x;
  3173. var y = value1.y - value2.y;
  3174. var z = value1.z - value2.z;
  3175. var w = value1.w - value2.w;
  3176. return (x * x) + (y * y) + (z * z) + (w * w);
  3177. };
  3178. /**
  3179. * Returns a new Vector4 located at the center between the vectors "value1" and "value2".
  3180. */
  3181. Vector4.Center = function (value1, value2) {
  3182. var center = value1.add(value2);
  3183. center.scaleInPlace(0.5);
  3184. return center;
  3185. };
  3186. /**
  3187. * Returns a new Vector4 set with the result of the normal transformation by the passed matrix of the passed vector.
  3188. * This methods computes transformed normalized direction vectors only.
  3189. */
  3190. Vector4.TransformNormal = function (vector, transformation) {
  3191. var result = Vector4.Zero();
  3192. Vector4.TransformNormalToRef(vector, transformation, result);
  3193. return result;
  3194. };
  3195. /**
  3196. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector.
  3197. * This methods computes transformed normalized direction vectors only.
  3198. */
  3199. Vector4.TransformNormalToRef = function (vector, transformation, result) {
  3200. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  3201. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  3202. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  3203. result.x = x;
  3204. result.y = y;
  3205. result.z = z;
  3206. result.w = vector.w;
  3207. };
  3208. /**
  3209. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z, w).
  3210. * This methods computes transformed normalized direction vectors only.
  3211. */
  3212. Vector4.TransformNormalFromFloatsToRef = function (x, y, z, w, transformation, result) {
  3213. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  3214. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  3215. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  3216. result.w = w;
  3217. };
  3218. return Vector4;
  3219. }());
  3220. BABYLON.Vector4 = Vector4;
  3221. var Size = /** @class */ (function () {
  3222. /**
  3223. * Creates a Size object from the passed width and height (floats).
  3224. */
  3225. function Size(width, height) {
  3226. this.width = width;
  3227. this.height = height;
  3228. }
  3229. // Returns a string with the Size width and height.
  3230. Size.prototype.toString = function () {
  3231. return "{W: " + this.width + ", H: " + this.height + "}";
  3232. };
  3233. /**
  3234. * Returns the string "Size"
  3235. */
  3236. Size.prototype.getClassName = function () {
  3237. return "Size";
  3238. };
  3239. /**
  3240. * Returns the Size hash code.
  3241. */
  3242. Size.prototype.getHashCode = function () {
  3243. var hash = this.width || 0;
  3244. hash = (hash * 397) ^ (this.height || 0);
  3245. return hash;
  3246. };
  3247. /**
  3248. * Updates the current size from the passed one.
  3249. * Returns the updated Size.
  3250. */
  3251. Size.prototype.copyFrom = function (src) {
  3252. this.width = src.width;
  3253. this.height = src.height;
  3254. };
  3255. /**
  3256. * Updates in place the current Size from the passed floats.
  3257. * Returns the updated Size.
  3258. */
  3259. Size.prototype.copyFromFloats = function (width, height) {
  3260. this.width = width;
  3261. this.height = height;
  3262. return this;
  3263. };
  3264. /**
  3265. * Updates in place the current Size from the passed floats.
  3266. * Returns the updated Size.
  3267. */
  3268. Size.prototype.set = function (width, height) {
  3269. return this.copyFromFloats(width, height);
  3270. };
  3271. /**
  3272. * Returns a new Size set with the multiplication result of the current Size and the passed floats.
  3273. */
  3274. Size.prototype.multiplyByFloats = function (w, h) {
  3275. return new Size(this.width * w, this.height * h);
  3276. };
  3277. /**
  3278. * Returns a new Size copied from the passed one.
  3279. */
  3280. Size.prototype.clone = function () {
  3281. return new Size(this.width, this.height);
  3282. };
  3283. /**
  3284. * Boolean : True if the current Size and the passed one width and height are strictly equal.
  3285. */
  3286. Size.prototype.equals = function (other) {
  3287. if (!other) {
  3288. return false;
  3289. }
  3290. return (this.width === other.width) && (this.height === other.height);
  3291. };
  3292. Object.defineProperty(Size.prototype, "surface", {
  3293. /**
  3294. * Returns the surface of the Size : width * height (float).
  3295. */
  3296. get: function () {
  3297. return this.width * this.height;
  3298. },
  3299. enumerable: true,
  3300. configurable: true
  3301. });
  3302. /**
  3303. * Returns a new Size set to (0.0, 0.0)
  3304. */
  3305. Size.Zero = function () {
  3306. return new Size(0.0, 0.0);
  3307. };
  3308. /**
  3309. * Returns a new Size set as the addition result of the current Size and the passed one.
  3310. */
  3311. Size.prototype.add = function (otherSize) {
  3312. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  3313. return r;
  3314. };
  3315. /**
  3316. * Returns a new Size set as the subtraction result of the passed one from the current Size.
  3317. */
  3318. Size.prototype.subtract = function (otherSize) {
  3319. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  3320. return r;
  3321. };
  3322. /**
  3323. * Returns a new Size set at the linear interpolation "amount" between "start" and "end".
  3324. */
  3325. Size.Lerp = function (start, end, amount) {
  3326. var w = start.width + ((end.width - start.width) * amount);
  3327. var h = start.height + ((end.height - start.height) * amount);
  3328. return new Size(w, h);
  3329. };
  3330. return Size;
  3331. }());
  3332. BABYLON.Size = Size;
  3333. var Quaternion = /** @class */ (function () {
  3334. /**
  3335. * Creates a new Quaternion from the passed floats.
  3336. */
  3337. function Quaternion(x, y, z, w) {
  3338. if (x === void 0) { x = 0.0; }
  3339. if (y === void 0) { y = 0.0; }
  3340. if (z === void 0) { z = 0.0; }
  3341. if (w === void 0) { w = 1.0; }
  3342. this.x = x;
  3343. this.y = y;
  3344. this.z = z;
  3345. this.w = w;
  3346. }
  3347. /**
  3348. * Returns a string with the Quaternion coordinates.
  3349. */
  3350. Quaternion.prototype.toString = function () {
  3351. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  3352. };
  3353. /**
  3354. * Returns the string "Quaternion".
  3355. */
  3356. Quaternion.prototype.getClassName = function () {
  3357. return "Quaternion";
  3358. };
  3359. /**
  3360. * Returns the Quaternion hash code.
  3361. */
  3362. Quaternion.prototype.getHashCode = function () {
  3363. var hash = this.x || 0;
  3364. hash = (hash * 397) ^ (this.y || 0);
  3365. hash = (hash * 397) ^ (this.z || 0);
  3366. hash = (hash * 397) ^ (this.w || 0);
  3367. return hash;
  3368. };
  3369. /**
  3370. * Returns a new array populated with 4 elements : the Quaternion coordinates.
  3371. */
  3372. Quaternion.prototype.asArray = function () {
  3373. return [this.x, this.y, this.z, this.w];
  3374. };
  3375. /**
  3376. * Boolean : True if the current Quaterion and the passed one coordinates are strictly equal.
  3377. */
  3378. Quaternion.prototype.equals = function (otherQuaternion) {
  3379. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  3380. };
  3381. /**
  3382. * Returns a new Quaternion copied from the current one.
  3383. */
  3384. Quaternion.prototype.clone = function () {
  3385. return new Quaternion(this.x, this.y, this.z, this.w);
  3386. };
  3387. /**
  3388. * Updates the current Quaternion from the passed one coordinates.
  3389. * Returns the updated Quaterion.
  3390. */
  3391. Quaternion.prototype.copyFrom = function (other) {
  3392. this.x = other.x;
  3393. this.y = other.y;
  3394. this.z = other.z;
  3395. this.w = other.w;
  3396. return this;
  3397. };
  3398. /**
  3399. * Updates the current Quaternion from the passed float coordinates.
  3400. * Returns the updated Quaterion.
  3401. */
  3402. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  3403. this.x = x;
  3404. this.y = y;
  3405. this.z = z;
  3406. this.w = w;
  3407. return this;
  3408. };
  3409. /**
  3410. * Updates the current Quaternion from the passed float coordinates.
  3411. * Returns the updated Quaterion.
  3412. */
  3413. Quaternion.prototype.set = function (x, y, z, w) {
  3414. return this.copyFromFloats(x, y, z, w);
  3415. };
  3416. /**
  3417. * Returns a new Quaternion as the addition result of the passed one and the current Quaternion.
  3418. */
  3419. Quaternion.prototype.add = function (other) {
  3420. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  3421. };
  3422. /**
  3423. * Returns a new Quaternion as the subtraction result of the passed one from the current Quaternion.
  3424. */
  3425. Quaternion.prototype.subtract = function (other) {
  3426. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  3427. };
  3428. /**
  3429. * Returns a new Quaternion set by multiplying the current Quaterion coordinates by the float "scale".
  3430. */
  3431. Quaternion.prototype.scale = function (value) {
  3432. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  3433. };
  3434. /**
  3435. * Returns a new Quaternion set as the quaternion mulplication result of the current one with the passed one "q1".
  3436. */
  3437. Quaternion.prototype.multiply = function (q1) {
  3438. var result = new Quaternion(0, 0, 0, 1.0);
  3439. this.multiplyToRef(q1, result);
  3440. return result;
  3441. };
  3442. /**
  3443. * Sets the passed "result" as the quaternion mulplication result of the current one with the passed one "q1".
  3444. * Returns the current Quaternion.
  3445. */
  3446. Quaternion.prototype.multiplyToRef = function (q1, result) {
  3447. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  3448. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  3449. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  3450. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  3451. result.copyFromFloats(x, y, z, w);
  3452. return this;
  3453. };
  3454. /**
  3455. * Updates the current Quaternion with the quaternion mulplication result of itself with the passed one "q1".
  3456. * Returns the updated Quaternion.
  3457. */
  3458. Quaternion.prototype.multiplyInPlace = function (q1) {
  3459. this.multiplyToRef(q1, this);
  3460. return this;
  3461. };
  3462. /**
  3463. * Sets the passed "ref" with the conjugation of the current Quaternion.
  3464. * Returns the current Quaternion.
  3465. */
  3466. Quaternion.prototype.conjugateToRef = function (ref) {
  3467. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  3468. return this;
  3469. };
  3470. /**
  3471. * Conjugates in place the current Quaternion.
  3472. * Returns the updated Quaternion.
  3473. */
  3474. Quaternion.prototype.conjugateInPlace = function () {
  3475. this.x *= -1;
  3476. this.y *= -1;
  3477. this.z *= -1;
  3478. return this;
  3479. };
  3480. /**
  3481. * Returns a new Quaternion as the conjugate of the current Quaternion.
  3482. */
  3483. Quaternion.prototype.conjugate = function () {
  3484. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  3485. return result;
  3486. };
  3487. /**
  3488. * Returns the Quaternion length (float).
  3489. */
  3490. Quaternion.prototype.length = function () {
  3491. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  3492. };
  3493. /**
  3494. * Normalize in place the current Quaternion.
  3495. * Returns the updated Quaternion.
  3496. */
  3497. Quaternion.prototype.normalize = function () {
  3498. var length = 1.0 / this.length();
  3499. this.x *= length;
  3500. this.y *= length;
  3501. this.z *= length;
  3502. this.w *= length;
  3503. return this;
  3504. };
  3505. /**
  3506. * Returns a new Vector3 set with the Euler angles translated from the current Quaternion.
  3507. */
  3508. Quaternion.prototype.toEulerAngles = function (order) {
  3509. if (order === void 0) { order = "YZX"; }
  3510. var result = Vector3.Zero();
  3511. this.toEulerAnglesToRef(result, order);
  3512. return result;
  3513. };
  3514. /**
  3515. * Sets the passed vector3 "result" with the Euler angles translated from the current Quaternion.
  3516. * Returns the current Quaternion.
  3517. */
  3518. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  3519. if (order === void 0) { order = "YZX"; }
  3520. var qz = this.z;
  3521. var qx = this.x;
  3522. var qy = this.y;
  3523. var qw = this.w;
  3524. var sqw = qw * qw;
  3525. var sqz = qz * qz;
  3526. var sqx = qx * qx;
  3527. var sqy = qy * qy;
  3528. var zAxisY = qy * qz - qx * qw;
  3529. var limit = .4999999;
  3530. if (zAxisY < -limit) {
  3531. result.y = 2 * Math.atan2(qy, qw);
  3532. result.x = Math.PI / 2;
  3533. result.z = 0;
  3534. }
  3535. else if (zAxisY > limit) {
  3536. result.y = 2 * Math.atan2(qy, qw);
  3537. result.x = -Math.PI / 2;
  3538. result.z = 0;
  3539. }
  3540. else {
  3541. result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));
  3542. result.x = Math.asin(-2.0 * (qz * qy - qx * qw));
  3543. result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));
  3544. }
  3545. return this;
  3546. };
  3547. /**
  3548. * Updates the passed rotation matrix with the current Quaternion values.
  3549. * Returns the current Quaternion.
  3550. */
  3551. Quaternion.prototype.toRotationMatrix = function (result) {
  3552. var xx = this.x * this.x;
  3553. var yy = this.y * this.y;
  3554. var zz = this.z * this.z;
  3555. var xy = this.x * this.y;
  3556. var zw = this.z * this.w;
  3557. var zx = this.z * this.x;
  3558. var yw = this.y * this.w;
  3559. var yz = this.y * this.z;
  3560. var xw = this.x * this.w;
  3561. result.m[0] = 1.0 - (2.0 * (yy + zz));
  3562. result.m[1] = 2.0 * (xy + zw);
  3563. result.m[2] = 2.0 * (zx - yw);
  3564. result.m[3] = 0;
  3565. result.m[4] = 2.0 * (xy - zw);
  3566. result.m[5] = 1.0 - (2.0 * (zz + xx));
  3567. result.m[6] = 2.0 * (yz + xw);
  3568. result.m[7] = 0;
  3569. result.m[8] = 2.0 * (zx + yw);
  3570. result.m[9] = 2.0 * (yz - xw);
  3571. result.m[10] = 1.0 - (2.0 * (yy + xx));
  3572. result.m[11] = 0;
  3573. result.m[12] = 0;
  3574. result.m[13] = 0;
  3575. result.m[14] = 0;
  3576. result.m[15] = 1.0;
  3577. result._markAsUpdated();
  3578. return this;
  3579. };
  3580. /**
  3581. * Updates the current Quaternion from the passed rotation matrix values.
  3582. * Returns the updated Quaternion.
  3583. */
  3584. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  3585. Quaternion.FromRotationMatrixToRef(matrix, this);
  3586. return this;
  3587. };
  3588. // Statics
  3589. /**
  3590. * Returns a new Quaternion set from the passed rotation matrix values.
  3591. */
  3592. Quaternion.FromRotationMatrix = function (matrix) {
  3593. var result = new Quaternion();
  3594. Quaternion.FromRotationMatrixToRef(matrix, result);
  3595. return result;
  3596. };
  3597. /**
  3598. * Updates the passed quaternion "result" with the passed rotation matrix values.
  3599. */
  3600. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  3601. var data = matrix.m;
  3602. var m11 = data[0], m12 = data[4], m13 = data[8];
  3603. var m21 = data[1], m22 = data[5], m23 = data[9];
  3604. var m31 = data[2], m32 = data[6], m33 = data[10];
  3605. var trace = m11 + m22 + m33;
  3606. var s;
  3607. if (trace > 0) {
  3608. s = 0.5 / Math.sqrt(trace + 1.0);
  3609. result.w = 0.25 / s;
  3610. result.x = (m32 - m23) * s;
  3611. result.y = (m13 - m31) * s;
  3612. result.z = (m21 - m12) * s;
  3613. }
  3614. else if (m11 > m22 && m11 > m33) {
  3615. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  3616. result.w = (m32 - m23) / s;
  3617. result.x = 0.25 * s;
  3618. result.y = (m12 + m21) / s;
  3619. result.z = (m13 + m31) / s;
  3620. }
  3621. else if (m22 > m33) {
  3622. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  3623. result.w = (m13 - m31) / s;
  3624. result.x = (m12 + m21) / s;
  3625. result.y = 0.25 * s;
  3626. result.z = (m23 + m32) / s;
  3627. }
  3628. else {
  3629. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  3630. result.w = (m21 - m12) / s;
  3631. result.x = (m13 + m31) / s;
  3632. result.y = (m23 + m32) / s;
  3633. result.z = 0.25 * s;
  3634. }
  3635. };
  3636. /**
  3637. * Returns a new Quaternion set to (0.0, 0.0, 0.0).
  3638. */
  3639. Quaternion.Zero = function () {
  3640. return new Quaternion(0.0, 0.0, 0.0, 0.0);
  3641. };
  3642. /**
  3643. * Returns a new Quaternion as the inverted current Quaternion.
  3644. */
  3645. Quaternion.Inverse = function (q) {
  3646. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  3647. };
  3648. /**
  3649. * Returns the identity Quaternion.
  3650. */
  3651. Quaternion.Identity = function () {
  3652. return new Quaternion(0.0, 0.0, 0.0, 1.0);
  3653. };
  3654. Quaternion.IsIdentity = function (quaternion) {
  3655. return quaternion && quaternion.x === 0 && quaternion.y === 0 && quaternion.z === 0 && quaternion.w === 1;
  3656. };
  3657. /**
  3658. * Returns a new Quaternion set from the passed axis (Vector3) and angle in radians (float).
  3659. */
  3660. Quaternion.RotationAxis = function (axis, angle) {
  3661. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  3662. };
  3663. /**
  3664. * Sets the passed quaternion "result" from the passed axis (Vector3) and angle in radians (float).
  3665. */
  3666. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  3667. var sin = Math.sin(angle / 2);
  3668. axis.normalize();
  3669. result.w = Math.cos(angle / 2);
  3670. result.x = axis.x * sin;
  3671. result.y = axis.y * sin;
  3672. result.z = axis.z * sin;
  3673. return result;
  3674. };
  3675. /**
  3676. * Retuns a new Quaternion set from the starting index of the passed array.
  3677. */
  3678. Quaternion.FromArray = function (array, offset) {
  3679. if (!offset) {
  3680. offset = 0;
  3681. }
  3682. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  3683. };
  3684. /**
  3685. * Returns a new Quaternion set from the passed Euler float angles (y, x, z).
  3686. */
  3687. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  3688. var q = new Quaternion();
  3689. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  3690. return q;
  3691. };
  3692. /**
  3693. * Sets the passed quaternion "result" from the passed float Euler angles (y, x, z).
  3694. */
  3695. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  3696. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  3697. var halfRoll = roll * 0.5;
  3698. var halfPitch = pitch * 0.5;
  3699. var halfYaw = yaw * 0.5;
  3700. var sinRoll = Math.sin(halfRoll);
  3701. var cosRoll = Math.cos(halfRoll);
  3702. var sinPitch = Math.sin(halfPitch);
  3703. var cosPitch = Math.cos(halfPitch);
  3704. var sinYaw = Math.sin(halfYaw);
  3705. var cosYaw = Math.cos(halfYaw);
  3706. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  3707. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  3708. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  3709. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  3710. };
  3711. /**
  3712. * Returns a new Quaternion from the passed float Euler angles expressed in z-x-z orientation
  3713. */
  3714. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  3715. var result = new Quaternion();
  3716. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  3717. return result;
  3718. };
  3719. /**
  3720. * Sets the passed quaternion "result" from the passed float Euler angles expressed in z-x-z orientation
  3721. */
  3722. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  3723. // Produces a quaternion from Euler angles in the z-x-z orientation
  3724. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  3725. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  3726. var halfBeta = beta * 0.5;
  3727. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  3728. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  3729. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  3730. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  3731. };
  3732. /**
  3733. * Returns a new Quaternion as the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  3734. * cf to Vector3.RotationFromAxis() documentation.
  3735. * Note : axis1, axis2 and axis3 are normalized during this operation.
  3736. */
  3737. Quaternion.RotationQuaternionFromAxis = function (axis1, axis2, axis3, ref) {
  3738. var quat = new Quaternion(0.0, 0.0, 0.0, 0.0);
  3739. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  3740. return quat;
  3741. };
  3742. /**
  3743. * Sets the passed quaternion "ref" with the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  3744. * cf to Vector3.RotationFromAxis() documentation.
  3745. * Note : axis1, axis2 and axis3 are normalized during this operation.
  3746. */
  3747. Quaternion.RotationQuaternionFromAxisToRef = function (axis1, axis2, axis3, ref) {
  3748. var rotMat = MathTmp.Matrix[0];
  3749. Matrix.FromXYZAxesToRef(axis1.normalize(), axis2.normalize(), axis3.normalize(), rotMat);
  3750. Quaternion.FromRotationMatrixToRef(rotMat, ref);
  3751. };
  3752. Quaternion.Slerp = function (left, right, amount) {
  3753. var result = Quaternion.Identity();
  3754. Quaternion.SlerpToRef(left, right, amount, result);
  3755. return result;
  3756. };
  3757. Quaternion.SlerpToRef = function (left, right, amount, result) {
  3758. var num2;
  3759. var num3;
  3760. var num = amount;
  3761. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  3762. var flag = false;
  3763. if (num4 < 0) {
  3764. flag = true;
  3765. num4 = -num4;
  3766. }
  3767. if (num4 > 0.999999) {
  3768. num3 = 1 - num;
  3769. num2 = flag ? -num : num;
  3770. }
  3771. else {
  3772. var num5 = Math.acos(num4);
  3773. var num6 = (1.0 / Math.sin(num5));
  3774. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  3775. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  3776. }
  3777. result.x = (num3 * left.x) + (num2 * right.x);
  3778. result.y = (num3 * left.y) + (num2 * right.y);
  3779. result.z = (num3 * left.z) + (num2 * right.z);
  3780. result.w = (num3 * left.w) + (num2 * right.w);
  3781. };
  3782. /**
  3783. * Returns a new Quaternion located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2".
  3784. */
  3785. Quaternion.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  3786. var squared = amount * amount;
  3787. var cubed = amount * squared;
  3788. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  3789. var part2 = (-2.0 * cubed) + (3.0 * squared);
  3790. var part3 = (cubed - (2.0 * squared)) + amount;
  3791. var part4 = cubed - squared;
  3792. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  3793. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  3794. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  3795. var w = (((value1.w * part1) + (value2.w * part2)) + (tangent1.w * part3)) + (tangent2.w * part4);
  3796. return new Quaternion(x, y, z, w);
  3797. };
  3798. return Quaternion;
  3799. }());
  3800. BABYLON.Quaternion = Quaternion;
  3801. var Matrix = /** @class */ (function () {
  3802. function Matrix() {
  3803. this._isIdentity = false;
  3804. this._isIdentityDirty = true;
  3805. this.m = new Float32Array(16);
  3806. this._markAsUpdated();
  3807. }
  3808. Matrix.prototype._markAsUpdated = function () {
  3809. this.updateFlag = Matrix._updateFlagSeed++;
  3810. this._isIdentityDirty = true;
  3811. };
  3812. // Properties
  3813. /**
  3814. * Boolean : True is the matrix is the identity matrix
  3815. */
  3816. Matrix.prototype.isIdentity = function (considerAsTextureMatrix) {
  3817. if (considerAsTextureMatrix === void 0) { considerAsTextureMatrix = false; }
  3818. if (this._isIdentityDirty) {
  3819. this._isIdentityDirty = false;
  3820. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[15] !== 1.0) {
  3821. this._isIdentity = false;
  3822. }
  3823. else if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  3824. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  3825. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  3826. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0) {
  3827. this._isIdentity = false;
  3828. }
  3829. else {
  3830. this._isIdentity = true;
  3831. }
  3832. if (!considerAsTextureMatrix && this.m[10] !== 1.0) {
  3833. this._isIdentity = false;
  3834. }
  3835. }
  3836. return this._isIdentity;
  3837. };
  3838. /**
  3839. * Returns the matrix determinant (float).
  3840. */
  3841. Matrix.prototype.determinant = function () {
  3842. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  3843. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  3844. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  3845. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  3846. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  3847. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  3848. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  3849. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  3850. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  3851. };
  3852. // Methods
  3853. /**
  3854. * Returns the matrix underlying array.
  3855. */
  3856. Matrix.prototype.toArray = function () {
  3857. return this.m;
  3858. };
  3859. /**
  3860. * Returns the matrix underlying array.
  3861. */
  3862. Matrix.prototype.asArray = function () {
  3863. return this.toArray();
  3864. };
  3865. /**
  3866. * Inverts in place the Matrix.
  3867. * Returns the Matrix inverted.
  3868. */
  3869. Matrix.prototype.invert = function () {
  3870. this.invertToRef(this);
  3871. return this;
  3872. };
  3873. /**
  3874. * Sets all the matrix elements to zero.
  3875. * Returns the Matrix.
  3876. */
  3877. Matrix.prototype.reset = function () {
  3878. for (var index = 0; index < 16; index++) {
  3879. this.m[index] = 0.0;
  3880. }
  3881. this._markAsUpdated();
  3882. return this;
  3883. };
  3884. /**
  3885. * Returns a new Matrix as the addition result of the current Matrix and the passed one.
  3886. */
  3887. Matrix.prototype.add = function (other) {
  3888. var result = new Matrix();
  3889. this.addToRef(other, result);
  3890. return result;
  3891. };
  3892. /**
  3893. * Sets the passed matrix "result" with the ddition result of the current Matrix and the passed one.
  3894. * Returns the Matrix.
  3895. */
  3896. Matrix.prototype.addToRef = function (other, result) {
  3897. for (var index = 0; index < 16; index++) {
  3898. result.m[index] = this.m[index] + other.m[index];
  3899. }
  3900. result._markAsUpdated();
  3901. return this;
  3902. };
  3903. /**
  3904. * Adds in place the passed matrix to the current Matrix.
  3905. * Returns the updated Matrix.
  3906. */
  3907. Matrix.prototype.addToSelf = function (other) {
  3908. for (var index = 0; index < 16; index++) {
  3909. this.m[index] += other.m[index];
  3910. }
  3911. this._markAsUpdated();
  3912. return this;
  3913. };
  3914. /**
  3915. * Sets the passed matrix with the current inverted Matrix.
  3916. * Returns the unmodified current Matrix.
  3917. */
  3918. Matrix.prototype.invertToRef = function (other) {
  3919. var l1 = this.m[0];
  3920. var l2 = this.m[1];
  3921. var l3 = this.m[2];
  3922. var l4 = this.m[3];
  3923. var l5 = this.m[4];
  3924. var l6 = this.m[5];
  3925. var l7 = this.m[6];
  3926. var l8 = this.m[7];
  3927. var l9 = this.m[8];
  3928. var l10 = this.m[9];
  3929. var l11 = this.m[10];
  3930. var l12 = this.m[11];
  3931. var l13 = this.m[12];
  3932. var l14 = this.m[13];
  3933. var l15 = this.m[14];
  3934. var l16 = this.m[15];
  3935. var l17 = (l11 * l16) - (l12 * l15);
  3936. var l18 = (l10 * l16) - (l12 * l14);
  3937. var l19 = (l10 * l15) - (l11 * l14);
  3938. var l20 = (l9 * l16) - (l12 * l13);
  3939. var l21 = (l9 * l15) - (l11 * l13);
  3940. var l22 = (l9 * l14) - (l10 * l13);
  3941. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  3942. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  3943. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  3944. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  3945. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  3946. var l28 = (l7 * l16) - (l8 * l15);
  3947. var l29 = (l6 * l16) - (l8 * l14);
  3948. var l30 = (l6 * l15) - (l7 * l14);
  3949. var l31 = (l5 * l16) - (l8 * l13);
  3950. var l32 = (l5 * l15) - (l7 * l13);
  3951. var l33 = (l5 * l14) - (l6 * l13);
  3952. var l34 = (l7 * l12) - (l8 * l11);
  3953. var l35 = (l6 * l12) - (l8 * l10);
  3954. var l36 = (l6 * l11) - (l7 * l10);
  3955. var l37 = (l5 * l12) - (l8 * l9);
  3956. var l38 = (l5 * l11) - (l7 * l9);
  3957. var l39 = (l5 * l10) - (l6 * l9);
  3958. other.m[0] = l23 * l27;
  3959. other.m[4] = l24 * l27;
  3960. other.m[8] = l25 * l27;
  3961. other.m[12] = l26 * l27;
  3962. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  3963. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  3964. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  3965. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  3966. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  3967. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  3968. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  3969. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  3970. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  3971. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  3972. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  3973. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  3974. other._markAsUpdated();
  3975. return this;
  3976. };
  3977. /**
  3978. * Inserts the translation vector (using 3 x floats) in the current Matrix.
  3979. * Returns the updated Matrix.
  3980. */
  3981. Matrix.prototype.setTranslationFromFloats = function (x, y, z) {
  3982. this.m[12] = x;
  3983. this.m[13] = y;
  3984. this.m[14] = z;
  3985. this._markAsUpdated();
  3986. return this;
  3987. };
  3988. /**
  3989. * Inserts the translation vector in the current Matrix.
  3990. * Returns the updated Matrix.
  3991. */
  3992. Matrix.prototype.setTranslation = function (vector3) {
  3993. this.m[12] = vector3.x;
  3994. this.m[13] = vector3.y;
  3995. this.m[14] = vector3.z;
  3996. this._markAsUpdated();
  3997. return this;
  3998. };
  3999. /**
  4000. * Returns a new Vector3 as the extracted translation from the Matrix.
  4001. */
  4002. Matrix.prototype.getTranslation = function () {
  4003. return new Vector3(this.m[12], this.m[13], this.m[14]);
  4004. };
  4005. /**
  4006. * Fill a Vector3 with the extracted translation from the Matrix.
  4007. */
  4008. Matrix.prototype.getTranslationToRef = function (result) {
  4009. result.x = this.m[12];
  4010. result.y = this.m[13];
  4011. result.z = this.m[14];
  4012. return this;
  4013. };
  4014. /**
  4015. * Remove rotation and scaling part from the Matrix.
  4016. * Returns the updated Matrix.
  4017. */
  4018. Matrix.prototype.removeRotationAndScaling = function () {
  4019. this.setRowFromFloats(0, 1, 0, 0, 0);
  4020. this.setRowFromFloats(1, 0, 1, 0, 0);
  4021. this.setRowFromFloats(2, 0, 0, 1, 0);
  4022. return this;
  4023. };
  4024. /**
  4025. * Returns a new Matrix set with the multiplication result of the current Matrix and the passed one.
  4026. */
  4027. Matrix.prototype.multiply = function (other) {
  4028. var result = new Matrix();
  4029. this.multiplyToRef(other, result);
  4030. return result;
  4031. };
  4032. /**
  4033. * Updates the current Matrix from the passed one values.
  4034. * Returns the updated Matrix.
  4035. */
  4036. Matrix.prototype.copyFrom = function (other) {
  4037. for (var index = 0; index < 16; index++) {
  4038. this.m[index] = other.m[index];
  4039. }
  4040. this._markAsUpdated();
  4041. return this;
  4042. };
  4043. /**
  4044. * Populates the passed array from the starting index with the Matrix values.
  4045. * Returns the Matrix.
  4046. */
  4047. Matrix.prototype.copyToArray = function (array, offset) {
  4048. if (offset === void 0) { offset = 0; }
  4049. for (var index = 0; index < 16; index++) {
  4050. array[offset + index] = this.m[index];
  4051. }
  4052. return this;
  4053. };
  4054. /**
  4055. * Sets the passed matrix "result" with the multiplication result of the current Matrix and the passed one.
  4056. */
  4057. Matrix.prototype.multiplyToRef = function (other, result) {
  4058. this.multiplyToArray(other, result.m, 0);
  4059. result._markAsUpdated();
  4060. return this;
  4061. };
  4062. /**
  4063. * Sets the Float32Array "result" from the passed index "offset" with the multiplication result of the current Matrix and the passed one.
  4064. */
  4065. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  4066. var tm0 = this.m[0];
  4067. var tm1 = this.m[1];
  4068. var tm2 = this.m[2];
  4069. var tm3 = this.m[3];
  4070. var tm4 = this.m[4];
  4071. var tm5 = this.m[5];
  4072. var tm6 = this.m[6];
  4073. var tm7 = this.m[7];
  4074. var tm8 = this.m[8];
  4075. var tm9 = this.m[9];
  4076. var tm10 = this.m[10];
  4077. var tm11 = this.m[11];
  4078. var tm12 = this.m[12];
  4079. var tm13 = this.m[13];
  4080. var tm14 = this.m[14];
  4081. var tm15 = this.m[15];
  4082. var om0 = other.m[0];
  4083. var om1 = other.m[1];
  4084. var om2 = other.m[2];
  4085. var om3 = other.m[3];
  4086. var om4 = other.m[4];
  4087. var om5 = other.m[5];
  4088. var om6 = other.m[6];
  4089. var om7 = other.m[7];
  4090. var om8 = other.m[8];
  4091. var om9 = other.m[9];
  4092. var om10 = other.m[10];
  4093. var om11 = other.m[11];
  4094. var om12 = other.m[12];
  4095. var om13 = other.m[13];
  4096. var om14 = other.m[14];
  4097. var om15 = other.m[15];
  4098. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  4099. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  4100. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  4101. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  4102. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  4103. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  4104. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  4105. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  4106. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  4107. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  4108. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  4109. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  4110. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  4111. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  4112. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  4113. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  4114. return this;
  4115. };
  4116. /**
  4117. * Boolean : True is the current Matrix and the passed one values are strictly equal.
  4118. */
  4119. Matrix.prototype.equals = function (value) {
  4120. return value &&
  4121. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  4122. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  4123. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  4124. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  4125. };
  4126. /**
  4127. * Returns a new Matrix from the current Matrix.
  4128. */
  4129. Matrix.prototype.clone = function () {
  4130. 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]);
  4131. };
  4132. /**
  4133. * Returns the string "Matrix"
  4134. */
  4135. Matrix.prototype.getClassName = function () {
  4136. return "Matrix";
  4137. };
  4138. /**
  4139. * Returns the Matrix hash code.
  4140. */
  4141. Matrix.prototype.getHashCode = function () {
  4142. var hash = this.m[0] || 0;
  4143. for (var i = 1; i < 16; i++) {
  4144. hash = (hash * 397) ^ (this.m[i] || 0);
  4145. }
  4146. return hash;
  4147. };
  4148. /**
  4149. * Decomposes the current Matrix into :
  4150. * - a scale vector3 passed as a reference to update,
  4151. * - a rotation quaternion passed as a reference to update,
  4152. * - a translation vector3 passed as a reference to update.
  4153. * Returns the boolean `true`.
  4154. */
  4155. Matrix.prototype.decompose = function (scale, rotation, translation) {
  4156. translation.x = this.m[12];
  4157. translation.y = this.m[13];
  4158. translation.z = this.m[14];
  4159. scale.x = Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  4160. scale.y = Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  4161. scale.z = Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  4162. if (this.determinant() <= 0) {
  4163. scale.y *= -1;
  4164. }
  4165. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  4166. rotation.x = 0;
  4167. rotation.y = 0;
  4168. rotation.z = 0;
  4169. rotation.w = 1;
  4170. return false;
  4171. }
  4172. 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]);
  4173. Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], rotation);
  4174. return true;
  4175. };
  4176. /**
  4177. * Returns a new Matrix as the extracted rotation matrix from the current one.
  4178. */
  4179. Matrix.prototype.getRotationMatrix = function () {
  4180. var result = Matrix.Identity();
  4181. this.getRotationMatrixToRef(result);
  4182. return result;
  4183. };
  4184. /**
  4185. * Extracts the rotation matrix from the current one and sets it as the passed "result".
  4186. * Returns the current Matrix.
  4187. */
  4188. Matrix.prototype.getRotationMatrixToRef = function (result) {
  4189. var m = this.m;
  4190. var xs = m[0] * m[1] * m[2] * m[3] < 0 ? -1 : 1;
  4191. var ys = m[4] * m[5] * m[6] * m[7] < 0 ? -1 : 1;
  4192. var zs = m[8] * m[9] * m[10] * m[11] < 0 ? -1 : 1;
  4193. var sx = xs * Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
  4194. var sy = ys * Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
  4195. var sz = zs * Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
  4196. 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);
  4197. return this;
  4198. };
  4199. // Statics
  4200. /**
  4201. * Returns a new Matrix set from the starting index of the passed array.
  4202. */
  4203. Matrix.FromArray = function (array, offset) {
  4204. var result = new Matrix();
  4205. if (!offset) {
  4206. offset = 0;
  4207. }
  4208. Matrix.FromArrayToRef(array, offset, result);
  4209. return result;
  4210. };
  4211. /**
  4212. * Sets the passed "result" matrix from the starting index of the passed array.
  4213. */
  4214. Matrix.FromArrayToRef = function (array, offset, result) {
  4215. for (var index = 0; index < 16; index++) {
  4216. result.m[index] = array[index + offset];
  4217. }
  4218. result._markAsUpdated();
  4219. };
  4220. /**
  4221. * Sets the passed "result" matrix from the starting index of the passed Float32Array by multiplying each element by the float "scale".
  4222. */
  4223. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  4224. for (var index = 0; index < 16; index++) {
  4225. result.m[index] = array[index + offset] * scale;
  4226. }
  4227. result._markAsUpdated();
  4228. };
  4229. /**
  4230. * Sets the passed matrix "result" with the 16 passed floats.
  4231. */
  4232. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  4233. result.m[0] = initialM11;
  4234. result.m[1] = initialM12;
  4235. result.m[2] = initialM13;
  4236. result.m[3] = initialM14;
  4237. result.m[4] = initialM21;
  4238. result.m[5] = initialM22;
  4239. result.m[6] = initialM23;
  4240. result.m[7] = initialM24;
  4241. result.m[8] = initialM31;
  4242. result.m[9] = initialM32;
  4243. result.m[10] = initialM33;
  4244. result.m[11] = initialM34;
  4245. result.m[12] = initialM41;
  4246. result.m[13] = initialM42;
  4247. result.m[14] = initialM43;
  4248. result.m[15] = initialM44;
  4249. result._markAsUpdated();
  4250. };
  4251. /**
  4252. * Returns the index-th row of the current matrix as a new Vector4.
  4253. */
  4254. Matrix.prototype.getRow = function (index) {
  4255. if (index < 0 || index > 3) {
  4256. return null;
  4257. }
  4258. var i = index * 4;
  4259. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  4260. };
  4261. /**
  4262. * Sets the index-th row of the current matrix with the passed Vector4 values.
  4263. * Returns the updated Matrix.
  4264. */
  4265. Matrix.prototype.setRow = function (index, row) {
  4266. if (index < 0 || index > 3) {
  4267. return this;
  4268. }
  4269. var i = index * 4;
  4270. this.m[i + 0] = row.x;
  4271. this.m[i + 1] = row.y;
  4272. this.m[i + 2] = row.z;
  4273. this.m[i + 3] = row.w;
  4274. this._markAsUpdated();
  4275. return this;
  4276. };
  4277. /**
  4278. * Compute the transpose of the matrix.
  4279. * Returns a new Matrix.
  4280. */
  4281. Matrix.prototype.transpose = function () {
  4282. return Matrix.Transpose(this);
  4283. };
  4284. /**
  4285. * Compute the transpose of the matrix.
  4286. * Returns the current matrix.
  4287. */
  4288. Matrix.prototype.transposeToRef = function (result) {
  4289. Matrix.TransposeToRef(this, result);
  4290. return this;
  4291. };
  4292. /**
  4293. * Sets the index-th row of the current matrix with the passed 4 x float values.
  4294. * Returns the updated Matrix.
  4295. */
  4296. Matrix.prototype.setRowFromFloats = function (index, x, y, z, w) {
  4297. if (index < 0 || index > 3) {
  4298. return this;
  4299. }
  4300. var i = index * 4;
  4301. this.m[i + 0] = x;
  4302. this.m[i + 1] = y;
  4303. this.m[i + 2] = z;
  4304. this.m[i + 3] = w;
  4305. this._markAsUpdated();
  4306. return this;
  4307. };
  4308. Object.defineProperty(Matrix, "IdentityReadOnly", {
  4309. /**
  4310. * Static identity matrix to be used as readonly matrix
  4311. * Must not be updated.
  4312. */
  4313. get: function () {
  4314. return Matrix._identityReadOnly;
  4315. },
  4316. enumerable: true,
  4317. configurable: true
  4318. });
  4319. /**
  4320. * Returns a new Matrix set from the 16 passed floats.
  4321. */
  4322. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  4323. var result = new Matrix();
  4324. result.m[0] = initialM11;
  4325. result.m[1] = initialM12;
  4326. result.m[2] = initialM13;
  4327. result.m[3] = initialM14;
  4328. result.m[4] = initialM21;
  4329. result.m[5] = initialM22;
  4330. result.m[6] = initialM23;
  4331. result.m[7] = initialM24;
  4332. result.m[8] = initialM31;
  4333. result.m[9] = initialM32;
  4334. result.m[10] = initialM33;
  4335. result.m[11] = initialM34;
  4336. result.m[12] = initialM41;
  4337. result.m[13] = initialM42;
  4338. result.m[14] = initialM43;
  4339. result.m[15] = initialM44;
  4340. return result;
  4341. };
  4342. /**
  4343. * Returns a new Matrix composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  4344. */
  4345. Matrix.Compose = function (scale, rotation, translation) {
  4346. var result = Matrix.Identity();
  4347. Matrix.ComposeToRef(scale, rotation, translation, result);
  4348. return result;
  4349. };
  4350. /**
  4351. * Update a Matrix with values composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  4352. */
  4353. Matrix.ComposeToRef = function (scale, rotation, translation, result) {
  4354. Matrix.FromValuesToRef(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[1]);
  4355. rotation.toRotationMatrix(MathTmp.Matrix[0]);
  4356. MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0], result);
  4357. result.setTranslation(translation);
  4358. };
  4359. /**
  4360. * Returns a new indentity Matrix.
  4361. */
  4362. Matrix.Identity = function () {
  4363. 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);
  4364. };
  4365. /**
  4366. * Sets the passed "result" as an identity matrix.
  4367. */
  4368. Matrix.IdentityToRef = function (result) {
  4369. 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);
  4370. };
  4371. /**
  4372. * Returns a new zero Matrix.
  4373. */
  4374. Matrix.Zero = function () {
  4375. 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);
  4376. };
  4377. /**
  4378. * Returns a new rotation matrix for "angle" radians around the X axis.
  4379. */
  4380. Matrix.RotationX = function (angle) {
  4381. var result = new Matrix();
  4382. Matrix.RotationXToRef(angle, result);
  4383. return result;
  4384. };
  4385. /**
  4386. * Returns a new Matrix as the passed inverted one.
  4387. */
  4388. Matrix.Invert = function (source) {
  4389. var result = new Matrix();
  4390. source.invertToRef(result);
  4391. return result;
  4392. };
  4393. /**
  4394. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the X axis.
  4395. */
  4396. Matrix.RotationXToRef = function (angle, result) {
  4397. var s = Math.sin(angle);
  4398. var c = Math.cos(angle);
  4399. result.m[0] = 1.0;
  4400. result.m[15] = 1.0;
  4401. result.m[5] = c;
  4402. result.m[10] = c;
  4403. result.m[9] = -s;
  4404. result.m[6] = s;
  4405. result.m[1] = 0.0;
  4406. result.m[2] = 0.0;
  4407. result.m[3] = 0.0;
  4408. result.m[4] = 0.0;
  4409. result.m[7] = 0.0;
  4410. result.m[8] = 0.0;
  4411. result.m[11] = 0.0;
  4412. result.m[12] = 0.0;
  4413. result.m[13] = 0.0;
  4414. result.m[14] = 0.0;
  4415. result._markAsUpdated();
  4416. };
  4417. /**
  4418. * Returns a new rotation matrix for "angle" radians around the Y axis.
  4419. */
  4420. Matrix.RotationY = function (angle) {
  4421. var result = new Matrix();
  4422. Matrix.RotationYToRef(angle, result);
  4423. return result;
  4424. };
  4425. /**
  4426. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Y axis.
  4427. */
  4428. Matrix.RotationYToRef = function (angle, result) {
  4429. var s = Math.sin(angle);
  4430. var c = Math.cos(angle);
  4431. result.m[5] = 1.0;
  4432. result.m[15] = 1.0;
  4433. result.m[0] = c;
  4434. result.m[2] = -s;
  4435. result.m[8] = s;
  4436. result.m[10] = c;
  4437. result.m[1] = 0.0;
  4438. result.m[3] = 0.0;
  4439. result.m[4] = 0.0;
  4440. result.m[6] = 0.0;
  4441. result.m[7] = 0.0;
  4442. result.m[9] = 0.0;
  4443. result.m[11] = 0.0;
  4444. result.m[12] = 0.0;
  4445. result.m[13] = 0.0;
  4446. result.m[14] = 0.0;
  4447. result._markAsUpdated();
  4448. };
  4449. /**
  4450. * Returns a new rotation matrix for "angle" radians around the Z axis.
  4451. */
  4452. Matrix.RotationZ = function (angle) {
  4453. var result = new Matrix();
  4454. Matrix.RotationZToRef(angle, result);
  4455. return result;
  4456. };
  4457. /**
  4458. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Z axis.
  4459. */
  4460. Matrix.RotationZToRef = function (angle, result) {
  4461. var s = Math.sin(angle);
  4462. var c = Math.cos(angle);
  4463. result.m[10] = 1.0;
  4464. result.m[15] = 1.0;
  4465. result.m[0] = c;
  4466. result.m[1] = s;
  4467. result.m[4] = -s;
  4468. result.m[5] = c;
  4469. result.m[2] = 0.0;
  4470. result.m[3] = 0.0;
  4471. result.m[6] = 0.0;
  4472. result.m[7] = 0.0;
  4473. result.m[8] = 0.0;
  4474. result.m[9] = 0.0;
  4475. result.m[11] = 0.0;
  4476. result.m[12] = 0.0;
  4477. result.m[13] = 0.0;
  4478. result.m[14] = 0.0;
  4479. result._markAsUpdated();
  4480. };
  4481. /**
  4482. * Returns a new rotation matrix for "angle" radians around the passed axis.
  4483. */
  4484. Matrix.RotationAxis = function (axis, angle) {
  4485. var result = Matrix.Zero();
  4486. Matrix.RotationAxisToRef(axis, angle, result);
  4487. return result;
  4488. };
  4489. /**
  4490. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the passed axis.
  4491. */
  4492. Matrix.RotationAxisToRef = function (axis, angle, result) {
  4493. var s = Math.sin(-angle);
  4494. var c = Math.cos(-angle);
  4495. var c1 = 1 - c;
  4496. axis.normalize();
  4497. result.m[0] = (axis.x * axis.x) * c1 + c;
  4498. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  4499. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  4500. result.m[3] = 0.0;
  4501. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  4502. result.m[5] = (axis.y * axis.y) * c1 + c;
  4503. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  4504. result.m[7] = 0.0;
  4505. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  4506. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  4507. result.m[10] = (axis.z * axis.z) * c1 + c;
  4508. result.m[11] = 0.0;
  4509. result.m[15] = 1.0;
  4510. result._markAsUpdated();
  4511. };
  4512. /**
  4513. * Returns a new Matrix as a rotation matrix from the Euler angles (y, x, z).
  4514. */
  4515. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  4516. var result = new Matrix();
  4517. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  4518. return result;
  4519. };
  4520. /**
  4521. * Sets the passed matrix "result" as a rotation matrix from the Euler angles (y, x, z).
  4522. */
  4523. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  4524. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  4525. this._tempQuaternion.toRotationMatrix(result);
  4526. };
  4527. /**
  4528. * Returns a new Matrix as a scaling matrix from the passed floats (x, y, z).
  4529. */
  4530. Matrix.Scaling = function (x, y, z) {
  4531. var result = Matrix.Zero();
  4532. Matrix.ScalingToRef(x, y, z, result);
  4533. return result;
  4534. };
  4535. /**
  4536. * Sets the passed matrix "result" as a scaling matrix from the passed floats (x, y, z).
  4537. */
  4538. Matrix.ScalingToRef = function (x, y, z, result) {
  4539. result.m[0] = x;
  4540. result.m[1] = 0.0;
  4541. result.m[2] = 0.0;
  4542. result.m[3] = 0.0;
  4543. result.m[4] = 0.0;
  4544. result.m[5] = y;
  4545. result.m[6] = 0.0;
  4546. result.m[7] = 0.0;
  4547. result.m[8] = 0.0;
  4548. result.m[9] = 0.0;
  4549. result.m[10] = z;
  4550. result.m[11] = 0.0;
  4551. result.m[12] = 0.0;
  4552. result.m[13] = 0.0;
  4553. result.m[14] = 0.0;
  4554. result.m[15] = 1.0;
  4555. result._markAsUpdated();
  4556. };
  4557. /**
  4558. * Returns a new Matrix as a translation matrix from the passed floats (x, y, z).
  4559. */
  4560. Matrix.Translation = function (x, y, z) {
  4561. var result = Matrix.Identity();
  4562. Matrix.TranslationToRef(x, y, z, result);
  4563. return result;
  4564. };
  4565. /**
  4566. * Sets the passed matrix "result" as a translation matrix from the passed floats (x, y, z).
  4567. */
  4568. Matrix.TranslationToRef = function (x, y, z, result) {
  4569. 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);
  4570. };
  4571. /**
  4572. * Returns a new Matrix whose values are the interpolated values for "gradien" (float) between the ones of the matrices "startValue" and "endValue".
  4573. */
  4574. Matrix.Lerp = function (startValue, endValue, gradient) {
  4575. var result = Matrix.Zero();
  4576. for (var index = 0; index < 16; index++) {
  4577. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  4578. }
  4579. result._markAsUpdated();
  4580. return result;
  4581. };
  4582. /**
  4583. * Returns a new Matrix whose values are computed by :
  4584. * - decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices,
  4585. * - interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end,
  4586. * - recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices.
  4587. */
  4588. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  4589. var startScale = new Vector3(0, 0, 0);
  4590. var startRotation = new Quaternion();
  4591. var startTranslation = new Vector3(0, 0, 0);
  4592. startValue.decompose(startScale, startRotation, startTranslation);
  4593. var endScale = new Vector3(0, 0, 0);
  4594. var endRotation = new Quaternion();
  4595. var endTranslation = new Vector3(0, 0, 0);
  4596. endValue.decompose(endScale, endRotation, endTranslation);
  4597. var resultScale = Vector3.Lerp(startScale, endScale, gradient);
  4598. var resultRotation = Quaternion.Slerp(startRotation, endRotation, gradient);
  4599. var resultTranslation = Vector3.Lerp(startTranslation, endTranslation, gradient);
  4600. return Matrix.Compose(resultScale, resultRotation, resultTranslation);
  4601. };
  4602. /**
  4603. * 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".
  4604. * This methods works for a Left-Handed system.
  4605. */
  4606. Matrix.LookAtLH = function (eye, target, up) {
  4607. var result = Matrix.Zero();
  4608. Matrix.LookAtLHToRef(eye, target, up, result);
  4609. return result;
  4610. };
  4611. /**
  4612. * 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".
  4613. * This methods works for a Left-Handed system.
  4614. */
  4615. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  4616. // Z axis
  4617. target.subtractToRef(eye, this._zAxis);
  4618. this._zAxis.normalize();
  4619. // X axis
  4620. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  4621. if (this._xAxis.lengthSquared() === 0) {
  4622. this._xAxis.x = 1.0;
  4623. }
  4624. else {
  4625. this._xAxis.normalize();
  4626. }
  4627. // Y axis
  4628. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  4629. this._yAxis.normalize();
  4630. // Eye angles
  4631. var ex = -Vector3.Dot(this._xAxis, eye);
  4632. var ey = -Vector3.Dot(this._yAxis, eye);
  4633. var ez = -Vector3.Dot(this._zAxis, eye);
  4634. 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);
  4635. };
  4636. /**
  4637. * 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".
  4638. * This methods works for a Right-Handed system.
  4639. */
  4640. Matrix.LookAtRH = function (eye, target, up) {
  4641. var result = Matrix.Zero();
  4642. Matrix.LookAtRHToRef(eye, target, up, result);
  4643. return result;
  4644. };
  4645. /**
  4646. * 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".
  4647. * This methods works for a Left-Handed system.
  4648. */
  4649. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  4650. // Z axis
  4651. eye.subtractToRef(target, this._zAxis);
  4652. this._zAxis.normalize();
  4653. // X axis
  4654. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  4655. if (this._xAxis.lengthSquared() === 0) {
  4656. this._xAxis.x = 1.0;
  4657. }
  4658. else {
  4659. this._xAxis.normalize();
  4660. }
  4661. // Y axis
  4662. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  4663. this._yAxis.normalize();
  4664. // Eye angles
  4665. var ex = -Vector3.Dot(this._xAxis, eye);
  4666. var ey = -Vector3.Dot(this._yAxis, eye);
  4667. var ez = -Vector3.Dot(this._zAxis, eye);
  4668. 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);
  4669. };
  4670. /**
  4671. * 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.
  4672. */
  4673. Matrix.OrthoLH = function (width, height, znear, zfar) {
  4674. var matrix = Matrix.Zero();
  4675. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  4676. return matrix;
  4677. };
  4678. /**
  4679. * 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.
  4680. */
  4681. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  4682. var n = znear;
  4683. var f = zfar;
  4684. var a = 2.0 / width;
  4685. var b = 2.0 / height;
  4686. var c = 2.0 / (f - n);
  4687. var d = -(f + n) / (f - n);
  4688. 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);
  4689. };
  4690. /**
  4691. * 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.
  4692. */
  4693. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  4694. var matrix = Matrix.Zero();
  4695. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  4696. return matrix;
  4697. };
  4698. /**
  4699. * 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.
  4700. */
  4701. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  4702. var n = znear;
  4703. var f = zfar;
  4704. var a = 2.0 / (right - left);
  4705. var b = 2.0 / (top - bottom);
  4706. var c = 2.0 / (f - n);
  4707. var d = -(f + n) / (f - n);
  4708. var i0 = (left + right) / (left - right);
  4709. var i1 = (top + bottom) / (bottom - top);
  4710. 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);
  4711. };
  4712. /**
  4713. * 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.
  4714. */
  4715. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  4716. var matrix = Matrix.Zero();
  4717. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  4718. return matrix;
  4719. };
  4720. /**
  4721. * 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.
  4722. */
  4723. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  4724. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  4725. result.m[10] *= -1.0;
  4726. };
  4727. /**
  4728. * 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.
  4729. */
  4730. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  4731. var matrix = Matrix.Zero();
  4732. var n = znear;
  4733. var f = zfar;
  4734. var a = 2.0 * n / width;
  4735. var b = 2.0 * n / height;
  4736. var c = (f + n) / (f - n);
  4737. var d = -2.0 * f * n / (f - n);
  4738. 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);
  4739. return matrix;
  4740. };
  4741. /**
  4742. * 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.
  4743. */
  4744. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  4745. var matrix = Matrix.Zero();
  4746. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  4747. return matrix;
  4748. };
  4749. /**
  4750. * 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.
  4751. */
  4752. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  4753. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  4754. var n = znear;
  4755. var f = zfar;
  4756. var t = 1.0 / (Math.tan(fov * 0.5));
  4757. var a = isVerticalFovFixed ? (t / aspect) : t;
  4758. var b = isVerticalFovFixed ? t : (t * aspect);
  4759. var c = (f + n) / (f - n);
  4760. var d = -2.0 * f * n / (f - n);
  4761. 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);
  4762. };
  4763. /**
  4764. * 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.
  4765. */
  4766. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  4767. var matrix = Matrix.Zero();
  4768. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  4769. return matrix;
  4770. };
  4771. /**
  4772. * 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.
  4773. */
  4774. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  4775. //alternatively this could be expressed as:
  4776. // m = PerspectiveFovLHToRef
  4777. // m[10] *= -1.0;
  4778. // m[11] *= -1.0;
  4779. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  4780. var n = znear;
  4781. var f = zfar;
  4782. var t = 1.0 / (Math.tan(fov * 0.5));
  4783. var a = isVerticalFovFixed ? (t / aspect) : t;
  4784. var b = isVerticalFovFixed ? t : (t * aspect);
  4785. var c = -(f + n) / (f - n);
  4786. var d = -2 * f * n / (f - n);
  4787. 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);
  4788. };
  4789. /**
  4790. * 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.
  4791. */
  4792. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, rightHanded) {
  4793. if (rightHanded === void 0) { rightHanded = false; }
  4794. var rightHandedFactor = rightHanded ? -1 : 1;
  4795. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  4796. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  4797. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  4798. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  4799. var xScale = 2.0 / (leftTan + rightTan);
  4800. var yScale = 2.0 / (upTan + downTan);
  4801. result.m[0] = xScale;
  4802. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  4803. result.m[5] = yScale;
  4804. result.m[6] = result.m[7] = 0.0;
  4805. result.m[8] = ((leftTan - rightTan) * xScale * 0.5); // * rightHandedFactor;
  4806. result.m[9] = -((upTan - downTan) * yScale * 0.5); // * rightHandedFactor;
  4807. //result.m[10] = -(znear + zfar) / (zfar - znear) * rightHandedFactor;
  4808. result.m[10] = -zfar / (znear - zfar);
  4809. result.m[11] = 1.0 * rightHandedFactor;
  4810. result.m[12] = result.m[13] = result.m[15] = 0.0;
  4811. result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  4812. // result.m[14] = (znear * zfar) / (znear - zfar);
  4813. result._markAsUpdated();
  4814. };
  4815. /**
  4816. * Returns the final transformation matrix : world * view * projection * viewport
  4817. */
  4818. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  4819. var cw = viewport.width;
  4820. var ch = viewport.height;
  4821. var cx = viewport.x;
  4822. var cy = viewport.y;
  4823. 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);
  4824. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  4825. };
  4826. /**
  4827. * Returns a new Float32Array array with 4 elements : the 2x2 matrix extracted from the passed Matrix.
  4828. */
  4829. Matrix.GetAsMatrix2x2 = function (matrix) {
  4830. return new Float32Array([
  4831. matrix.m[0], matrix.m[1],
  4832. matrix.m[4], matrix.m[5]
  4833. ]);
  4834. };
  4835. /**
  4836. * Returns a new Float32Array array with 9 elements : the 3x3 matrix extracted from the passed Matrix.
  4837. */
  4838. Matrix.GetAsMatrix3x3 = function (matrix) {
  4839. return new Float32Array([
  4840. matrix.m[0], matrix.m[1], matrix.m[2],
  4841. matrix.m[4], matrix.m[5], matrix.m[6],
  4842. matrix.m[8], matrix.m[9], matrix.m[10]
  4843. ]);
  4844. };
  4845. /**
  4846. * Compute the transpose of the passed Matrix.
  4847. * Returns a new Matrix.
  4848. */
  4849. Matrix.Transpose = function (matrix) {
  4850. var result = new Matrix();
  4851. Matrix.TransposeToRef(matrix, result);
  4852. return result;
  4853. };
  4854. /**
  4855. * Compute the transpose of the passed Matrix and store it in the result matrix.
  4856. */
  4857. Matrix.TransposeToRef = function (matrix, result) {
  4858. result.m[0] = matrix.m[0];
  4859. result.m[1] = matrix.m[4];
  4860. result.m[2] = matrix.m[8];
  4861. result.m[3] = matrix.m[12];
  4862. result.m[4] = matrix.m[1];
  4863. result.m[5] = matrix.m[5];
  4864. result.m[6] = matrix.m[9];
  4865. result.m[7] = matrix.m[13];
  4866. result.m[8] = matrix.m[2];
  4867. result.m[9] = matrix.m[6];
  4868. result.m[10] = matrix.m[10];
  4869. result.m[11] = matrix.m[14];
  4870. result.m[12] = matrix.m[3];
  4871. result.m[13] = matrix.m[7];
  4872. result.m[14] = matrix.m[11];
  4873. result.m[15] = matrix.m[15];
  4874. };
  4875. /**
  4876. * Returns a new Matrix as the reflection matrix across the passed plane.
  4877. */
  4878. Matrix.Reflection = function (plane) {
  4879. var matrix = new Matrix();
  4880. Matrix.ReflectionToRef(plane, matrix);
  4881. return matrix;
  4882. };
  4883. /**
  4884. * Sets the passed matrix "result" as the reflection matrix across the passed plane.
  4885. */
  4886. Matrix.ReflectionToRef = function (plane, result) {
  4887. plane.normalize();
  4888. var x = plane.normal.x;
  4889. var y = plane.normal.y;
  4890. var z = plane.normal.z;
  4891. var temp = -2 * x;
  4892. var temp2 = -2 * y;
  4893. var temp3 = -2 * z;
  4894. result.m[0] = (temp * x) + 1;
  4895. result.m[1] = temp2 * x;
  4896. result.m[2] = temp3 * x;
  4897. result.m[3] = 0.0;
  4898. result.m[4] = temp * y;
  4899. result.m[5] = (temp2 * y) + 1;
  4900. result.m[6] = temp3 * y;
  4901. result.m[7] = 0.0;
  4902. result.m[8] = temp * z;
  4903. result.m[9] = temp2 * z;
  4904. result.m[10] = (temp3 * z) + 1;
  4905. result.m[11] = 0.0;
  4906. result.m[12] = temp * plane.d;
  4907. result.m[13] = temp2 * plane.d;
  4908. result.m[14] = temp3 * plane.d;
  4909. result.m[15] = 1.0;
  4910. result._markAsUpdated();
  4911. };
  4912. /**
  4913. * Sets the passed matrix "mat" as a rotation matrix composed from the 3 passed left handed axis.
  4914. */
  4915. Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, result) {
  4916. result.m[0] = xaxis.x;
  4917. result.m[1] = xaxis.y;
  4918. result.m[2] = xaxis.z;
  4919. result.m[3] = 0.0;
  4920. result.m[4] = yaxis.x;
  4921. result.m[5] = yaxis.y;
  4922. result.m[6] = yaxis.z;
  4923. result.m[7] = 0.0;
  4924. result.m[8] = zaxis.x;
  4925. result.m[9] = zaxis.y;
  4926. result.m[10] = zaxis.z;
  4927. result.m[11] = 0.0;
  4928. result.m[12] = 0.0;
  4929. result.m[13] = 0.0;
  4930. result.m[14] = 0.0;
  4931. result.m[15] = 1.0;
  4932. result._markAsUpdated();
  4933. };
  4934. /**
  4935. * Sets the passed matrix "result" as a rotation matrix according to the passed quaternion.
  4936. */
  4937. Matrix.FromQuaternionToRef = function (quat, result) {
  4938. var xx = quat.x * quat.x;
  4939. var yy = quat.y * quat.y;
  4940. var zz = quat.z * quat.z;
  4941. var xy = quat.x * quat.y;
  4942. var zw = quat.z * quat.w;
  4943. var zx = quat.z * quat.x;
  4944. var yw = quat.y * quat.w;
  4945. var yz = quat.y * quat.z;
  4946. var xw = quat.x * quat.w;
  4947. result.m[0] = 1.0 - (2.0 * (yy + zz));
  4948. result.m[1] = 2.0 * (xy + zw);
  4949. result.m[2] = 2.0 * (zx - yw);
  4950. result.m[3] = 0.0;
  4951. result.m[4] = 2.0 * (xy - zw);
  4952. result.m[5] = 1.0 - (2.0 * (zz + xx));
  4953. result.m[6] = 2.0 * (yz + xw);
  4954. result.m[7] = 0.0;
  4955. result.m[8] = 2.0 * (zx + yw);
  4956. result.m[9] = 2.0 * (yz - xw);
  4957. result.m[10] = 1.0 - (2.0 * (yy + xx));
  4958. result.m[11] = 0.0;
  4959. result.m[12] = 0.0;
  4960. result.m[13] = 0.0;
  4961. result.m[14] = 0.0;
  4962. result.m[15] = 1.0;
  4963. result._markAsUpdated();
  4964. };
  4965. Matrix._tempQuaternion = new Quaternion();
  4966. Matrix._xAxis = Vector3.Zero();
  4967. Matrix._yAxis = Vector3.Zero();
  4968. Matrix._zAxis = Vector3.Zero();
  4969. Matrix._updateFlagSeed = 0;
  4970. Matrix._identityReadOnly = Matrix.Identity();
  4971. return Matrix;
  4972. }());
  4973. BABYLON.Matrix = Matrix;
  4974. var Plane = /** @class */ (function () {
  4975. /**
  4976. * Creates a Plane object according to the passed floats a, b, c, d and the plane equation : ax + by + cz + d = 0
  4977. */
  4978. function Plane(a, b, c, d) {
  4979. this.normal = new Vector3(a, b, c);
  4980. this.d = d;
  4981. }
  4982. /**
  4983. * Returns the plane coordinates as a new array of 4 elements [a, b, c, d].
  4984. */
  4985. Plane.prototype.asArray = function () {
  4986. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  4987. };
  4988. // Methods
  4989. /**
  4990. * Returns a new plane copied from the current Plane.
  4991. */
  4992. Plane.prototype.clone = function () {
  4993. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  4994. };
  4995. /**
  4996. * Returns the string "Plane".
  4997. */
  4998. Plane.prototype.getClassName = function () {
  4999. return "Plane";
  5000. };
  5001. /**
  5002. * Returns the Plane hash code.
  5003. */
  5004. Plane.prototype.getHashCode = function () {
  5005. var hash = this.normal.getHashCode();
  5006. hash = (hash * 397) ^ (this.d || 0);
  5007. return hash;
  5008. };
  5009. /**
  5010. * Normalize the current Plane in place.
  5011. * Returns the updated Plane.
  5012. */
  5013. Plane.prototype.normalize = function () {
  5014. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  5015. var magnitude = 0.0;
  5016. if (norm !== 0) {
  5017. magnitude = 1.0 / norm;
  5018. }
  5019. this.normal.x *= magnitude;
  5020. this.normal.y *= magnitude;
  5021. this.normal.z *= magnitude;
  5022. this.d *= magnitude;
  5023. return this;
  5024. };
  5025. /**
  5026. * Returns a new Plane as the result of the transformation of the current Plane by the passed matrix.
  5027. */
  5028. Plane.prototype.transform = function (transformation) {
  5029. var transposedMatrix = Matrix.Transpose(transformation);
  5030. var x = this.normal.x;
  5031. var y = this.normal.y;
  5032. var z = this.normal.z;
  5033. var d = this.d;
  5034. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  5035. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  5036. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  5037. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  5038. return new Plane(normalX, normalY, normalZ, finalD);
  5039. };
  5040. /**
  5041. * Returns the dot product (float) of the point coordinates and the plane normal.
  5042. */
  5043. Plane.prototype.dotCoordinate = function (point) {
  5044. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  5045. };
  5046. /**
  5047. * Updates the current Plane from the plane defined by the three passed points.
  5048. * Returns the updated Plane.
  5049. */
  5050. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  5051. var x1 = point2.x - point1.x;
  5052. var y1 = point2.y - point1.y;
  5053. var z1 = point2.z - point1.z;
  5054. var x2 = point3.x - point1.x;
  5055. var y2 = point3.y - point1.y;
  5056. var z2 = point3.z - point1.z;
  5057. var yz = (y1 * z2) - (z1 * y2);
  5058. var xz = (z1 * x2) - (x1 * z2);
  5059. var xy = (x1 * y2) - (y1 * x2);
  5060. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  5061. var invPyth;
  5062. if (pyth !== 0) {
  5063. invPyth = 1.0 / pyth;
  5064. }
  5065. else {
  5066. invPyth = 0.0;
  5067. }
  5068. this.normal.x = yz * invPyth;
  5069. this.normal.y = xz * invPyth;
  5070. this.normal.z = xy * invPyth;
  5071. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  5072. return this;
  5073. };
  5074. /**
  5075. * Boolean : True is the vector "direction" is the same side than the plane normal.
  5076. */
  5077. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  5078. var dot = Vector3.Dot(this.normal, direction);
  5079. return (dot <= epsilon);
  5080. };
  5081. /**
  5082. * Returns the signed distance (float) from the passed point to the Plane.
  5083. */
  5084. Plane.prototype.signedDistanceTo = function (point) {
  5085. return Vector3.Dot(point, this.normal) + this.d;
  5086. };
  5087. // Statics
  5088. /**
  5089. * Returns a new Plane from the passed array.
  5090. */
  5091. Plane.FromArray = function (array) {
  5092. return new Plane(array[0], array[1], array[2], array[3]);
  5093. };
  5094. /**
  5095. * Returns a new Plane defined by the three passed points.
  5096. */
  5097. Plane.FromPoints = function (point1, point2, point3) {
  5098. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  5099. result.copyFromPoints(point1, point2, point3);
  5100. return result;
  5101. };
  5102. /**
  5103. * Returns a new Plane the normal vector to this plane at the passed origin point.
  5104. * Note : the vector "normal" is updated because normalized.
  5105. */
  5106. Plane.FromPositionAndNormal = function (origin, normal) {
  5107. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  5108. normal.normalize();
  5109. result.normal = normal;
  5110. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  5111. return result;
  5112. };
  5113. /**
  5114. * Returns the signed distance between the plane defined by the normal vector at the "origin"" point and the passed other point.
  5115. */
  5116. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  5117. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  5118. return Vector3.Dot(point, normal) + d;
  5119. };
  5120. return Plane;
  5121. }());
  5122. BABYLON.Plane = Plane;
  5123. var Viewport = /** @class */ (function () {
  5124. /**
  5125. * Creates a Viewport object located at (x, y) and sized (width, height).
  5126. */
  5127. function Viewport(x, y, width, height) {
  5128. this.x = x;
  5129. this.y = y;
  5130. this.width = width;
  5131. this.height = height;
  5132. }
  5133. Viewport.prototype.toGlobal = function (renderWidthOrEngine, renderHeight) {
  5134. if (renderWidthOrEngine.getRenderWidth) {
  5135. var engine = renderWidthOrEngine;
  5136. return this.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  5137. }
  5138. var renderWidth = renderWidthOrEngine;
  5139. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  5140. };
  5141. /**
  5142. * Returns a new Viewport copied from the current one.
  5143. */
  5144. Viewport.prototype.clone = function () {
  5145. return new Viewport(this.x, this.y, this.width, this.height);
  5146. };
  5147. return Viewport;
  5148. }());
  5149. BABYLON.Viewport = Viewport;
  5150. var Frustum = /** @class */ (function () {
  5151. function Frustum() {
  5152. }
  5153. /**
  5154. * Returns a new array of 6 Frustum planes computed by the passed transformation matrix.
  5155. */
  5156. Frustum.GetPlanes = function (transform) {
  5157. var frustumPlanes = [];
  5158. for (var index = 0; index < 6; index++) {
  5159. frustumPlanes.push(new Plane(0.0, 0.0, 0.0, 0.0));
  5160. }
  5161. Frustum.GetPlanesToRef(transform, frustumPlanes);
  5162. return frustumPlanes;
  5163. };
  5164. Frustum.GetNearPlaneToRef = function (transform, frustumPlane) {
  5165. frustumPlane.normal.x = transform.m[3] + transform.m[2];
  5166. frustumPlane.normal.y = transform.m[7] + transform.m[6];
  5167. frustumPlane.normal.z = transform.m[11] + transform.m[10];
  5168. frustumPlane.d = transform.m[15] + transform.m[14];
  5169. frustumPlane.normalize();
  5170. };
  5171. Frustum.GetFarPlaneToRef = function (transform, frustumPlane) {
  5172. frustumPlane.normal.x = transform.m[3] - transform.m[2];
  5173. frustumPlane.normal.y = transform.m[7] - transform.m[6];
  5174. frustumPlane.normal.z = transform.m[11] - transform.m[10];
  5175. frustumPlane.d = transform.m[15] - transform.m[14];
  5176. frustumPlane.normalize();
  5177. };
  5178. Frustum.GetLeftPlaneToRef = function (transform, frustumPlane) {
  5179. frustumPlane.normal.x = transform.m[3] + transform.m[0];
  5180. frustumPlane.normal.y = transform.m[7] + transform.m[4];
  5181. frustumPlane.normal.z = transform.m[11] + transform.m[8];
  5182. frustumPlane.d = transform.m[15] + transform.m[12];
  5183. frustumPlane.normalize();
  5184. };
  5185. Frustum.GetRightPlaneToRef = function (transform, frustumPlane) {
  5186. frustumPlane.normal.x = transform.m[3] - transform.m[0];
  5187. frustumPlane.normal.y = transform.m[7] - transform.m[4];
  5188. frustumPlane.normal.z = transform.m[11] - transform.m[8];
  5189. frustumPlane.d = transform.m[15] - transform.m[12];
  5190. frustumPlane.normalize();
  5191. };
  5192. Frustum.GetTopPlaneToRef = function (transform, frustumPlane) {
  5193. frustumPlane.normal.x = transform.m[3] - transform.m[1];
  5194. frustumPlane.normal.y = transform.m[7] - transform.m[5];
  5195. frustumPlane.normal.z = transform.m[11] - transform.m[9];
  5196. frustumPlane.d = transform.m[15] - transform.m[13];
  5197. frustumPlane.normalize();
  5198. };
  5199. Frustum.GetBottomPlaneToRef = function (transform, frustumPlane) {
  5200. frustumPlane.normal.x = transform.m[3] + transform.m[1];
  5201. frustumPlane.normal.y = transform.m[7] + transform.m[5];
  5202. frustumPlane.normal.z = transform.m[11] + transform.m[9];
  5203. frustumPlane.d = transform.m[15] + transform.m[13];
  5204. frustumPlane.normalize();
  5205. };
  5206. /**
  5207. * Sets the passed array "frustumPlanes" with the 6 Frustum planes computed by the passed transformation matrix.
  5208. */
  5209. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  5210. // Near
  5211. Frustum.GetNearPlaneToRef(transform, frustumPlanes[0]);
  5212. // Far
  5213. Frustum.GetFarPlaneToRef(transform, frustumPlanes[1]);
  5214. // Left
  5215. Frustum.GetLeftPlaneToRef(transform, frustumPlanes[2]);
  5216. // Right
  5217. Frustum.GetRightPlaneToRef(transform, frustumPlanes[3]);
  5218. // Top
  5219. Frustum.GetTopPlaneToRef(transform, frustumPlanes[4]);
  5220. // Bottom
  5221. Frustum.GetBottomPlaneToRef(transform, frustumPlanes[5]);
  5222. };
  5223. return Frustum;
  5224. }());
  5225. BABYLON.Frustum = Frustum;
  5226. var Space;
  5227. (function (Space) {
  5228. Space[Space["LOCAL"] = 0] = "LOCAL";
  5229. Space[Space["WORLD"] = 1] = "WORLD";
  5230. Space[Space["BONE"] = 2] = "BONE";
  5231. })(Space = BABYLON.Space || (BABYLON.Space = {}));
  5232. var Axis = /** @class */ (function () {
  5233. function Axis() {
  5234. }
  5235. Axis.X = new Vector3(1.0, 0.0, 0.0);
  5236. Axis.Y = new Vector3(0.0, 1.0, 0.0);
  5237. Axis.Z = new Vector3(0.0, 0.0, 1.0);
  5238. return Axis;
  5239. }());
  5240. BABYLON.Axis = Axis;
  5241. ;
  5242. var BezierCurve = /** @class */ (function () {
  5243. function BezierCurve() {
  5244. }
  5245. /**
  5246. * Returns the cubic Bezier interpolated value (float) at "t" (float) from the passed x1, y1, x2, y2 floats.
  5247. */
  5248. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  5249. // Extract X (which is equal to time here)
  5250. var f0 = 1 - 3 * x2 + 3 * x1;
  5251. var f1 = 3 * x2 - 6 * x1;
  5252. var f2 = 3 * x1;
  5253. var refinedT = t;
  5254. for (var i = 0; i < 5; i++) {
  5255. var refinedT2 = refinedT * refinedT;
  5256. var refinedT3 = refinedT2 * refinedT;
  5257. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  5258. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  5259. refinedT -= (x - t) * slope;
  5260. refinedT = Math.min(1, Math.max(0, refinedT));
  5261. }
  5262. // Resolve cubic bezier for the given x
  5263. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  5264. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  5265. Math.pow(refinedT, 3);
  5266. };
  5267. return BezierCurve;
  5268. }());
  5269. BABYLON.BezierCurve = BezierCurve;
  5270. var Orientation;
  5271. (function (Orientation) {
  5272. Orientation[Orientation["CW"] = 0] = "CW";
  5273. Orientation[Orientation["CCW"] = 1] = "CCW";
  5274. })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));
  5275. var Angle = /** @class */ (function () {
  5276. /**
  5277. * Creates an Angle object of "radians" radians (float).
  5278. */
  5279. function Angle(radians) {
  5280. var _this = this;
  5281. /**
  5282. * Returns the Angle value in degrees (float).
  5283. */
  5284. this.degrees = function () { return _this._radians * 180.0 / Math.PI; };
  5285. /**
  5286. * Returns the Angle value in radians (float).
  5287. */
  5288. this.radians = function () { return _this._radians; };
  5289. this._radians = radians;
  5290. if (this._radians < 0.0)
  5291. this._radians += (2.0 * Math.PI);
  5292. }
  5293. /**
  5294. * Returns a new Angle object valued with the angle value in radians between the two passed vectors.
  5295. */
  5296. Angle.BetweenTwoPoints = function (a, b) {
  5297. var delta = b.subtract(a);
  5298. var theta = Math.atan2(delta.y, delta.x);
  5299. return new Angle(theta);
  5300. };
  5301. /**
  5302. * Returns a new Angle object from the passed float in radians.
  5303. */
  5304. Angle.FromRadians = function (radians) {
  5305. return new Angle(radians);
  5306. };
  5307. /**
  5308. * Returns a new Angle object from the passed float in degrees.
  5309. */
  5310. Angle.FromDegrees = function (degrees) {
  5311. return new Angle(degrees * Math.PI / 180.0);
  5312. };
  5313. return Angle;
  5314. }());
  5315. BABYLON.Angle = Angle;
  5316. var Arc2 = /** @class */ (function () {
  5317. /**
  5318. * Creates an Arc object from the three passed points : start, middle and end.
  5319. */
  5320. function Arc2(startPoint, midPoint, endPoint) {
  5321. this.startPoint = startPoint;
  5322. this.midPoint = midPoint;
  5323. this.endPoint = endPoint;
  5324. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  5325. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  5326. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  5327. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  5328. 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);
  5329. this.radius = this.centerPoint.subtract(this.startPoint).length();
  5330. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  5331. var a1 = this.startAngle.degrees();
  5332. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  5333. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  5334. // angles correction
  5335. if (a2 - a1 > +180.0)
  5336. a2 -= 360.0;
  5337. if (a2 - a1 < -180.0)
  5338. a2 += 360.0;
  5339. if (a3 - a2 > +180.0)
  5340. a3 -= 360.0;
  5341. if (a3 - a2 < -180.0)
  5342. a3 += 360.0;
  5343. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  5344. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  5345. }
  5346. return Arc2;
  5347. }());
  5348. BABYLON.Arc2 = Arc2;
  5349. var Path2 = /** @class */ (function () {
  5350. /**
  5351. * Creates a Path2 object from the starting 2D coordinates x and y.
  5352. */
  5353. function Path2(x, y) {
  5354. this._points = new Array();
  5355. this._length = 0.0;
  5356. this.closed = false;
  5357. this._points.push(new Vector2(x, y));
  5358. }
  5359. /**
  5360. * Adds a new segment until the passed coordinates (x, y) to the current Path2.
  5361. * Returns the updated Path2.
  5362. */
  5363. Path2.prototype.addLineTo = function (x, y) {
  5364. if (this.closed) {
  5365. //Tools.Error("cannot add lines to closed paths");
  5366. return this;
  5367. }
  5368. var newPoint = new Vector2(x, y);
  5369. var previousPoint = this._points[this._points.length - 1];
  5370. this._points.push(newPoint);
  5371. this._length += newPoint.subtract(previousPoint).length();
  5372. return this;
  5373. };
  5374. /**
  5375. * 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.
  5376. * Returns the updated Path2.
  5377. */
  5378. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  5379. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  5380. if (this.closed) {
  5381. //Tools.Error("cannot add arcs to closed paths");
  5382. return this;
  5383. }
  5384. var startPoint = this._points[this._points.length - 1];
  5385. var midPoint = new Vector2(midX, midY);
  5386. var endPoint = new Vector2(endX, endY);
  5387. var arc = new Arc2(startPoint, midPoint, endPoint);
  5388. var increment = arc.angle.radians() / numberOfSegments;
  5389. if (arc.orientation === Orientation.CW)
  5390. increment *= -1;
  5391. var currentAngle = arc.startAngle.radians() + increment;
  5392. for (var i = 0; i < numberOfSegments; i++) {
  5393. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  5394. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  5395. this.addLineTo(x, y);
  5396. currentAngle += increment;
  5397. }
  5398. return this;
  5399. };
  5400. /**
  5401. * Closes the Path2.
  5402. * Returns the Path2.
  5403. */
  5404. Path2.prototype.close = function () {
  5405. this.closed = true;
  5406. return this;
  5407. };
  5408. /**
  5409. * Returns the Path2 total length (float).
  5410. */
  5411. Path2.prototype.length = function () {
  5412. var result = this._length;
  5413. if (!this.closed) {
  5414. var lastPoint = this._points[this._points.length - 1];
  5415. var firstPoint = this._points[0];
  5416. result += (firstPoint.subtract(lastPoint).length());
  5417. }
  5418. return result;
  5419. };
  5420. /**
  5421. * Returns the Path2 internal array of points.
  5422. */
  5423. Path2.prototype.getPoints = function () {
  5424. return this._points;
  5425. };
  5426. /**
  5427. * Returns a new Vector2 located at a percentage of the Path2 total length on this path.
  5428. */
  5429. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  5430. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  5431. //Tools.Error("normalized length position should be between 0 and 1.");
  5432. return Vector2.Zero();
  5433. }
  5434. var lengthPosition = normalizedLengthPosition * this.length();
  5435. var previousOffset = 0;
  5436. for (var i = 0; i < this._points.length; i++) {
  5437. var j = (i + 1) % this._points.length;
  5438. var a = this._points[i];
  5439. var b = this._points[j];
  5440. var bToA = b.subtract(a);
  5441. var nextOffset = (bToA.length() + previousOffset);
  5442. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  5443. var dir = bToA.normalize();
  5444. var localOffset = lengthPosition - previousOffset;
  5445. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  5446. }
  5447. previousOffset = nextOffset;
  5448. }
  5449. //Tools.Error("internal error");
  5450. return Vector2.Zero();
  5451. };
  5452. /**
  5453. * Returns a new Path2 starting at the coordinates (x, y).
  5454. */
  5455. Path2.StartingAt = function (x, y) {
  5456. return new Path2(x, y);
  5457. };
  5458. return Path2;
  5459. }());
  5460. BABYLON.Path2 = Path2;
  5461. var Path3D = /** @class */ (function () {
  5462. /**
  5463. * new Path3D(path, normal, raw)
  5464. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  5465. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  5466. * path : an array of Vector3, the curve axis of the Path3D
  5467. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  5468. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  5469. */
  5470. function Path3D(path, firstNormal, raw) {
  5471. if (firstNormal === void 0) { firstNormal = null; }
  5472. this.path = path;
  5473. this._curve = new Array();
  5474. this._distances = new Array();
  5475. this._tangents = new Array();
  5476. this._normals = new Array();
  5477. this._binormals = new Array();
  5478. for (var p = 0; p < path.length; p++) {
  5479. this._curve[p] = path[p].clone(); // hard copy
  5480. }
  5481. this._raw = raw || false;
  5482. this._compute(firstNormal);
  5483. }
  5484. /**
  5485. * Returns the Path3D array of successive Vector3 designing its curve.
  5486. */
  5487. Path3D.prototype.getCurve = function () {
  5488. return this._curve;
  5489. };
  5490. /**
  5491. * Returns an array populated with tangent vectors on each Path3D curve point.
  5492. */
  5493. Path3D.prototype.getTangents = function () {
  5494. return this._tangents;
  5495. };
  5496. /**
  5497. * Returns an array populated with normal vectors on each Path3D curve point.
  5498. */
  5499. Path3D.prototype.getNormals = function () {
  5500. return this._normals;
  5501. };
  5502. /**
  5503. * Returns an array populated with binormal vectors on each Path3D curve point.
  5504. */
  5505. Path3D.prototype.getBinormals = function () {
  5506. return this._binormals;
  5507. };
  5508. /**
  5509. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  5510. */
  5511. Path3D.prototype.getDistances = function () {
  5512. return this._distances;
  5513. };
  5514. /**
  5515. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  5516. * Returns the same object updated.
  5517. */
  5518. Path3D.prototype.update = function (path, firstNormal) {
  5519. if (firstNormal === void 0) { firstNormal = null; }
  5520. for (var p = 0; p < path.length; p++) {
  5521. this._curve[p].x = path[p].x;
  5522. this._curve[p].y = path[p].y;
  5523. this._curve[p].z = path[p].z;
  5524. }
  5525. this._compute(firstNormal);
  5526. return this;
  5527. };
  5528. // private function compute() : computes tangents, normals and binormals
  5529. Path3D.prototype._compute = function (firstNormal) {
  5530. var l = this._curve.length;
  5531. // first and last tangents
  5532. this._tangents[0] = this._getFirstNonNullVector(0);
  5533. if (!this._raw) {
  5534. this._tangents[0].normalize();
  5535. }
  5536. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  5537. if (!this._raw) {
  5538. this._tangents[l - 1].normalize();
  5539. }
  5540. // normals and binormals at first point : arbitrary vector with _normalVector()
  5541. var tg0 = this._tangents[0];
  5542. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  5543. this._normals[0] = pp0;
  5544. if (!this._raw) {
  5545. this._normals[0].normalize();
  5546. }
  5547. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  5548. if (!this._raw) {
  5549. this._binormals[0].normalize();
  5550. }
  5551. this._distances[0] = 0.0;
  5552. // normals and binormals : next points
  5553. var prev; // previous vector (segment)
  5554. var cur; // current vector (segment)
  5555. var curTang; // current tangent
  5556. // previous normal
  5557. var prevBinor; // previous binormal
  5558. for (var i = 1; i < l; i++) {
  5559. // tangents
  5560. prev = this._getLastNonNullVector(i);
  5561. if (i < l - 1) {
  5562. cur = this._getFirstNonNullVector(i);
  5563. this._tangents[i] = prev.add(cur);
  5564. this._tangents[i].normalize();
  5565. }
  5566. this._distances[i] = this._distances[i - 1] + prev.length();
  5567. // normals and binormals
  5568. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  5569. curTang = this._tangents[i];
  5570. prevBinor = this._binormals[i - 1];
  5571. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  5572. if (!this._raw) {
  5573. this._normals[i].normalize();
  5574. }
  5575. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  5576. if (!this._raw) {
  5577. this._binormals[i].normalize();
  5578. }
  5579. }
  5580. };
  5581. // private function getFirstNonNullVector(index)
  5582. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  5583. Path3D.prototype._getFirstNonNullVector = function (index) {
  5584. var i = 1;
  5585. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  5586. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  5587. i++;
  5588. nNVector = this._curve[index + i].subtract(this._curve[index]);
  5589. }
  5590. return nNVector;
  5591. };
  5592. // private function getLastNonNullVector(index)
  5593. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  5594. Path3D.prototype._getLastNonNullVector = function (index) {
  5595. var i = 1;
  5596. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  5597. while (nLVector.length() === 0 && index > i + 1) {
  5598. i++;
  5599. nLVector = this._curve[index].subtract(this._curve[index - i]);
  5600. }
  5601. return nLVector;
  5602. };
  5603. // private function normalVector(v0, vt, va) :
  5604. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  5605. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  5606. Path3D.prototype._normalVector = function (v0, vt, va) {
  5607. var normal0;
  5608. var tgl = vt.length();
  5609. if (tgl === 0.0) {
  5610. tgl = 1.0;
  5611. }
  5612. if (va === undefined || va === null) {
  5613. var point;
  5614. if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) {
  5615. point = new Vector3(0.0, -1.0, 0.0);
  5616. }
  5617. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  5618. point = new Vector3(1.0, 0.0, 0.0);
  5619. }
  5620. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  5621. point = new Vector3(0.0, 0.0, 1.0);
  5622. }
  5623. else {
  5624. point = Vector3.Zero();
  5625. }
  5626. normal0 = Vector3.Cross(vt, point);
  5627. }
  5628. else {
  5629. normal0 = Vector3.Cross(vt, va);
  5630. Vector3.CrossToRef(normal0, vt, normal0);
  5631. }
  5632. normal0.normalize();
  5633. return normal0;
  5634. };
  5635. return Path3D;
  5636. }());
  5637. BABYLON.Path3D = Path3D;
  5638. var Curve3 = /** @class */ (function () {
  5639. /**
  5640. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  5641. * A Curve3 is designed from a series of successive Vector3.
  5642. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  5643. */
  5644. function Curve3(points) {
  5645. this._length = 0.0;
  5646. this._points = points;
  5647. this._length = this._computeLength(points);
  5648. }
  5649. /**
  5650. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  5651. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  5652. * @param v1 (Vector3) the control point
  5653. * @param v2 (Vector3) the end point of the Quadratic Bezier
  5654. * @param nbPoints (integer) the wanted number of points in the curve
  5655. */
  5656. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  5657. nbPoints = nbPoints > 2 ? nbPoints : 3;
  5658. var bez = new Array();
  5659. var equation = function (t, val0, val1, val2) {
  5660. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  5661. return res;
  5662. };
  5663. for (var i = 0; i <= nbPoints; i++) {
  5664. 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)));
  5665. }
  5666. return new Curve3(bez);
  5667. };
  5668. /**
  5669. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  5670. * @param v0 (Vector3) the origin point of the Cubic Bezier
  5671. * @param v1 (Vector3) the first control point
  5672. * @param v2 (Vector3) the second control point
  5673. * @param v3 (Vector3) the end point of the Cubic Bezier
  5674. * @param nbPoints (integer) the wanted number of points in the curve
  5675. */
  5676. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  5677. nbPoints = nbPoints > 3 ? nbPoints : 4;
  5678. var bez = new Array();
  5679. var equation = function (t, val0, val1, val2, val3) {
  5680. 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;
  5681. return res;
  5682. };
  5683. for (var i = 0; i <= nbPoints; i++) {
  5684. 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)));
  5685. }
  5686. return new Curve3(bez);
  5687. };
  5688. /**
  5689. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  5690. * @param p1 (Vector3) the origin point of the Hermite Spline
  5691. * @param t1 (Vector3) the tangent vector at the origin point
  5692. * @param p2 (Vector3) the end point of the Hermite Spline
  5693. * @param t2 (Vector3) the tangent vector at the end point
  5694. * @param nbPoints (integer) the wanted number of points in the curve
  5695. */
  5696. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  5697. var hermite = new Array();
  5698. var step = 1.0 / nbPoints;
  5699. for (var i = 0; i <= nbPoints; i++) {
  5700. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  5701. }
  5702. return new Curve3(hermite);
  5703. };
  5704. /**
  5705. * Returns a Curve3 object along a CatmullRom Spline curve :
  5706. * @param points (array of Vector3) the points the spline must pass through. At least, four points required.
  5707. * @param nbPoints (integer) the wanted number of points between each curve control points.
  5708. */
  5709. Curve3.CreateCatmullRomSpline = function (points, nbPoints) {
  5710. var totalPoints = new Array();
  5711. totalPoints.push(points[0].clone());
  5712. Array.prototype.push.apply(totalPoints, points);
  5713. totalPoints.push(points[points.length - 1].clone());
  5714. var catmullRom = new Array();
  5715. var step = 1.0 / nbPoints;
  5716. var amount = 0.0;
  5717. for (var i = 0; i < totalPoints.length - 3; i++) {
  5718. amount = 0;
  5719. for (var c = 0; c < nbPoints; c++) {
  5720. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  5721. amount += step;
  5722. }
  5723. }
  5724. i--;
  5725. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  5726. return new Curve3(catmullRom);
  5727. };
  5728. /**
  5729. * Returns the Curve3 stored array of successive Vector3
  5730. */
  5731. Curve3.prototype.getPoints = function () {
  5732. return this._points;
  5733. };
  5734. /**
  5735. * Returns the computed length (float) of the curve.
  5736. */
  5737. Curve3.prototype.length = function () {
  5738. return this._length;
  5739. };
  5740. /**
  5741. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  5742. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  5743. * curveA and curveB keep unchanged.
  5744. */
  5745. Curve3.prototype.continue = function (curve) {
  5746. var lastPoint = this._points[this._points.length - 1];
  5747. var continuedPoints = this._points.slice();
  5748. var curvePoints = curve.getPoints();
  5749. for (var i = 1; i < curvePoints.length; i++) {
  5750. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  5751. }
  5752. var continuedCurve = new Curve3(continuedPoints);
  5753. return continuedCurve;
  5754. };
  5755. Curve3.prototype._computeLength = function (path) {
  5756. var l = 0;
  5757. for (var i = 1; i < path.length; i++) {
  5758. l += (path[i].subtract(path[i - 1])).length();
  5759. }
  5760. return l;
  5761. };
  5762. return Curve3;
  5763. }());
  5764. BABYLON.Curve3 = Curve3;
  5765. // Vertex formats
  5766. var PositionNormalVertex = /** @class */ (function () {
  5767. function PositionNormalVertex(position, normal) {
  5768. if (position === void 0) { position = Vector3.Zero(); }
  5769. if (normal === void 0) { normal = Vector3.Up(); }
  5770. this.position = position;
  5771. this.normal = normal;
  5772. }
  5773. PositionNormalVertex.prototype.clone = function () {
  5774. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  5775. };
  5776. return PositionNormalVertex;
  5777. }());
  5778. BABYLON.PositionNormalVertex = PositionNormalVertex;
  5779. var PositionNormalTextureVertex = /** @class */ (function () {
  5780. function PositionNormalTextureVertex(position, normal, uv) {
  5781. if (position === void 0) { position = Vector3.Zero(); }
  5782. if (normal === void 0) { normal = Vector3.Up(); }
  5783. if (uv === void 0) { uv = Vector2.Zero(); }
  5784. this.position = position;
  5785. this.normal = normal;
  5786. this.uv = uv;
  5787. }
  5788. PositionNormalTextureVertex.prototype.clone = function () {
  5789. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  5790. };
  5791. return PositionNormalTextureVertex;
  5792. }());
  5793. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  5794. // Temporary pre-allocated objects for engine internal use
  5795. // usage in any internal function :
  5796. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  5797. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  5798. var Tmp = /** @class */ (function () {
  5799. function Tmp() {
  5800. }
  5801. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  5802. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  5803. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  5804. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  5805. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  5806. Tmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero()]; // 2 temp Quaternion at once should be enough
  5807. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  5808. Matrix.Zero(), Matrix.Zero(),
  5809. Matrix.Zero(), Matrix.Zero(),
  5810. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  5811. return Tmp;
  5812. }());
  5813. BABYLON.Tmp = Tmp;
  5814. // Same as Tmp but not exported to keep it onyl for math functions to avoid conflicts
  5815. var MathTmp = /** @class */ (function () {
  5816. function MathTmp() {
  5817. }
  5818. MathTmp.Vector3 = [Vector3.Zero()];
  5819. MathTmp.Matrix = [Matrix.Zero(), Matrix.Zero()];
  5820. MathTmp.Quaternion = [Quaternion.Zero()];
  5821. return MathTmp;
  5822. }());
  5823. })(BABYLON || (BABYLON = {}));
  5824. //# sourceMappingURL=babylon.math.js.map
  5825. var BABYLON;
  5826. (function (BABYLON) {
  5827. var Scalar = /** @class */ (function () {
  5828. function Scalar() {
  5829. }
  5830. /**
  5831. * Boolean : true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
  5832. */
  5833. Scalar.WithinEpsilon = function (a, b, epsilon) {
  5834. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  5835. var num = a - b;
  5836. return -epsilon <= num && num <= epsilon;
  5837. };
  5838. /**
  5839. * Returns a string : the upper case translation of the number i to hexadecimal.
  5840. */
  5841. Scalar.ToHex = function (i) {
  5842. var str = i.toString(16);
  5843. if (i <= 15) {
  5844. return ("0" + str).toUpperCase();
  5845. }
  5846. return str.toUpperCase();
  5847. };
  5848. /**
  5849. * Returns -1 if value is negative and +1 is value is positive.
  5850. * Returns the value itself if it's equal to zero.
  5851. */
  5852. Scalar.Sign = function (value) {
  5853. value = +value; // convert to a number
  5854. if (value === 0 || isNaN(value))
  5855. return value;
  5856. return value > 0 ? 1 : -1;
  5857. };
  5858. /**
  5859. * Returns the value itself if it's between min and max.
  5860. * Returns min if the value is lower than min.
  5861. * Returns max if the value is greater than max.
  5862. */
  5863. Scalar.Clamp = function (value, min, max) {
  5864. if (min === void 0) { min = 0; }
  5865. if (max === void 0) { max = 1; }
  5866. return Math.min(max, Math.max(min, value));
  5867. };
  5868. /**
  5869. * Returns the log2 of value.
  5870. */
  5871. Scalar.Log2 = function (value) {
  5872. return Math.log(value) * Math.LOG2E;
  5873. };
  5874. /**
  5875. * Loops the value, so that it is never larger than length and never smaller than 0.
  5876. *
  5877. * This is similar to the modulo operator but it works with floating point numbers.
  5878. * For example, using 3.0 for t and 2.5 for length, the result would be 0.5.
  5879. * With t = 5 and length = 2.5, the result would be 0.0.
  5880. * Note, however, that the behaviour is not defined for negative numbers as it is for the modulo operator
  5881. */
  5882. Scalar.Repeat = function (value, length) {
  5883. return value - Math.floor(value / length) * length;
  5884. };
  5885. /**
  5886. * Normalize the value between 0.0 and 1.0 using min and max values
  5887. */
  5888. Scalar.Normalize = function (value, min, max) {
  5889. return (value - min) / (max - min);
  5890. };
  5891. /**
  5892. * Denormalize the value from 0.0 and 1.0 using min and max values
  5893. */
  5894. Scalar.Denormalize = function (normalized, min, max) {
  5895. return (normalized * (max - min) + min);
  5896. };
  5897. /**
  5898. * Calculates the shortest difference between two given angles given in degrees.
  5899. */
  5900. Scalar.DeltaAngle = function (current, target) {
  5901. var num = Scalar.Repeat(target - current, 360.0);
  5902. if (num > 180.0) {
  5903. num -= 360.0;
  5904. }
  5905. return num;
  5906. };
  5907. /**
  5908. * PingPongs the value t, so that it is never larger than length and never smaller than 0.
  5909. *
  5910. * The returned value will move back and forth between 0 and length
  5911. */
  5912. Scalar.PingPong = function (tx, length) {
  5913. var t = Scalar.Repeat(tx, length * 2.0);
  5914. return length - Math.abs(t - length);
  5915. };
  5916. /**
  5917. * Interpolates between min and max with smoothing at the limits.
  5918. *
  5919. * This function interpolates between min and max in a similar way to Lerp. However, the interpolation will gradually speed up
  5920. * from the start and slow down toward the end. This is useful for creating natural-looking animation, fading and other transitions.
  5921. */
  5922. Scalar.SmoothStep = function (from, to, tx) {
  5923. var t = Scalar.Clamp(tx);
  5924. t = -2.0 * t * t * t + 3.0 * t * t;
  5925. return to * t + from * (1.0 - t);
  5926. };
  5927. /**
  5928. * Moves a value current towards target.
  5929. *
  5930. * This is essentially the same as Mathf.Lerp but instead the function will ensure that the speed never exceeds maxDelta.
  5931. * Negative values of maxDelta pushes the value away from target.
  5932. */
  5933. Scalar.MoveTowards = function (current, target, maxDelta) {
  5934. var result = 0;
  5935. if (Math.abs(target - current) <= maxDelta) {
  5936. result = target;
  5937. }
  5938. else {
  5939. result = current + Scalar.Sign(target - current) * maxDelta;
  5940. }
  5941. return result;
  5942. };
  5943. /**
  5944. * Same as MoveTowards but makes sure the values interpolate correctly when they wrap around 360 degrees.
  5945. *
  5946. * Variables current and target are assumed to be in degrees. For optimization reasons, negative values of maxDelta
  5947. * are not supported and may cause oscillation. To push current away from a target angle, add 180 to that angle instead.
  5948. */
  5949. Scalar.MoveTowardsAngle = function (current, target, maxDelta) {
  5950. var num = Scalar.DeltaAngle(current, target);
  5951. var result = 0;
  5952. if (-maxDelta < num && num < maxDelta) {
  5953. result = target;
  5954. }
  5955. else {
  5956. target = current + num;
  5957. result = Scalar.MoveTowards(current, target, maxDelta);
  5958. }
  5959. return result;
  5960. };
  5961. /**
  5962. * Creates a new scalar with values linearly interpolated of "amount" between the start scalar and the end scalar.
  5963. */
  5964. Scalar.Lerp = function (start, end, amount) {
  5965. return start + ((end - start) * amount);
  5966. };
  5967. /**
  5968. * Same as Lerp but makes sure the values interpolate correctly when they wrap around 360 degrees.
  5969. * The parameter t is clamped to the range [0, 1]. Variables a and b are assumed to be in degrees.
  5970. */
  5971. Scalar.LerpAngle = function (start, end, amount) {
  5972. var num = Scalar.Repeat(end - start, 360.0);
  5973. if (num > 180.0) {
  5974. num -= 360.0;
  5975. }
  5976. return start + num * Scalar.Clamp(amount);
  5977. };
  5978. /**
  5979. * Calculates the linear parameter t that produces the interpolant value within the range [a, b].
  5980. */
  5981. Scalar.InverseLerp = function (a, b, value) {
  5982. var result = 0;
  5983. if (a != b) {
  5984. result = Scalar.Clamp((value - a) / (b - a));
  5985. }
  5986. else {
  5987. result = 0.0;
  5988. }
  5989. return result;
  5990. };
  5991. /**
  5992. * Returns a new scalar located for "amount" (float) on the Hermite spline defined by the scalars "value1", "value3", "tangent1", "tangent2".
  5993. */
  5994. Scalar.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  5995. var squared = amount * amount;
  5996. var cubed = amount * squared;
  5997. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  5998. var part2 = (-2.0 * cubed) + (3.0 * squared);
  5999. var part3 = (cubed - (2.0 * squared)) + amount;
  6000. var part4 = cubed - squared;
  6001. return (((value1 * part1) + (value2 * part2)) + (tangent1 * part3)) + (tangent2 * part4);
  6002. };
  6003. /**
  6004. * Returns a random float number between and min and max values
  6005. */
  6006. Scalar.RandomRange = function (min, max) {
  6007. if (min === max)
  6008. return min;
  6009. return ((Math.random() * (max - min)) + min);
  6010. };
  6011. /**
  6012. * This function returns percentage of a number in a given range.
  6013. *
  6014. * RangeToPercent(40,20,60) will return 0.5 (50%)
  6015. * RangeToPercent(34,0,100) will return 0.34 (34%)
  6016. */
  6017. Scalar.RangeToPercent = function (number, min, max) {
  6018. return ((number - min) / (max - min));
  6019. };
  6020. /**
  6021. * This function returns number that corresponds to the percentage in a given range.
  6022. *
  6023. * PercentToRange(0.34,0,100) will return 34.
  6024. */
  6025. Scalar.PercentToRange = function (percent, min, max) {
  6026. return ((max - min) * percent + min);
  6027. };
  6028. /**
  6029. * Returns the angle converted to equivalent value between -Math.PI and Math.PI radians.
  6030. * @param angle The angle to normalize in radian.
  6031. * @return The converted angle.
  6032. */
  6033. Scalar.NormalizeRadians = function (angle) {
  6034. // More precise but slower version kept for reference.
  6035. // angle = angle % Tools.TwoPi;
  6036. // angle = (angle + Tools.TwoPi) % Tools.TwoPi;
  6037. //if (angle > Math.PI) {
  6038. // angle -= Tools.TwoPi;
  6039. //}
  6040. angle -= (Scalar.TwoPi * Math.floor((angle + Math.PI) / Scalar.TwoPi));
  6041. return angle;
  6042. };
  6043. /**
  6044. * Two pi constants convenient for computation.
  6045. */
  6046. Scalar.TwoPi = Math.PI * 2;
  6047. return Scalar;
  6048. }());
  6049. BABYLON.Scalar = Scalar;
  6050. })(BABYLON || (BABYLON = {}));
  6051. //# sourceMappingURL=babylon.math.scalar.js.map
  6052. //# sourceMappingURL=babylon.mixins.js.map
  6053. // Type definitions for WebGL 2, Editor's Draft Fri Feb 24 16:10:18 2017 -0800
  6054. // Project: https://www.khronos.org/registry/webgl/specs/latest/2.0/
  6055. // Definitions by: Nico Kemnitz <https://github.com/nkemnitz/>
  6056. // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
  6057. //# sourceMappingURL=babylon.webgl2.js.map
  6058. var BABYLON;
  6059. (function (BABYLON) {
  6060. var __decoratorInitialStore = {};
  6061. var __mergedStore = {};
  6062. var _copySource = function (creationFunction, source, instanciate) {
  6063. var destination = creationFunction();
  6064. // Tags
  6065. if (BABYLON.Tags) {
  6066. BABYLON.Tags.AddTagsTo(destination, source.tags);
  6067. }
  6068. var classStore = getMergedStore(destination);
  6069. // Properties
  6070. for (var property in classStore) {
  6071. var propertyDescriptor = classStore[property];
  6072. var sourceProperty = source[property];
  6073. var propertyType = propertyDescriptor.type;
  6074. if (sourceProperty !== undefined && sourceProperty !== null) {
  6075. switch (propertyType) {
  6076. case 0: // Value
  6077. case 6:// Mesh reference
  6078. destination[property] = sourceProperty;
  6079. break;
  6080. case 1:// Texture
  6081. destination[property] = (instanciate || sourceProperty.isRenderTarget) ? sourceProperty : sourceProperty.clone();
  6082. break;
  6083. case 2: // Color3
  6084. case 3: // FresnelParameters
  6085. case 4: // Vector2
  6086. case 5: // Vector3
  6087. case 7: // Color Curves
  6088. case 10:// Quaternion
  6089. destination[property] = instanciate ? sourceProperty : sourceProperty.clone();
  6090. break;
  6091. }
  6092. }
  6093. }
  6094. return destination;
  6095. };
  6096. function getDirectStore(target) {
  6097. var classKey = target.getClassName();
  6098. if (!__decoratorInitialStore[classKey]) {
  6099. __decoratorInitialStore[classKey] = {};
  6100. }
  6101. return __decoratorInitialStore[classKey];
  6102. }
  6103. /**
  6104. * Return the list of properties flagged as serializable
  6105. * @param target: host object
  6106. */
  6107. function getMergedStore(target) {
  6108. var classKey = target.getClassName();
  6109. if (__mergedStore[classKey]) {
  6110. return __mergedStore[classKey];
  6111. }
  6112. __mergedStore[classKey] = {};
  6113. var store = __mergedStore[classKey];
  6114. var currentTarget = target;
  6115. var currentKey = classKey;
  6116. while (currentKey) {
  6117. var initialStore = __decoratorInitialStore[currentKey];
  6118. for (var property in initialStore) {
  6119. store[property] = initialStore[property];
  6120. }
  6121. var parent_1 = void 0;
  6122. var done = false;
  6123. do {
  6124. parent_1 = Object.getPrototypeOf(currentTarget);
  6125. if (!parent_1.getClassName) {
  6126. done = true;
  6127. break;
  6128. }
  6129. if (parent_1.getClassName() !== currentKey) {
  6130. break;
  6131. }
  6132. currentTarget = parent_1;
  6133. } while (parent_1);
  6134. if (done) {
  6135. break;
  6136. }
  6137. currentKey = parent_1.getClassName();
  6138. currentTarget = parent_1;
  6139. }
  6140. return store;
  6141. }
  6142. function generateSerializableMember(type, sourceName) {
  6143. return function (target, propertyKey) {
  6144. var classStore = getDirectStore(target);
  6145. if (!classStore[propertyKey]) {
  6146. classStore[propertyKey] = { type: type, sourceName: sourceName };
  6147. }
  6148. };
  6149. }
  6150. function generateExpandMember(setCallback, targetKey) {
  6151. if (targetKey === void 0) { targetKey = null; }
  6152. return function (target, propertyKey) {
  6153. var key = targetKey || ("_" + propertyKey);
  6154. Object.defineProperty(target, propertyKey, {
  6155. get: function () {
  6156. return this[key];
  6157. },
  6158. set: function (value) {
  6159. if (this[key] === value) {
  6160. return;
  6161. }
  6162. this[key] = value;
  6163. target[setCallback].apply(this);
  6164. },
  6165. enumerable: true,
  6166. configurable: true
  6167. });
  6168. };
  6169. }
  6170. function expandToProperty(callback, targetKey) {
  6171. if (targetKey === void 0) { targetKey = null; }
  6172. return generateExpandMember(callback, targetKey);
  6173. }
  6174. BABYLON.expandToProperty = expandToProperty;
  6175. function serialize(sourceName) {
  6176. return generateSerializableMember(0, sourceName); // value member
  6177. }
  6178. BABYLON.serialize = serialize;
  6179. function serializeAsTexture(sourceName) {
  6180. return generateSerializableMember(1, sourceName); // texture member
  6181. }
  6182. BABYLON.serializeAsTexture = serializeAsTexture;
  6183. function serializeAsColor3(sourceName) {
  6184. return generateSerializableMember(2, sourceName); // color3 member
  6185. }
  6186. BABYLON.serializeAsColor3 = serializeAsColor3;
  6187. function serializeAsFresnelParameters(sourceName) {
  6188. return generateSerializableMember(3, sourceName); // fresnel parameters member
  6189. }
  6190. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  6191. function serializeAsVector2(sourceName) {
  6192. return generateSerializableMember(4, sourceName); // vector2 member
  6193. }
  6194. BABYLON.serializeAsVector2 = serializeAsVector2;
  6195. function serializeAsVector3(sourceName) {
  6196. return generateSerializableMember(5, sourceName); // vector3 member
  6197. }
  6198. BABYLON.serializeAsVector3 = serializeAsVector3;
  6199. function serializeAsMeshReference(sourceName) {
  6200. return generateSerializableMember(6, sourceName); // mesh reference member
  6201. }
  6202. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  6203. function serializeAsColorCurves(sourceName) {
  6204. return generateSerializableMember(7, sourceName); // color curves
  6205. }
  6206. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  6207. function serializeAsColor4(sourceName) {
  6208. return generateSerializableMember(8, sourceName); // color 4
  6209. }
  6210. BABYLON.serializeAsColor4 = serializeAsColor4;
  6211. function serializeAsImageProcessingConfiguration(sourceName) {
  6212. return generateSerializableMember(9, sourceName); // image processing
  6213. }
  6214. BABYLON.serializeAsImageProcessingConfiguration = serializeAsImageProcessingConfiguration;
  6215. function serializeAsQuaternion(sourceName) {
  6216. return generateSerializableMember(10, sourceName); // quaternion member
  6217. }
  6218. BABYLON.serializeAsQuaternion = serializeAsQuaternion;
  6219. var SerializationHelper = /** @class */ (function () {
  6220. function SerializationHelper() {
  6221. }
  6222. SerializationHelper.Serialize = function (entity, serializationObject) {
  6223. if (!serializationObject) {
  6224. serializationObject = {};
  6225. }
  6226. // Tags
  6227. if (BABYLON.Tags) {
  6228. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  6229. }
  6230. var serializedProperties = getMergedStore(entity);
  6231. // Properties
  6232. for (var property in serializedProperties) {
  6233. var propertyDescriptor = serializedProperties[property];
  6234. var targetPropertyName = propertyDescriptor.sourceName || property;
  6235. var propertyType = propertyDescriptor.type;
  6236. var sourceProperty = entity[property];
  6237. if (sourceProperty !== undefined && sourceProperty !== null) {
  6238. switch (propertyType) {
  6239. case 0:// Value
  6240. serializationObject[targetPropertyName] = sourceProperty;
  6241. break;
  6242. case 1:// Texture
  6243. serializationObject[targetPropertyName] = sourceProperty.serialize();
  6244. break;
  6245. case 2:// Color3
  6246. serializationObject[targetPropertyName] = sourceProperty.asArray();
  6247. break;
  6248. case 3:// FresnelParameters
  6249. serializationObject[targetPropertyName] = sourceProperty.serialize();
  6250. break;
  6251. case 4:// Vector2
  6252. serializationObject[targetPropertyName] = sourceProperty.asArray();
  6253. break;
  6254. case 5:// Vector3
  6255. serializationObject[targetPropertyName] = sourceProperty.asArray();
  6256. break;
  6257. case 6:// Mesh reference
  6258. serializationObject[targetPropertyName] = sourceProperty.id;
  6259. break;
  6260. case 7:// Color Curves
  6261. serializationObject[targetPropertyName] = sourceProperty.serialize();
  6262. break;
  6263. case 8:// Color 4
  6264. serializationObject[targetPropertyName] = sourceProperty.asArray();
  6265. break;
  6266. case 9:// Image Processing
  6267. serializationObject[targetPropertyName] = sourceProperty.serialize();
  6268. break;
  6269. }
  6270. }
  6271. }
  6272. return serializationObject;
  6273. };
  6274. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  6275. if (rootUrl === void 0) { rootUrl = null; }
  6276. var destination = creationFunction();
  6277. if (!rootUrl) {
  6278. rootUrl = "";
  6279. }
  6280. // Tags
  6281. if (BABYLON.Tags) {
  6282. BABYLON.Tags.AddTagsTo(destination, source.tags);
  6283. }
  6284. var classStore = getMergedStore(destination);
  6285. // Properties
  6286. for (var property in classStore) {
  6287. var propertyDescriptor = classStore[property];
  6288. var sourceProperty = source[propertyDescriptor.sourceName || property];
  6289. var propertyType = propertyDescriptor.type;
  6290. if (sourceProperty !== undefined && sourceProperty !== null) {
  6291. var dest = destination;
  6292. switch (propertyType) {
  6293. case 0:// Value
  6294. dest[property] = sourceProperty;
  6295. break;
  6296. case 1:// Texture
  6297. if (scene) {
  6298. dest[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  6299. }
  6300. break;
  6301. case 2:// Color3
  6302. dest[property] = BABYLON.Color3.FromArray(sourceProperty);
  6303. break;
  6304. case 3:// FresnelParameters
  6305. dest[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  6306. break;
  6307. case 4:// Vector2
  6308. dest[property] = BABYLON.Vector2.FromArray(sourceProperty);
  6309. break;
  6310. case 5:// Vector3
  6311. dest[property] = BABYLON.Vector3.FromArray(sourceProperty);
  6312. break;
  6313. case 6:// Mesh reference
  6314. if (scene) {
  6315. dest[property] = scene.getLastMeshByID(sourceProperty);
  6316. }
  6317. break;
  6318. case 7:// Color Curves
  6319. dest[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  6320. break;
  6321. case 8:// Color 4
  6322. dest[property] = BABYLON.Color4.FromArray(sourceProperty);
  6323. break;
  6324. case 9:// Image Processing
  6325. dest[property] = BABYLON.ImageProcessingConfiguration.Parse(sourceProperty);
  6326. break;
  6327. }
  6328. }
  6329. }
  6330. return destination;
  6331. };
  6332. SerializationHelper.Clone = function (creationFunction, source) {
  6333. return _copySource(creationFunction, source, false);
  6334. };
  6335. SerializationHelper.Instanciate = function (creationFunction, source) {
  6336. return _copySource(creationFunction, source, true);
  6337. };
  6338. return SerializationHelper;
  6339. }());
  6340. BABYLON.SerializationHelper = SerializationHelper;
  6341. })(BABYLON || (BABYLON = {}));
  6342. //# sourceMappingURL=babylon.decorators.js.map
  6343. var BABYLON;
  6344. (function (BABYLON) {
  6345. /**
  6346. * A class serves as a medium between the observable and its observers
  6347. */
  6348. var EventState = /** @class */ (function () {
  6349. /**
  6350. * If the callback of a given Observer set skipNextObservers to true the following observers will be ignored
  6351. */
  6352. function EventState(mask, skipNextObservers, target, currentTarget) {
  6353. if (skipNextObservers === void 0) { skipNextObservers = false; }
  6354. this.initalize(mask, skipNextObservers, target, currentTarget);
  6355. }
  6356. EventState.prototype.initalize = function (mask, skipNextObservers, target, currentTarget) {
  6357. if (skipNextObservers === void 0) { skipNextObservers = false; }
  6358. this.mask = mask;
  6359. this.skipNextObservers = skipNextObservers;
  6360. this.target = target;
  6361. this.currentTarget = currentTarget;
  6362. return this;
  6363. };
  6364. return EventState;
  6365. }());
  6366. BABYLON.EventState = EventState;
  6367. /**
  6368. * Represent an Observer registered to a given Observable object.
  6369. */
  6370. var Observer = /** @class */ (function () {
  6371. function Observer(callback, mask, scope) {
  6372. if (scope === void 0) { scope = null; }
  6373. this.callback = callback;
  6374. this.mask = mask;
  6375. this.scope = scope;
  6376. }
  6377. return Observer;
  6378. }());
  6379. BABYLON.Observer = Observer;
  6380. /**
  6381. * Represent a list of observers registered to multiple Observables object.
  6382. */
  6383. var MultiObserver = /** @class */ (function () {
  6384. function MultiObserver() {
  6385. }
  6386. MultiObserver.prototype.dispose = function () {
  6387. if (this._observers && this._observables) {
  6388. for (var index = 0; index < this._observers.length; index++) {
  6389. this._observables[index].remove(this._observers[index]);
  6390. }
  6391. }
  6392. this._observers = null;
  6393. this._observables = null;
  6394. };
  6395. MultiObserver.Watch = function (observables, callback, mask, scope) {
  6396. if (mask === void 0) { mask = -1; }
  6397. if (scope === void 0) { scope = null; }
  6398. var result = new MultiObserver();
  6399. result._observers = new Array();
  6400. result._observables = observables;
  6401. for (var _i = 0, observables_1 = observables; _i < observables_1.length; _i++) {
  6402. var observable = observables_1[_i];
  6403. var observer = observable.add(callback, mask, false, scope);
  6404. if (observer) {
  6405. result._observers.push(observer);
  6406. }
  6407. }
  6408. return result;
  6409. };
  6410. return MultiObserver;
  6411. }());
  6412. BABYLON.MultiObserver = MultiObserver;
  6413. /**
  6414. * The Observable class is a simple implementation of the Observable pattern.
  6415. * 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.
  6416. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  6417. * 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).
  6418. * 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.
  6419. */
  6420. var Observable = /** @class */ (function () {
  6421. function Observable(onObserverAdded) {
  6422. this._observers = new Array();
  6423. this._eventState = new EventState(0);
  6424. if (onObserverAdded) {
  6425. this._onObserverAdded = onObserverAdded;
  6426. }
  6427. }
  6428. /**
  6429. * Create a new Observer with the specified callback
  6430. * @param callback the callback that will be executed for that Observer
  6431. * @param mask the mask used to filter observers
  6432. * @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.
  6433. * @param scope optional scope for the callback to be called from
  6434. */
  6435. Observable.prototype.add = function (callback, mask, insertFirst, scope) {
  6436. if (mask === void 0) { mask = -1; }
  6437. if (insertFirst === void 0) { insertFirst = false; }
  6438. if (scope === void 0) { scope = null; }
  6439. if (!callback) {
  6440. return null;
  6441. }
  6442. var observer = new Observer(callback, mask, scope);
  6443. if (insertFirst) {
  6444. this._observers.unshift(observer);
  6445. }
  6446. else {
  6447. this._observers.push(observer);
  6448. }
  6449. if (this._onObserverAdded) {
  6450. this._onObserverAdded(observer);
  6451. }
  6452. return observer;
  6453. };
  6454. /**
  6455. * Remove an Observer from the Observable object
  6456. * @param observer the instance of the Observer to remove. If it doesn't belong to this Observable, false will be returned.
  6457. */
  6458. Observable.prototype.remove = function (observer) {
  6459. if (!observer) {
  6460. return false;
  6461. }
  6462. var index = this._observers.indexOf(observer);
  6463. if (index !== -1) {
  6464. this._observers.splice(index, 1);
  6465. return true;
  6466. }
  6467. return false;
  6468. };
  6469. /**
  6470. * Remove a callback from the Observable object
  6471. * @param callback the callback to remove. If it doesn't belong to this Observable, false will be returned.
  6472. * @param scope optional scope. If used only the callbacks with this scope will be removed.
  6473. */
  6474. Observable.prototype.removeCallback = function (callback, scope) {
  6475. for (var index = 0; index < this._observers.length; index++) {
  6476. if (this._observers[index].callback === callback && (!scope || scope === this._observers[index].scope)) {
  6477. this._observers.splice(index, 1);
  6478. return true;
  6479. }
  6480. }
  6481. return false;
  6482. };
  6483. /**
  6484. * Notify all Observers by calling their respective callback with the given data
  6485. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  6486. * @param eventData
  6487. * @param mask
  6488. */
  6489. Observable.prototype.notifyObservers = function (eventData, mask, target, currentTarget) {
  6490. if (mask === void 0) { mask = -1; }
  6491. if (!this._observers.length) {
  6492. return true;
  6493. }
  6494. var state = this._eventState;
  6495. state.mask = mask;
  6496. state.target = target;
  6497. state.currentTarget = currentTarget;
  6498. state.skipNextObservers = false;
  6499. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  6500. var obs = _a[_i];
  6501. if (obs.mask & mask) {
  6502. if (obs.scope) {
  6503. obs.callback.apply(obs.scope, [eventData, state]);
  6504. }
  6505. else {
  6506. obs.callback(eventData, state);
  6507. }
  6508. }
  6509. if (state.skipNextObservers) {
  6510. return false;
  6511. }
  6512. }
  6513. return true;
  6514. };
  6515. /**
  6516. * Notify a specific observer
  6517. * @param eventData
  6518. * @param mask
  6519. */
  6520. Observable.prototype.notifyObserver = function (observer, eventData, mask) {
  6521. if (mask === void 0) { mask = -1; }
  6522. var state = this._eventState;
  6523. state.mask = mask;
  6524. state.skipNextObservers = false;
  6525. observer.callback(eventData, state);
  6526. };
  6527. /**
  6528. * return true is the Observable has at least one Observer registered
  6529. */
  6530. Observable.prototype.hasObservers = function () {
  6531. return this._observers.length > 0;
  6532. };
  6533. /**
  6534. * Clear the list of observers
  6535. */
  6536. Observable.prototype.clear = function () {
  6537. this._observers = new Array();
  6538. this._onObserverAdded = null;
  6539. };
  6540. /**
  6541. * Clone the current observable
  6542. */
  6543. Observable.prototype.clone = function () {
  6544. var result = new Observable();
  6545. result._observers = this._observers.slice(0);
  6546. return result;
  6547. };
  6548. /**
  6549. * Does this observable handles observer registered with a given mask
  6550. * @param {number} trigger - the mask to be tested
  6551. * @return {boolean} whether or not one observer registered with the given mask is handeled
  6552. **/
  6553. Observable.prototype.hasSpecificMask = function (mask) {
  6554. if (mask === void 0) { mask = -1; }
  6555. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  6556. var obs = _a[_i];
  6557. if (obs.mask & mask || obs.mask === mask) {
  6558. return true;
  6559. }
  6560. }
  6561. return false;
  6562. };
  6563. return Observable;
  6564. }());
  6565. BABYLON.Observable = Observable;
  6566. })(BABYLON || (BABYLON = {}));
  6567. //# sourceMappingURL=babylon.observable.js.map
  6568. var BABYLON;
  6569. (function (BABYLON) {
  6570. var SmartArray = /** @class */ (function () {
  6571. function SmartArray(capacity) {
  6572. this.length = 0;
  6573. this.data = new Array(capacity);
  6574. this._id = SmartArray._GlobalId++;
  6575. }
  6576. SmartArray.prototype.push = function (value) {
  6577. this.data[this.length++] = value;
  6578. if (this.length > this.data.length) {
  6579. this.data.length *= 2;
  6580. }
  6581. };
  6582. SmartArray.prototype.forEach = function (func) {
  6583. for (var index = 0; index < this.length; index++) {
  6584. func(this.data[index]);
  6585. }
  6586. };
  6587. SmartArray.prototype.sort = function (compareFn) {
  6588. this.data.sort(compareFn);
  6589. };
  6590. SmartArray.prototype.reset = function () {
  6591. this.length = 0;
  6592. };
  6593. SmartArray.prototype.dispose = function () {
  6594. this.reset();
  6595. if (this.data) {
  6596. this.data.length = 0;
  6597. this.data = [];
  6598. }
  6599. };
  6600. SmartArray.prototype.concat = function (array) {
  6601. if (array.length === 0) {
  6602. return;
  6603. }
  6604. if (this.length + array.length > this.data.length) {
  6605. this.data.length = (this.length + array.length) * 2;
  6606. }
  6607. for (var index = 0; index < array.length; index++) {
  6608. this.data[this.length++] = (array.data || array)[index];
  6609. }
  6610. };
  6611. SmartArray.prototype.indexOf = function (value) {
  6612. var position = this.data.indexOf(value);
  6613. if (position >= this.length) {
  6614. return -1;
  6615. }
  6616. return position;
  6617. };
  6618. SmartArray.prototype.contains = function (value) {
  6619. return this.data.indexOf(value) !== -1;
  6620. };
  6621. // Statics
  6622. SmartArray._GlobalId = 0;
  6623. return SmartArray;
  6624. }());
  6625. BABYLON.SmartArray = SmartArray;
  6626. var SmartArrayNoDuplicate = /** @class */ (function (_super) {
  6627. __extends(SmartArrayNoDuplicate, _super);
  6628. function SmartArrayNoDuplicate() {
  6629. var _this = _super !== null && _super.apply(this, arguments) || this;
  6630. _this._duplicateId = 0;
  6631. return _this;
  6632. }
  6633. SmartArrayNoDuplicate.prototype.push = function (value) {
  6634. _super.prototype.push.call(this, value);
  6635. if (!value.__smartArrayFlags) {
  6636. value.__smartArrayFlags = {};
  6637. }
  6638. value.__smartArrayFlags[this._id] = this._duplicateId;
  6639. };
  6640. SmartArrayNoDuplicate.prototype.pushNoDuplicate = function (value) {
  6641. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  6642. return false;
  6643. }
  6644. this.push(value);
  6645. return true;
  6646. };
  6647. SmartArrayNoDuplicate.prototype.reset = function () {
  6648. _super.prototype.reset.call(this);
  6649. this._duplicateId++;
  6650. };
  6651. SmartArrayNoDuplicate.prototype.concatWithNoDuplicate = function (array) {
  6652. if (array.length === 0) {
  6653. return;
  6654. }
  6655. if (this.length + array.length > this.data.length) {
  6656. this.data.length = (this.length + array.length) * 2;
  6657. }
  6658. for (var index = 0; index < array.length; index++) {
  6659. var item = (array.data || array)[index];
  6660. this.pushNoDuplicate(item);
  6661. }
  6662. };
  6663. return SmartArrayNoDuplicate;
  6664. }(SmartArray));
  6665. BABYLON.SmartArrayNoDuplicate = SmartArrayNoDuplicate;
  6666. })(BABYLON || (BABYLON = {}));
  6667. //# sourceMappingURL=babylon.smartArray.js.map
  6668. var BABYLON;
  6669. (function (BABYLON) {
  6670. // See https://stackoverflow.com/questions/12915412/how-do-i-extend-a-host-object-e-g-error-in-typescript
  6671. // and https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work
  6672. var LoadFileError = /** @class */ (function (_super) {
  6673. __extends(LoadFileError, _super);
  6674. function LoadFileError(message, request) {
  6675. var _this = _super.call(this, message) || this;
  6676. _this.request = request;
  6677. _this.name = "LoadFileError";
  6678. LoadFileError._setPrototypeOf(_this, LoadFileError.prototype);
  6679. return _this;
  6680. }
  6681. // Polyfill for Object.setPrototypeOf if necessary.
  6682. LoadFileError._setPrototypeOf = Object.setPrototypeOf || (function (o, proto) { o.__proto__ = proto; return o; });
  6683. return LoadFileError;
  6684. }(Error));
  6685. BABYLON.LoadFileError = LoadFileError;
  6686. var RetryStrategy = /** @class */ (function () {
  6687. function RetryStrategy() {
  6688. }
  6689. RetryStrategy.ExponentialBackoff = function (maxRetries, baseInterval) {
  6690. if (maxRetries === void 0) { maxRetries = 3; }
  6691. if (baseInterval === void 0) { baseInterval = 500; }
  6692. return function (url, request, retryIndex) {
  6693. if (request.status !== 0 || retryIndex >= maxRetries || url.indexOf("file:") !== -1) {
  6694. return -1;
  6695. }
  6696. return Math.pow(2, retryIndex) * baseInterval;
  6697. };
  6698. };
  6699. return RetryStrategy;
  6700. }());
  6701. BABYLON.RetryStrategy = RetryStrategy;
  6702. // Screenshots
  6703. var screenshotCanvas;
  6704. var cloneValue = function (source, destinationObject) {
  6705. if (!source)
  6706. return null;
  6707. if (source instanceof BABYLON.Mesh) {
  6708. return null;
  6709. }
  6710. if (source instanceof BABYLON.SubMesh) {
  6711. return source.clone(destinationObject);
  6712. }
  6713. else if (source.clone) {
  6714. return source.clone();
  6715. }
  6716. return null;
  6717. };
  6718. var Tools = /** @class */ (function () {
  6719. function Tools() {
  6720. }
  6721. /**
  6722. * Interpolates between a and b via alpha
  6723. * @param a The lower value (returned when alpha = 0)
  6724. * @param b The upper value (returned when alpha = 1)
  6725. * @param alpha The interpolation-factor
  6726. * @return The mixed value
  6727. */
  6728. Tools.Mix = function (a, b, alpha) {
  6729. return a * (1 - alpha) + b * alpha;
  6730. };
  6731. Tools.Instantiate = function (className) {
  6732. if (Tools.RegisteredExternalClasses && Tools.RegisteredExternalClasses[className]) {
  6733. return Tools.RegisteredExternalClasses[className];
  6734. }
  6735. var arr = className.split(".");
  6736. var fn = (window || this);
  6737. for (var i = 0, len = arr.length; i < len; i++) {
  6738. fn = fn[arr[i]];
  6739. }
  6740. if (typeof fn !== "function") {
  6741. return null;
  6742. }
  6743. return fn;
  6744. };
  6745. /**
  6746. * Provides a slice function that will work even on IE
  6747. * @param data defines the array to slice
  6748. * @returns the new sliced array
  6749. */
  6750. Tools.Slice = function (data) {
  6751. if (data.slice) {
  6752. return data.slice();
  6753. }
  6754. return Array.prototype.slice.call(data);
  6755. };
  6756. Tools.SetImmediate = function (action) {
  6757. if (window.setImmediate) {
  6758. window.setImmediate(action);
  6759. }
  6760. else {
  6761. setTimeout(action, 1);
  6762. }
  6763. };
  6764. Tools.IsExponentOfTwo = function (value) {
  6765. var count = 1;
  6766. do {
  6767. count *= 2;
  6768. } while (count < value);
  6769. return count === value;
  6770. };
  6771. /**
  6772. * Find the next highest power of two.
  6773. * @param x Number to start search from.
  6774. * @return Next highest power of two.
  6775. */
  6776. Tools.CeilingPOT = function (x) {
  6777. x--;
  6778. x |= x >> 1;
  6779. x |= x >> 2;
  6780. x |= x >> 4;
  6781. x |= x >> 8;
  6782. x |= x >> 16;
  6783. x++;
  6784. return x;
  6785. };
  6786. /**
  6787. * Find the next lowest power of two.
  6788. * @param x Number to start search from.
  6789. * @return Next lowest power of two.
  6790. */
  6791. Tools.FloorPOT = function (x) {
  6792. x = x | (x >> 1);
  6793. x = x | (x >> 2);
  6794. x = x | (x >> 4);
  6795. x = x | (x >> 8);
  6796. x = x | (x >> 16);
  6797. return x - (x >> 1);
  6798. };
  6799. /**
  6800. * Find the nearest power of two.
  6801. * @param x Number to start search from.
  6802. * @return Next nearest power of two.
  6803. */
  6804. Tools.NearestPOT = function (x) {
  6805. var c = Tools.CeilingPOT(x);
  6806. var f = Tools.FloorPOT(x);
  6807. return (c - x) > (x - f) ? f : c;
  6808. };
  6809. Tools.GetExponentOfTwo = function (value, max, mode) {
  6810. if (mode === void 0) { mode = BABYLON.Engine.SCALEMODE_NEAREST; }
  6811. var pot;
  6812. switch (mode) {
  6813. case BABYLON.Engine.SCALEMODE_FLOOR:
  6814. pot = Tools.FloorPOT(value);
  6815. break;
  6816. case BABYLON.Engine.SCALEMODE_NEAREST:
  6817. pot = Tools.NearestPOT(value);
  6818. break;
  6819. case BABYLON.Engine.SCALEMODE_CEILING:
  6820. default:
  6821. pot = Tools.CeilingPOT(value);
  6822. break;
  6823. }
  6824. return Math.min(pot, max);
  6825. };
  6826. Tools.GetFilename = function (path) {
  6827. var index = path.lastIndexOf("/");
  6828. if (index < 0)
  6829. return path;
  6830. return path.substring(index + 1);
  6831. };
  6832. Tools.GetFolderPath = function (uri) {
  6833. var index = uri.lastIndexOf("/");
  6834. if (index < 0)
  6835. return "";
  6836. return uri.substring(0, index + 1);
  6837. };
  6838. Tools.GetDOMTextContent = function (element) {
  6839. var result = "";
  6840. var child = element.firstChild;
  6841. while (child) {
  6842. if (child.nodeType === 3) {
  6843. result += child.textContent;
  6844. }
  6845. child = child.nextSibling;
  6846. }
  6847. return result;
  6848. };
  6849. Tools.ToDegrees = function (angle) {
  6850. return angle * 180 / Math.PI;
  6851. };
  6852. Tools.ToRadians = function (angle) {
  6853. return angle * Math.PI / 180;
  6854. };
  6855. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  6856. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  6857. var output = "";
  6858. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  6859. var i = 0;
  6860. var bytes = new Uint8Array(buffer);
  6861. while (i < bytes.length) {
  6862. chr1 = bytes[i++];
  6863. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  6864. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  6865. enc1 = chr1 >> 2;
  6866. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  6867. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  6868. enc4 = chr3 & 63;
  6869. if (isNaN(chr2)) {
  6870. enc3 = enc4 = 64;
  6871. }
  6872. else if (isNaN(chr3)) {
  6873. enc4 = 64;
  6874. }
  6875. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  6876. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  6877. }
  6878. return "data:image/png;base64," + output;
  6879. };
  6880. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  6881. if (bias === void 0) { bias = null; }
  6882. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  6883. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  6884. for (var index = indexStart; index < indexStart + indexCount; index++) {
  6885. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  6886. minimum = BABYLON.Vector3.Minimize(current, minimum);
  6887. maximum = BABYLON.Vector3.Maximize(current, maximum);
  6888. }
  6889. if (bias) {
  6890. minimum.x -= minimum.x * bias.x + bias.y;
  6891. minimum.y -= minimum.y * bias.x + bias.y;
  6892. minimum.z -= minimum.z * bias.x + bias.y;
  6893. maximum.x += maximum.x * bias.x + bias.y;
  6894. maximum.y += maximum.y * bias.x + bias.y;
  6895. maximum.z += maximum.z * bias.x + bias.y;
  6896. }
  6897. return {
  6898. minimum: minimum,
  6899. maximum: maximum
  6900. };
  6901. };
  6902. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  6903. if (bias === void 0) { bias = null; }
  6904. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  6905. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  6906. if (!stride) {
  6907. stride = 3;
  6908. }
  6909. for (var index = start; index < start + count; index++) {
  6910. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  6911. minimum = BABYLON.Vector3.Minimize(current, minimum);
  6912. maximum = BABYLON.Vector3.Maximize(current, maximum);
  6913. }
  6914. if (bias) {
  6915. minimum.x -= minimum.x * bias.x + bias.y;
  6916. minimum.y -= minimum.y * bias.x + bias.y;
  6917. minimum.z -= minimum.z * bias.x + bias.y;
  6918. maximum.x += maximum.x * bias.x + bias.y;
  6919. maximum.y += maximum.y * bias.x + bias.y;
  6920. maximum.z += maximum.z * bias.x + bias.y;
  6921. }
  6922. return {
  6923. minimum: minimum,
  6924. maximum: maximum
  6925. };
  6926. };
  6927. Tools.Vector2ArrayFeeder = function (array) {
  6928. return function (index) {
  6929. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  6930. var length = isFloatArray ? array.length / 2 : array.length;
  6931. if (index >= length) {
  6932. return null;
  6933. }
  6934. if (isFloatArray) {
  6935. var fa = array;
  6936. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  6937. }
  6938. var a = array;
  6939. return a[index];
  6940. };
  6941. };
  6942. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  6943. if (bias === void 0) { bias = null; }
  6944. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  6945. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  6946. var i = 0;
  6947. var cur = feeder(i++);
  6948. while (cur) {
  6949. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  6950. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  6951. cur = feeder(i++);
  6952. }
  6953. if (bias) {
  6954. minimum.x -= minimum.x * bias.x + bias.y;
  6955. minimum.y -= minimum.y * bias.x + bias.y;
  6956. maximum.x += maximum.x * bias.x + bias.y;
  6957. maximum.y += maximum.y * bias.x + bias.y;
  6958. }
  6959. return {
  6960. minimum: minimum,
  6961. maximum: maximum
  6962. };
  6963. };
  6964. Tools.MakeArray = function (obj, allowsNullUndefined) {
  6965. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  6966. return null;
  6967. return Array.isArray(obj) ? obj : [obj];
  6968. };
  6969. // Misc.
  6970. Tools.GetPointerPrefix = function () {
  6971. var eventPrefix = "pointer";
  6972. // Check if pointer events are supported
  6973. if (Tools.IsWindowObjectExist() && !window.PointerEvent && !navigator.pointerEnabled) {
  6974. eventPrefix = "mouse";
  6975. }
  6976. return eventPrefix;
  6977. };
  6978. /**
  6979. * @param func - the function to be called
  6980. * @param requester - the object that will request the next frame. Falls back to window.
  6981. */
  6982. Tools.QueueNewFrame = function (func, requester) {
  6983. if (!Tools.IsWindowObjectExist()) {
  6984. return setTimeout(func, 16);
  6985. }
  6986. if (!requester) {
  6987. requester = window;
  6988. }
  6989. if (requester.requestAnimationFrame) {
  6990. return requester.requestAnimationFrame(func);
  6991. }
  6992. else if (requester.msRequestAnimationFrame) {
  6993. return requester.msRequestAnimationFrame(func);
  6994. }
  6995. else if (requester.webkitRequestAnimationFrame) {
  6996. return requester.webkitRequestAnimationFrame(func);
  6997. }
  6998. else if (requester.mozRequestAnimationFrame) {
  6999. return requester.mozRequestAnimationFrame(func);
  7000. }
  7001. else if (requester.oRequestAnimationFrame) {
  7002. return requester.oRequestAnimationFrame(func);
  7003. }
  7004. else {
  7005. return window.setTimeout(func, 16);
  7006. }
  7007. };
  7008. Tools.RequestFullscreen = function (element) {
  7009. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  7010. if (!requestFunction)
  7011. return;
  7012. requestFunction.call(element);
  7013. };
  7014. Tools.ExitFullscreen = function () {
  7015. if (document.exitFullscreen) {
  7016. document.exitFullscreen();
  7017. }
  7018. else if (document.mozCancelFullScreen) {
  7019. document.mozCancelFullScreen();
  7020. }
  7021. else if (document.webkitCancelFullScreen) {
  7022. document.webkitCancelFullScreen();
  7023. }
  7024. else if (document.msCancelFullScreen) {
  7025. document.msCancelFullScreen();
  7026. }
  7027. };
  7028. Tools.SetCorsBehavior = function (url, element) {
  7029. if (url && url.indexOf("data:") === 0) {
  7030. return;
  7031. }
  7032. if (Tools.CorsBehavior) {
  7033. if (typeof (Tools.CorsBehavior) === 'string' || Tools.CorsBehavior instanceof String) {
  7034. element.crossOrigin = Tools.CorsBehavior;
  7035. }
  7036. else {
  7037. var result = Tools.CorsBehavior(url);
  7038. if (result) {
  7039. element.crossOrigin = result;
  7040. }
  7041. }
  7042. }
  7043. };
  7044. // External files
  7045. Tools.CleanUrl = function (url) {
  7046. url = url.replace(/#/mg, "%23");
  7047. return url;
  7048. };
  7049. Tools.LoadImage = function (url, onLoad, onError, database) {
  7050. if (url instanceof ArrayBuffer) {
  7051. url = Tools.EncodeArrayBufferTobase64(url);
  7052. }
  7053. url = Tools.CleanUrl(url);
  7054. url = Tools.PreprocessUrl(url);
  7055. var img = new Image();
  7056. Tools.SetCorsBehavior(url, img);
  7057. img.onload = function () {
  7058. onLoad(img);
  7059. };
  7060. img.onerror = function (err) {
  7061. Tools.Error("Error while trying to load image: " + url);
  7062. if (onError) {
  7063. onError("Error while trying to load image: " + url, err);
  7064. }
  7065. };
  7066. var noIndexedDB = function () {
  7067. img.src = url;
  7068. };
  7069. var loadFromIndexedDB = function () {
  7070. if (database) {
  7071. database.loadImageFromDB(url, img);
  7072. }
  7073. };
  7074. //ANY database to do!
  7075. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  7076. database.openAsync(loadFromIndexedDB, noIndexedDB);
  7077. }
  7078. else {
  7079. if (url.indexOf("file:") !== -1) {
  7080. var textureName = decodeURIComponent(url.substring(5).toLowerCase());
  7081. if (BABYLON.FilesInput.FilesToLoad[textureName]) {
  7082. try {
  7083. var blobURL;
  7084. try {
  7085. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName], { oneTimeOnly: true });
  7086. }
  7087. catch (ex) {
  7088. // Chrome doesn't support oneTimeOnly parameter
  7089. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  7090. }
  7091. img.src = blobURL;
  7092. }
  7093. catch (e) {
  7094. img.src = "";
  7095. }
  7096. return img;
  7097. }
  7098. }
  7099. noIndexedDB();
  7100. }
  7101. return img;
  7102. };
  7103. Tools.LoadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  7104. url = Tools.CleanUrl(url);
  7105. url = Tools.PreprocessUrl(url);
  7106. // If file and file input are set
  7107. if (url.indexOf("file:") !== -1) {
  7108. var fileName = decodeURIComponent(url.substring(5).toLowerCase());
  7109. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  7110. return Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], onSuccess, onProgress, useArrayBuffer);
  7111. }
  7112. }
  7113. var loadUrl = Tools.BaseUrl + url;
  7114. var aborted = false;
  7115. var fileRequest = {
  7116. onCompleteObservable: new BABYLON.Observable(),
  7117. abort: function () { return aborted = true; },
  7118. };
  7119. var requestFile = function () {
  7120. var request = new XMLHttpRequest();
  7121. var retryHandle = null;
  7122. fileRequest.abort = function () {
  7123. aborted = true;
  7124. if (request.readyState !== (XMLHttpRequest.DONE || 4)) {
  7125. request.abort();
  7126. }
  7127. if (retryHandle !== null) {
  7128. clearTimeout(retryHandle);
  7129. retryHandle = null;
  7130. }
  7131. };
  7132. var retryLoop = function (retryIndex) {
  7133. request.open('GET', loadUrl, true);
  7134. if (useArrayBuffer) {
  7135. request.responseType = "arraybuffer";
  7136. }
  7137. if (onProgress) {
  7138. request.addEventListener("progress", onProgress);
  7139. }
  7140. var onLoadEnd = function () {
  7141. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  7142. };
  7143. request.addEventListener("loadend", onLoadEnd);
  7144. var onReadyStateChange = function () {
  7145. if (aborted) {
  7146. return;
  7147. }
  7148. // In case of undefined state in some browsers.
  7149. if (request.readyState === (XMLHttpRequest.DONE || 4)) {
  7150. // Some browsers have issues where onreadystatechange can be called multiple times with the same value.
  7151. request.removeEventListener("readystatechange", onReadyStateChange);
  7152. if (request.status >= 200 && request.status < 300 || (!Tools.IsWindowObjectExist() && (request.status === 0))) {
  7153. onSuccess(!useArrayBuffer ? request.responseText : request.response, request.responseURL);
  7154. return;
  7155. }
  7156. var retryStrategy = Tools.DefaultRetryStrategy;
  7157. if (retryStrategy) {
  7158. var waitTime = retryStrategy(loadUrl, request, retryIndex);
  7159. if (waitTime !== -1) {
  7160. // Prevent the request from completing for retry.
  7161. request.removeEventListener("loadend", onLoadEnd);
  7162. request = new XMLHttpRequest();
  7163. retryHandle = setTimeout(function () { return retryLoop(retryIndex + 1); }, waitTime);
  7164. return;
  7165. }
  7166. }
  7167. var e = new LoadFileError("Error status: " + request.status + " " + request.statusText + " - Unable to load " + loadUrl, request);
  7168. if (onError) {
  7169. onError(request, e);
  7170. }
  7171. else {
  7172. throw e;
  7173. }
  7174. }
  7175. };
  7176. request.addEventListener("readystatechange", onReadyStateChange);
  7177. request.send();
  7178. };
  7179. retryLoop(0);
  7180. };
  7181. // Caching all files
  7182. if (database && database.enableSceneOffline) {
  7183. var noIndexedDB_1 = function () {
  7184. if (!aborted) {
  7185. requestFile();
  7186. }
  7187. };
  7188. var loadFromIndexedDB = function () {
  7189. // TODO: database needs to support aborting and should return a IFileRequest
  7190. if (aborted) {
  7191. return;
  7192. }
  7193. if (database) {
  7194. database.loadFileFromDB(url, function (data) {
  7195. if (!aborted) {
  7196. onSuccess(data);
  7197. }
  7198. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  7199. }, onProgress ? function (event) {
  7200. if (!aborted) {
  7201. onProgress(event);
  7202. }
  7203. } : undefined, noIndexedDB_1, useArrayBuffer);
  7204. }
  7205. };
  7206. database.openAsync(loadFromIndexedDB, noIndexedDB_1);
  7207. }
  7208. else {
  7209. requestFile();
  7210. }
  7211. return fileRequest;
  7212. };
  7213. /**
  7214. * Load a script (identified by an url). When the url returns, the
  7215. * content of this file is added into a new script element, attached to the DOM (body element)
  7216. */
  7217. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  7218. var head = document.getElementsByTagName('head')[0];
  7219. var script = document.createElement('script');
  7220. script.type = 'text/javascript';
  7221. script.src = scriptUrl;
  7222. script.onload = function () {
  7223. if (onSuccess) {
  7224. onSuccess();
  7225. }
  7226. };
  7227. script.onerror = function (e) {
  7228. if (onError) {
  7229. onError("Unable to load script", e);
  7230. }
  7231. };
  7232. head.appendChild(script);
  7233. };
  7234. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  7235. var reader = new FileReader();
  7236. var request = {
  7237. onCompleteObservable: new BABYLON.Observable(),
  7238. abort: function () { return reader.abort(); },
  7239. };
  7240. reader.onloadend = function (e) {
  7241. request.onCompleteObservable.notifyObservers(request);
  7242. };
  7243. reader.onload = function (e) {
  7244. //target doesn't have result from ts 1.3
  7245. callback(e.target['result']);
  7246. };
  7247. reader.onprogress = progressCallback;
  7248. reader.readAsDataURL(fileToLoad);
  7249. return request;
  7250. };
  7251. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  7252. var reader = new FileReader();
  7253. var request = {
  7254. onCompleteObservable: new BABYLON.Observable(),
  7255. abort: function () { return reader.abort(); },
  7256. };
  7257. reader.onloadend = function (e) { return request.onCompleteObservable.notifyObservers(request); };
  7258. reader.onerror = function (e) {
  7259. Tools.Log("Error while reading file: " + fileToLoad.name);
  7260. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  7261. };
  7262. reader.onload = function (e) {
  7263. //target doesn't have result from ts 1.3
  7264. callback(e.target['result']);
  7265. };
  7266. if (progressCallBack) {
  7267. reader.onprogress = progressCallBack;
  7268. }
  7269. if (!useArrayBuffer) {
  7270. // Asynchronous read
  7271. reader.readAsText(fileToLoad);
  7272. }
  7273. else {
  7274. reader.readAsArrayBuffer(fileToLoad);
  7275. }
  7276. return request;
  7277. };
  7278. //returns a downloadable url to a file content.
  7279. Tools.FileAsURL = function (content) {
  7280. var fileBlob = new Blob([content]);
  7281. var url = window.URL || window.webkitURL;
  7282. var link = url.createObjectURL(fileBlob);
  7283. return link;
  7284. };
  7285. // Misc.
  7286. Tools.Format = function (value, decimals) {
  7287. if (decimals === void 0) { decimals = 2; }
  7288. return value.toFixed(decimals);
  7289. };
  7290. Tools.CheckExtends = function (v, min, max) {
  7291. if (v.x < min.x)
  7292. min.x = v.x;
  7293. if (v.y < min.y)
  7294. min.y = v.y;
  7295. if (v.z < min.z)
  7296. min.z = v.z;
  7297. if (v.x > max.x)
  7298. max.x = v.x;
  7299. if (v.y > max.y)
  7300. max.y = v.y;
  7301. if (v.z > max.z)
  7302. max.z = v.z;
  7303. };
  7304. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  7305. for (var prop in source) {
  7306. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  7307. continue;
  7308. }
  7309. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  7310. continue;
  7311. }
  7312. var sourceValue = source[prop];
  7313. var typeOfSourceValue = typeof sourceValue;
  7314. if (typeOfSourceValue === "function") {
  7315. continue;
  7316. }
  7317. if (typeOfSourceValue === "object") {
  7318. if (sourceValue instanceof Array) {
  7319. destination[prop] = [];
  7320. if (sourceValue.length > 0) {
  7321. if (typeof sourceValue[0] == "object") {
  7322. for (var index = 0; index < sourceValue.length; index++) {
  7323. var clonedValue = cloneValue(sourceValue[index], destination);
  7324. if (destination[prop].indexOf(clonedValue) === -1) {
  7325. destination[prop].push(clonedValue);
  7326. }
  7327. }
  7328. }
  7329. else {
  7330. destination[prop] = sourceValue.slice(0);
  7331. }
  7332. }
  7333. }
  7334. else {
  7335. destination[prop] = cloneValue(sourceValue, destination);
  7336. }
  7337. }
  7338. else {
  7339. destination[prop] = sourceValue;
  7340. }
  7341. }
  7342. };
  7343. Tools.IsEmpty = function (obj) {
  7344. for (var i in obj) {
  7345. if (obj.hasOwnProperty(i)) {
  7346. return false;
  7347. }
  7348. }
  7349. return true;
  7350. };
  7351. Tools.RegisterTopRootEvents = function (events) {
  7352. for (var index = 0; index < events.length; index++) {
  7353. var event = events[index];
  7354. window.addEventListener(event.name, event.handler, false);
  7355. try {
  7356. if (window.parent) {
  7357. window.parent.addEventListener(event.name, event.handler, false);
  7358. }
  7359. }
  7360. catch (e) {
  7361. // Silently fails...
  7362. }
  7363. }
  7364. };
  7365. Tools.UnregisterTopRootEvents = function (events) {
  7366. for (var index = 0; index < events.length; index++) {
  7367. var event = events[index];
  7368. window.removeEventListener(event.name, event.handler);
  7369. try {
  7370. if (window.parent) {
  7371. window.parent.removeEventListener(event.name, event.handler);
  7372. }
  7373. }
  7374. catch (e) {
  7375. // Silently fails...
  7376. }
  7377. }
  7378. };
  7379. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType, fileName) {
  7380. if (mimeType === void 0) { mimeType = "image/png"; }
  7381. // Read the contents of the framebuffer
  7382. var numberOfChannelsByLine = width * 4;
  7383. var halfHeight = height / 2;
  7384. //Reading datas from WebGL
  7385. var data = engine.readPixels(0, 0, width, height);
  7386. //To flip image on Y axis.
  7387. for (var i = 0; i < halfHeight; i++) {
  7388. for (var j = 0; j < numberOfChannelsByLine; j++) {
  7389. var currentCell = j + i * numberOfChannelsByLine;
  7390. var targetLine = height - i - 1;
  7391. var targetCell = j + targetLine * numberOfChannelsByLine;
  7392. var temp = data[currentCell];
  7393. data[currentCell] = data[targetCell];
  7394. data[targetCell] = temp;
  7395. }
  7396. }
  7397. // Create a 2D canvas to store the result
  7398. if (!screenshotCanvas) {
  7399. screenshotCanvas = document.createElement('canvas');
  7400. }
  7401. screenshotCanvas.width = width;
  7402. screenshotCanvas.height = height;
  7403. var context = screenshotCanvas.getContext('2d');
  7404. if (context) {
  7405. // Copy the pixels to a 2D canvas
  7406. var imageData = context.createImageData(width, height);
  7407. var castData = (imageData.data);
  7408. castData.set(data);
  7409. context.putImageData(imageData, 0, 0);
  7410. Tools.EncodeScreenshotCanvasData(successCallback, mimeType, fileName);
  7411. }
  7412. };
  7413. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType, fileName) {
  7414. if (mimeType === void 0) { mimeType = "image/png"; }
  7415. var base64Image = screenshotCanvas.toDataURL(mimeType);
  7416. if (successCallback) {
  7417. successCallback(base64Image);
  7418. }
  7419. else {
  7420. // We need HTMLCanvasElement.toBlob for HD screenshots
  7421. if (!screenshotCanvas.toBlob) {
  7422. // low performance polyfill based on toDataURL (https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob)
  7423. screenshotCanvas.toBlob = function (callback, type, quality) {
  7424. var _this = this;
  7425. setTimeout(function () {
  7426. var binStr = atob(_this.toDataURL(type, quality).split(',')[1]), len = binStr.length, arr = new Uint8Array(len);
  7427. for (var i = 0; i < len; i++) {
  7428. arr[i] = binStr.charCodeAt(i);
  7429. }
  7430. callback(new Blob([arr], { type: type || 'image/png' }));
  7431. });
  7432. };
  7433. }
  7434. screenshotCanvas.toBlob(function (blob) {
  7435. var url = URL.createObjectURL(blob);
  7436. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  7437. if (("download" in document.createElement("a"))) {
  7438. var a = window.document.createElement("a");
  7439. a.href = url;
  7440. if (fileName) {
  7441. a.setAttribute("download", fileName);
  7442. }
  7443. else {
  7444. var date = new Date();
  7445. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(-2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  7446. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  7447. }
  7448. window.document.body.appendChild(a);
  7449. a.addEventListener("click", function () {
  7450. if (a.parentElement) {
  7451. a.parentElement.removeChild(a);
  7452. }
  7453. });
  7454. a.click();
  7455. }
  7456. else {
  7457. var newWindow = window.open("");
  7458. if (!newWindow)
  7459. return;
  7460. var img = newWindow.document.createElement("img");
  7461. img.onload = function () {
  7462. // no longer need to read the blob so it's revoked
  7463. URL.revokeObjectURL(url);
  7464. };
  7465. img.src = url;
  7466. newWindow.document.body.appendChild(img);
  7467. }
  7468. });
  7469. }
  7470. };
  7471. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  7472. if (mimeType === void 0) { mimeType = "image/png"; }
  7473. var width;
  7474. var height;
  7475. // If a precision value is specified
  7476. if (size.precision) {
  7477. width = Math.round(engine.getRenderWidth() * size.precision);
  7478. height = Math.round(width / engine.getAspectRatio(camera));
  7479. }
  7480. else if (size.width && size.height) {
  7481. width = size.width;
  7482. height = size.height;
  7483. }
  7484. else if (size.width && !size.height) {
  7485. width = size.width;
  7486. height = Math.round(width / engine.getAspectRatio(camera));
  7487. }
  7488. else if (size.height && !size.width) {
  7489. height = size.height;
  7490. width = Math.round(height * engine.getAspectRatio(camera));
  7491. }
  7492. else if (!isNaN(size)) {
  7493. height = size;
  7494. width = size;
  7495. }
  7496. else {
  7497. Tools.Error("Invalid 'size' parameter !");
  7498. return;
  7499. }
  7500. if (!screenshotCanvas) {
  7501. screenshotCanvas = document.createElement('canvas');
  7502. }
  7503. screenshotCanvas.width = width;
  7504. screenshotCanvas.height = height;
  7505. var renderContext = screenshotCanvas.getContext("2d");
  7506. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  7507. var newWidth = width;
  7508. var newHeight = newWidth / ratio;
  7509. if (newHeight > height) {
  7510. newHeight = height;
  7511. newWidth = newHeight * ratio;
  7512. }
  7513. var offsetX = Math.max(0, width - newWidth) / 2;
  7514. var offsetY = Math.max(0, height - newHeight) / 2;
  7515. var renderingCanvas = engine.getRenderingCanvas();
  7516. if (renderContext && renderingCanvas) {
  7517. renderContext.drawImage(renderingCanvas, offsetX, offsetY, newWidth, newHeight);
  7518. }
  7519. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  7520. };
  7521. /**
  7522. * Generates an image screenshot from the specified camera.
  7523. *
  7524. * @param engine The engine to use for rendering
  7525. * @param camera The camera to use for rendering
  7526. * @param size This parameter can be set to a single number or to an object with the
  7527. * following (optional) properties: precision, width, height. If a single number is passed,
  7528. * it will be used for both width and height. If an object is passed, the screenshot size
  7529. * will be derived from the parameters. The precision property is a multiplier allowing
  7530. * rendering at a higher or lower resolution.
  7531. * @param successCallback The callback receives a single parameter which contains the
  7532. * screenshot as a string of base64-encoded characters. This string can be assigned to the
  7533. * src parameter of an <img> to display it.
  7534. * @param mimeType The MIME type of the screenshot image (default: image/png).
  7535. * Check your browser for supported MIME types.
  7536. * @param samples Texture samples (default: 1)
  7537. * @param antialiasing Whether antialiasing should be turned on or not (default: false)
  7538. * @param fileName A name for for the downloaded file.
  7539. * @constructor
  7540. */
  7541. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples, antialiasing, fileName) {
  7542. if (mimeType === void 0) { mimeType = "image/png"; }
  7543. if (samples === void 0) { samples = 1; }
  7544. if (antialiasing === void 0) { antialiasing = false; }
  7545. var width;
  7546. var height;
  7547. //If a precision value is specified
  7548. if (size.precision) {
  7549. width = Math.round(engine.getRenderWidth() * size.precision);
  7550. height = Math.round(width / engine.getAspectRatio(camera));
  7551. size = { width: width, height: height };
  7552. }
  7553. else if (size.width && size.height) {
  7554. width = size.width;
  7555. height = size.height;
  7556. }
  7557. else if (size.width && !size.height) {
  7558. width = size.width;
  7559. height = Math.round(width / engine.getAspectRatio(camera));
  7560. size = { width: width, height: height };
  7561. }
  7562. else if (size.height && !size.width) {
  7563. height = size.height;
  7564. width = Math.round(height * engine.getAspectRatio(camera));
  7565. size = { width: width, height: height };
  7566. }
  7567. else if (!isNaN(size)) {
  7568. height = size;
  7569. width = size;
  7570. }
  7571. else {
  7572. Tools.Error("Invalid 'size' parameter !");
  7573. return;
  7574. }
  7575. var scene = camera.getScene();
  7576. var previousCamera = null;
  7577. if (scene.activeCamera !== camera) {
  7578. previousCamera = scene.activeCamera;
  7579. scene.activeCamera = camera;
  7580. }
  7581. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  7582. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  7583. texture.renderList = null;
  7584. texture.samples = samples;
  7585. if (antialiasing) {
  7586. texture.addPostProcess(new BABYLON.FxaaPostProcess('antialiasing', 1.0, scene.activeCamera));
  7587. }
  7588. texture.onAfterRenderObservable.add(function () {
  7589. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType, fileName);
  7590. });
  7591. scene.incrementRenderId();
  7592. scene.resetCachedMaterial();
  7593. texture.render(true);
  7594. texture.dispose();
  7595. if (previousCamera) {
  7596. scene.activeCamera = previousCamera;
  7597. }
  7598. camera.getProjectionMatrix(true); // Force cache refresh;
  7599. };
  7600. // XHR response validator for local file scenario
  7601. Tools.ValidateXHRData = function (xhr, dataType) {
  7602. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  7603. if (dataType === void 0) { dataType = 7; }
  7604. try {
  7605. if (dataType & 1) {
  7606. if (xhr.responseText && xhr.responseText.length > 0) {
  7607. return true;
  7608. }
  7609. else if (dataType === 1) {
  7610. return false;
  7611. }
  7612. }
  7613. if (dataType & 2) {
  7614. // Check header width and height since there is no "TGA" magic number
  7615. var tgaHeader = BABYLON.TGATools.GetTGAHeader(xhr.response);
  7616. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  7617. return true;
  7618. }
  7619. else if (dataType === 2) {
  7620. return false;
  7621. }
  7622. }
  7623. if (dataType & 4) {
  7624. // Check for the "DDS" magic number
  7625. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  7626. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  7627. return true;
  7628. }
  7629. else {
  7630. return false;
  7631. }
  7632. }
  7633. }
  7634. catch (e) {
  7635. // Global protection
  7636. }
  7637. return false;
  7638. };
  7639. /**
  7640. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  7641. * Be aware Math.random() could cause collisions, but:
  7642. * "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"
  7643. */
  7644. Tools.RandomId = function () {
  7645. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  7646. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  7647. return v.toString(16);
  7648. });
  7649. };
  7650. Object.defineProperty(Tools, "NoneLogLevel", {
  7651. get: function () {
  7652. return Tools._NoneLogLevel;
  7653. },
  7654. enumerable: true,
  7655. configurable: true
  7656. });
  7657. Object.defineProperty(Tools, "MessageLogLevel", {
  7658. get: function () {
  7659. return Tools._MessageLogLevel;
  7660. },
  7661. enumerable: true,
  7662. configurable: true
  7663. });
  7664. Object.defineProperty(Tools, "WarningLogLevel", {
  7665. get: function () {
  7666. return Tools._WarningLogLevel;
  7667. },
  7668. enumerable: true,
  7669. configurable: true
  7670. });
  7671. Object.defineProperty(Tools, "ErrorLogLevel", {
  7672. get: function () {
  7673. return Tools._ErrorLogLevel;
  7674. },
  7675. enumerable: true,
  7676. configurable: true
  7677. });
  7678. Object.defineProperty(Tools, "AllLogLevel", {
  7679. get: function () {
  7680. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  7681. },
  7682. enumerable: true,
  7683. configurable: true
  7684. });
  7685. Tools._AddLogEntry = function (entry) {
  7686. Tools._LogCache = entry + Tools._LogCache;
  7687. if (Tools.OnNewCacheEntry) {
  7688. Tools.OnNewCacheEntry(entry);
  7689. }
  7690. };
  7691. Tools._FormatMessage = function (message) {
  7692. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  7693. var date = new Date();
  7694. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  7695. };
  7696. Tools._LogDisabled = function (message) {
  7697. // nothing to do
  7698. };
  7699. Tools._LogEnabled = function (message) {
  7700. var formattedMessage = Tools._FormatMessage(message);
  7701. console.log("BJS - " + formattedMessage);
  7702. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  7703. Tools._AddLogEntry(entry);
  7704. };
  7705. Tools._WarnDisabled = function (message) {
  7706. // nothing to do
  7707. };
  7708. Tools._WarnEnabled = function (message) {
  7709. var formattedMessage = Tools._FormatMessage(message);
  7710. console.warn("BJS - " + formattedMessage);
  7711. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  7712. Tools._AddLogEntry(entry);
  7713. };
  7714. Tools._ErrorDisabled = function (message) {
  7715. // nothing to do
  7716. };
  7717. Tools._ErrorEnabled = function (message) {
  7718. Tools.errorsCount++;
  7719. var formattedMessage = Tools._FormatMessage(message);
  7720. console.error("BJS - " + formattedMessage);
  7721. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  7722. Tools._AddLogEntry(entry);
  7723. };
  7724. Object.defineProperty(Tools, "LogCache", {
  7725. get: function () {
  7726. return Tools._LogCache;
  7727. },
  7728. enumerable: true,
  7729. configurable: true
  7730. });
  7731. Tools.ClearLogCache = function () {
  7732. Tools._LogCache = "";
  7733. Tools.errorsCount = 0;
  7734. };
  7735. Object.defineProperty(Tools, "LogLevels", {
  7736. set: function (level) {
  7737. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  7738. Tools.Log = Tools._LogEnabled;
  7739. }
  7740. else {
  7741. Tools.Log = Tools._LogDisabled;
  7742. }
  7743. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  7744. Tools.Warn = Tools._WarnEnabled;
  7745. }
  7746. else {
  7747. Tools.Warn = Tools._WarnDisabled;
  7748. }
  7749. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  7750. Tools.Error = Tools._ErrorEnabled;
  7751. }
  7752. else {
  7753. Tools.Error = Tools._ErrorDisabled;
  7754. }
  7755. },
  7756. enumerable: true,
  7757. configurable: true
  7758. });
  7759. Tools.IsWindowObjectExist = function () {
  7760. return (typeof window) !== "undefined";
  7761. };
  7762. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  7763. get: function () {
  7764. return Tools._PerformanceNoneLogLevel;
  7765. },
  7766. enumerable: true,
  7767. configurable: true
  7768. });
  7769. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  7770. get: function () {
  7771. return Tools._PerformanceUserMarkLogLevel;
  7772. },
  7773. enumerable: true,
  7774. configurable: true
  7775. });
  7776. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  7777. get: function () {
  7778. return Tools._PerformanceConsoleLogLevel;
  7779. },
  7780. enumerable: true,
  7781. configurable: true
  7782. });
  7783. Object.defineProperty(Tools, "PerformanceLogLevel", {
  7784. set: function (level) {
  7785. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  7786. Tools.StartPerformanceCounter = Tools._StartUserMark;
  7787. Tools.EndPerformanceCounter = Tools._EndUserMark;
  7788. return;
  7789. }
  7790. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  7791. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  7792. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  7793. return;
  7794. }
  7795. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  7796. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  7797. },
  7798. enumerable: true,
  7799. configurable: true
  7800. });
  7801. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  7802. };
  7803. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  7804. };
  7805. Tools._StartUserMark = function (counterName, condition) {
  7806. if (condition === void 0) { condition = true; }
  7807. if (!Tools._performance) {
  7808. if (!Tools.IsWindowObjectExist()) {
  7809. return;
  7810. }
  7811. Tools._performance = window.performance;
  7812. }
  7813. if (!condition || !Tools._performance.mark) {
  7814. return;
  7815. }
  7816. Tools._performance.mark(counterName + "-Begin");
  7817. };
  7818. Tools._EndUserMark = function (counterName, condition) {
  7819. if (condition === void 0) { condition = true; }
  7820. if (!condition || !Tools._performance.mark) {
  7821. return;
  7822. }
  7823. Tools._performance.mark(counterName + "-End");
  7824. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  7825. };
  7826. Tools._StartPerformanceConsole = function (counterName, condition) {
  7827. if (condition === void 0) { condition = true; }
  7828. if (!condition) {
  7829. return;
  7830. }
  7831. Tools._StartUserMark(counterName, condition);
  7832. if (console.time) {
  7833. console.time(counterName);
  7834. }
  7835. };
  7836. Tools._EndPerformanceConsole = function (counterName, condition) {
  7837. if (condition === void 0) { condition = true; }
  7838. if (!condition) {
  7839. return;
  7840. }
  7841. Tools._EndUserMark(counterName, condition);
  7842. if (console.time) {
  7843. console.timeEnd(counterName);
  7844. }
  7845. };
  7846. Object.defineProperty(Tools, "Now", {
  7847. get: function () {
  7848. if (Tools.IsWindowObjectExist() && window.performance && window.performance.now) {
  7849. return window.performance.now();
  7850. }
  7851. return new Date().getTime();
  7852. },
  7853. enumerable: true,
  7854. configurable: true
  7855. });
  7856. /**
  7857. * This method will return the name of the class used to create the instance of the given object.
  7858. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  7859. * @param object the object to get the class name from
  7860. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  7861. */
  7862. Tools.GetClassName = function (object, isType) {
  7863. if (isType === void 0) { isType = false; }
  7864. var name = null;
  7865. if (!isType && object.getClassName) {
  7866. name = object.getClassName();
  7867. }
  7868. else {
  7869. if (object instanceof Object) {
  7870. var classObj = isType ? object : Object.getPrototypeOf(object);
  7871. name = classObj.constructor["__bjsclassName__"];
  7872. }
  7873. if (!name) {
  7874. name = typeof object;
  7875. }
  7876. }
  7877. return name;
  7878. };
  7879. Tools.First = function (array, predicate) {
  7880. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  7881. var el = array_1[_i];
  7882. if (predicate(el)) {
  7883. return el;
  7884. }
  7885. }
  7886. return null;
  7887. };
  7888. /**
  7889. * This method will return the name of the full name of the class, including its owning module (if any).
  7890. * 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).
  7891. * @param object the object to get the class name from
  7892. * @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.
  7893. */
  7894. Tools.getFullClassName = function (object, isType) {
  7895. if (isType === void 0) { isType = false; }
  7896. var className = null;
  7897. var moduleName = null;
  7898. if (!isType && object.getClassName) {
  7899. className = object.getClassName();
  7900. }
  7901. else {
  7902. if (object instanceof Object) {
  7903. var classObj = isType ? object : Object.getPrototypeOf(object);
  7904. className = classObj.constructor["__bjsclassName__"];
  7905. moduleName = classObj.constructor["__bjsmoduleName__"];
  7906. }
  7907. if (!className) {
  7908. className = typeof object;
  7909. }
  7910. }
  7911. if (!className) {
  7912. return null;
  7913. }
  7914. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  7915. };
  7916. /**
  7917. * 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.
  7918. * @param array
  7919. */
  7920. Tools.arrayOrStringFeeder = function (array) {
  7921. return function (index) {
  7922. if (index >= array.length) {
  7923. return null;
  7924. }
  7925. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  7926. if (val && val.getHashCode) {
  7927. val = val.getHashCode();
  7928. }
  7929. if (typeof val === "string") {
  7930. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  7931. }
  7932. return val;
  7933. };
  7934. };
  7935. /**
  7936. * Compute the hashCode of a stream of number
  7937. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  7938. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  7939. * @return the hash code computed
  7940. */
  7941. Tools.hashCodeFromStream = function (feeder) {
  7942. // Based from here: http://stackoverflow.com/a/7616484/802124
  7943. var hash = 0;
  7944. var index = 0;
  7945. var chr = feeder(index++);
  7946. while (chr != null) {
  7947. hash = ((hash << 5) - hash) + chr;
  7948. hash |= 0; // Convert to 32bit integer
  7949. chr = feeder(index++);
  7950. }
  7951. return hash;
  7952. };
  7953. Tools.BaseUrl = "";
  7954. Tools.DefaultRetryStrategy = RetryStrategy.ExponentialBackoff();
  7955. /**
  7956. * Default behaviour for cors in the application.
  7957. * It can be a string if the expected behavior is identical in the entire app.
  7958. * Or a callback to be able to set it per url or on a group of them (in case of Video source for instance)
  7959. */
  7960. Tools.CorsBehavior = "anonymous";
  7961. Tools.UseFallbackTexture = true;
  7962. /**
  7963. * Use this object to register external classes like custom textures or material
  7964. * to allow the laoders to instantiate them
  7965. */
  7966. Tools.RegisteredExternalClasses = {};
  7967. // Used in case of a texture loading problem
  7968. 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";
  7969. Tools.PreprocessUrl = function (url) {
  7970. return url;
  7971. };
  7972. // Logs
  7973. Tools._NoneLogLevel = 0;
  7974. Tools._MessageLogLevel = 1;
  7975. Tools._WarningLogLevel = 2;
  7976. Tools._ErrorLogLevel = 4;
  7977. Tools._LogCache = "";
  7978. Tools.errorsCount = 0;
  7979. Tools.Log = Tools._LogEnabled;
  7980. Tools.Warn = Tools._WarnEnabled;
  7981. Tools.Error = Tools._ErrorEnabled;
  7982. // Performances
  7983. Tools._PerformanceNoneLogLevel = 0;
  7984. Tools._PerformanceUserMarkLogLevel = 1;
  7985. Tools._PerformanceConsoleLogLevel = 2;
  7986. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  7987. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  7988. return Tools;
  7989. }());
  7990. BABYLON.Tools = Tools;
  7991. /**
  7992. * This class is used to track a performance counter which is number based.
  7993. * The user has access to many properties which give statistics of different nature
  7994. *
  7995. * The implementer can track two kinds of Performance Counter: time and count
  7996. * 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.
  7997. * 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.
  7998. */
  7999. var PerfCounter = /** @class */ (function () {
  8000. function PerfCounter() {
  8001. this._startMonitoringTime = 0;
  8002. this._min = 0;
  8003. this._max = 0;
  8004. this._average = 0;
  8005. this._lastSecAverage = 0;
  8006. this._current = 0;
  8007. this._totalValueCount = 0;
  8008. this._totalAccumulated = 0;
  8009. this._lastSecAccumulated = 0;
  8010. this._lastSecTime = 0;
  8011. this._lastSecValueCount = 0;
  8012. }
  8013. Object.defineProperty(PerfCounter.prototype, "min", {
  8014. /**
  8015. * Returns the smallest value ever
  8016. */
  8017. get: function () {
  8018. return this._min;
  8019. },
  8020. enumerable: true,
  8021. configurable: true
  8022. });
  8023. Object.defineProperty(PerfCounter.prototype, "max", {
  8024. /**
  8025. * Returns the biggest value ever
  8026. */
  8027. get: function () {
  8028. return this._max;
  8029. },
  8030. enumerable: true,
  8031. configurable: true
  8032. });
  8033. Object.defineProperty(PerfCounter.prototype, "average", {
  8034. /**
  8035. * Returns the average value since the performance counter is running
  8036. */
  8037. get: function () {
  8038. return this._average;
  8039. },
  8040. enumerable: true,
  8041. configurable: true
  8042. });
  8043. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  8044. /**
  8045. * Returns the average value of the last second the counter was monitored
  8046. */
  8047. get: function () {
  8048. return this._lastSecAverage;
  8049. },
  8050. enumerable: true,
  8051. configurable: true
  8052. });
  8053. Object.defineProperty(PerfCounter.prototype, "current", {
  8054. /**
  8055. * Returns the current value
  8056. */
  8057. get: function () {
  8058. return this._current;
  8059. },
  8060. enumerable: true,
  8061. configurable: true
  8062. });
  8063. Object.defineProperty(PerfCounter.prototype, "total", {
  8064. get: function () {
  8065. return this._totalAccumulated;
  8066. },
  8067. enumerable: true,
  8068. configurable: true
  8069. });
  8070. Object.defineProperty(PerfCounter.prototype, "count", {
  8071. get: function () {
  8072. return this._totalValueCount;
  8073. },
  8074. enumerable: true,
  8075. configurable: true
  8076. });
  8077. /**
  8078. * Call this method to start monitoring a new frame.
  8079. * 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.
  8080. */
  8081. PerfCounter.prototype.fetchNewFrame = function () {
  8082. this._totalValueCount++;
  8083. this._current = 0;
  8084. this._lastSecValueCount++;
  8085. };
  8086. /**
  8087. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  8088. * @param newCount the count value to add to the monitored count
  8089. * @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.
  8090. */
  8091. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  8092. if (!PerfCounter.Enabled) {
  8093. return;
  8094. }
  8095. this._current += newCount;
  8096. if (fetchResult) {
  8097. this._fetchResult();
  8098. }
  8099. };
  8100. /**
  8101. * Start monitoring this performance counter
  8102. */
  8103. PerfCounter.prototype.beginMonitoring = function () {
  8104. if (!PerfCounter.Enabled) {
  8105. return;
  8106. }
  8107. this._startMonitoringTime = Tools.Now;
  8108. };
  8109. /**
  8110. * Compute the time lapsed since the previous beginMonitoring() call.
  8111. * @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
  8112. */
  8113. PerfCounter.prototype.endMonitoring = function (newFrame) {
  8114. if (newFrame === void 0) { newFrame = true; }
  8115. if (!PerfCounter.Enabled) {
  8116. return;
  8117. }
  8118. if (newFrame) {
  8119. this.fetchNewFrame();
  8120. }
  8121. var currentTime = Tools.Now;
  8122. this._current = currentTime - this._startMonitoringTime;
  8123. if (newFrame) {
  8124. this._fetchResult();
  8125. }
  8126. };
  8127. PerfCounter.prototype._fetchResult = function () {
  8128. this._totalAccumulated += this._current;
  8129. this._lastSecAccumulated += this._current;
  8130. // Min/Max update
  8131. this._min = Math.min(this._min, this._current);
  8132. this._max = Math.max(this._max, this._current);
  8133. this._average = this._totalAccumulated / this._totalValueCount;
  8134. // Reset last sec?
  8135. var now = Tools.Now;
  8136. if ((now - this._lastSecTime) > 1000) {
  8137. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  8138. this._lastSecTime = now;
  8139. this._lastSecAccumulated = 0;
  8140. this._lastSecValueCount = 0;
  8141. }
  8142. };
  8143. PerfCounter.Enabled = true;
  8144. return PerfCounter;
  8145. }());
  8146. BABYLON.PerfCounter = PerfCounter;
  8147. /**
  8148. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  8149. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  8150. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  8151. * @param name The name of the class, case should be preserved
  8152. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  8153. */
  8154. function className(name, module) {
  8155. return function (target) {
  8156. target["__bjsclassName__"] = name;
  8157. target["__bjsmoduleName__"] = (module != null) ? module : null;
  8158. };
  8159. }
  8160. BABYLON.className = className;
  8161. /**
  8162. * An implementation of a loop for asynchronous functions.
  8163. */
  8164. var AsyncLoop = /** @class */ (function () {
  8165. /**
  8166. * Constroctor.
  8167. * @param iterations the number of iterations.
  8168. * @param _fn the function to run each iteration
  8169. * @param _successCallback the callback that will be called upon succesful execution
  8170. * @param offset starting offset.
  8171. */
  8172. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  8173. if (offset === void 0) { offset = 0; }
  8174. this.iterations = iterations;
  8175. this._fn = _fn;
  8176. this._successCallback = _successCallback;
  8177. this.index = offset - 1;
  8178. this._done = false;
  8179. }
  8180. /**
  8181. * Execute the next iteration. Must be called after the last iteration was finished.
  8182. */
  8183. AsyncLoop.prototype.executeNext = function () {
  8184. if (!this._done) {
  8185. if (this.index + 1 < this.iterations) {
  8186. ++this.index;
  8187. this._fn(this);
  8188. }
  8189. else {
  8190. this.breakLoop();
  8191. }
  8192. }
  8193. };
  8194. /**
  8195. * Break the loop and run the success callback.
  8196. */
  8197. AsyncLoop.prototype.breakLoop = function () {
  8198. this._done = true;
  8199. this._successCallback();
  8200. };
  8201. /**
  8202. * Helper function
  8203. */
  8204. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  8205. if (offset === void 0) { offset = 0; }
  8206. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  8207. loop.executeNext();
  8208. return loop;
  8209. };
  8210. /**
  8211. * A for-loop that will run a given number of iterations synchronous and the rest async.
  8212. * @param iterations total number of iterations
  8213. * @param syncedIterations number of synchronous iterations in each async iteration.
  8214. * @param fn the function to call each iteration.
  8215. * @param callback a success call back that will be called when iterating stops.
  8216. * @param breakFunction a break condition (optional)
  8217. * @param timeout timeout settings for the setTimeout function. default - 0.
  8218. * @constructor
  8219. */
  8220. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  8221. if (timeout === void 0) { timeout = 0; }
  8222. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  8223. if (breakFunction && breakFunction())
  8224. loop.breakLoop();
  8225. else {
  8226. setTimeout(function () {
  8227. for (var i = 0; i < syncedIterations; ++i) {
  8228. var iteration = (loop.index * syncedIterations) + i;
  8229. if (iteration >= iterations)
  8230. break;
  8231. fn(iteration);
  8232. if (breakFunction && breakFunction()) {
  8233. loop.breakLoop();
  8234. break;
  8235. }
  8236. }
  8237. loop.executeNext();
  8238. }, timeout);
  8239. }
  8240. }, callback);
  8241. };
  8242. return AsyncLoop;
  8243. }());
  8244. BABYLON.AsyncLoop = AsyncLoop;
  8245. })(BABYLON || (BABYLON = {}));
  8246. //# sourceMappingURL=babylon.tools.js.map
  8247. var BABYLON;
  8248. (function (BABYLON) {
  8249. var PromiseStates;
  8250. (function (PromiseStates) {
  8251. PromiseStates[PromiseStates["Pending"] = 0] = "Pending";
  8252. PromiseStates[PromiseStates["Fulfilled"] = 1] = "Fulfilled";
  8253. PromiseStates[PromiseStates["Rejected"] = 2] = "Rejected";
  8254. })(PromiseStates || (PromiseStates = {}));
  8255. var FulFillmentAgregator = /** @class */ (function () {
  8256. function FulFillmentAgregator() {
  8257. this.count = 0;
  8258. this.target = 0;
  8259. this.results = [];
  8260. }
  8261. return FulFillmentAgregator;
  8262. }());
  8263. var InternalPromise = /** @class */ (function () {
  8264. function InternalPromise(resolver) {
  8265. var _this = this;
  8266. this._state = PromiseStates.Pending;
  8267. this._children = new Array();
  8268. this._rejectWasConsumed = false;
  8269. if (!resolver) {
  8270. return;
  8271. }
  8272. try {
  8273. resolver(function (value) {
  8274. _this._resolve(value);
  8275. }, function (reason) {
  8276. _this._reject(reason);
  8277. });
  8278. }
  8279. catch (e) {
  8280. this._reject(e.message);
  8281. }
  8282. }
  8283. Object.defineProperty(InternalPromise.prototype, "state", {
  8284. get: function () {
  8285. return this._state;
  8286. },
  8287. enumerable: true,
  8288. configurable: true
  8289. });
  8290. Object.defineProperty(InternalPromise.prototype, "isFulfilled", {
  8291. get: function () {
  8292. return this._state === PromiseStates.Fulfilled;
  8293. },
  8294. enumerable: true,
  8295. configurable: true
  8296. });
  8297. Object.defineProperty(InternalPromise.prototype, "isRejected", {
  8298. get: function () {
  8299. return this._state === PromiseStates.Rejected;
  8300. },
  8301. enumerable: true,
  8302. configurable: true
  8303. });
  8304. Object.defineProperty(InternalPromise.prototype, "isPending", {
  8305. get: function () {
  8306. return this._state === PromiseStates.Pending;
  8307. },
  8308. enumerable: true,
  8309. configurable: true
  8310. });
  8311. InternalPromise.prototype.value = function () {
  8312. if (!this.isFulfilled) {
  8313. throw new Error("Promise is not fulfilled");
  8314. }
  8315. return this._result;
  8316. };
  8317. InternalPromise.prototype.reason = function () {
  8318. if (!this.isRejected) {
  8319. throw new Error("Promise is not rejected");
  8320. }
  8321. return this._reason;
  8322. };
  8323. InternalPromise.prototype.catch = function (onRejected) {
  8324. return this.then(undefined, onRejected);
  8325. };
  8326. InternalPromise.prototype.then = function (onFulfilled, onRejected) {
  8327. var newPromise = new InternalPromise();
  8328. newPromise._onFulfilled = onFulfilled;
  8329. newPromise._onRejected = onRejected;
  8330. // Composition
  8331. this._children.push(newPromise);
  8332. if (this._state !== PromiseStates.Pending) {
  8333. if (this._state === PromiseStates.Fulfilled || this._rejectWasConsumed) {
  8334. var returnedValue = newPromise._resolve(this._result);
  8335. if (returnedValue !== undefined && returnedValue !== null) {
  8336. if (returnedValue._state !== undefined) {
  8337. var returnedPromise = returnedValue;
  8338. newPromise._children.push(returnedPromise);
  8339. newPromise = returnedPromise;
  8340. }
  8341. else {
  8342. newPromise._result = returnedValue;
  8343. }
  8344. }
  8345. }
  8346. else {
  8347. newPromise._reject(this._reason);
  8348. }
  8349. }
  8350. return newPromise;
  8351. };
  8352. InternalPromise.prototype._moveChildren = function (children) {
  8353. this._children = children.splice(0, children.length);
  8354. if (this.isFulfilled) {
  8355. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  8356. var child = _a[_i];
  8357. child._resolve(this._result);
  8358. }
  8359. }
  8360. else if (this.isRejected) {
  8361. for (var _b = 0, _c = this._children; _b < _c.length; _b++) {
  8362. var child = _c[_b];
  8363. child._reject(this._reason);
  8364. }
  8365. }
  8366. };
  8367. InternalPromise.prototype._resolve = function (value) {
  8368. try {
  8369. this._state = PromiseStates.Fulfilled;
  8370. this._result = value;
  8371. var returnedValue = null;
  8372. if (this._onFulfilled) {
  8373. returnedValue = this._onFulfilled(value);
  8374. }
  8375. if (returnedValue !== undefined && returnedValue !== null) {
  8376. if (returnedValue._state !== undefined) {
  8377. // Transmit children
  8378. var returnedPromise = returnedValue;
  8379. returnedPromise._moveChildren(this._children);
  8380. }
  8381. }
  8382. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  8383. var child = _a[_i];
  8384. child._resolve(value);
  8385. }
  8386. return returnedValue;
  8387. }
  8388. catch (e) {
  8389. this._reject(e.message);
  8390. }
  8391. return null;
  8392. };
  8393. InternalPromise.prototype._reject = function (reason) {
  8394. this._state = PromiseStates.Rejected;
  8395. this._reason = reason;
  8396. if (this._onRejected) {
  8397. this._onRejected(reason);
  8398. this._rejectWasConsumed = true;
  8399. }
  8400. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  8401. var child = _a[_i];
  8402. if (this._rejectWasConsumed) {
  8403. child._resolve(null);
  8404. }
  8405. else {
  8406. child._reject(reason);
  8407. }
  8408. }
  8409. };
  8410. InternalPromise.resolve = function (value) {
  8411. var newPromise = new InternalPromise();
  8412. newPromise._resolve(value);
  8413. return newPromise;
  8414. };
  8415. InternalPromise._RegisterForFulfillment = function (promise, agregator, index) {
  8416. promise.then(function (value) {
  8417. agregator.results[index] = value;
  8418. agregator.count++;
  8419. if (agregator.count === agregator.target) {
  8420. agregator.rootPromise._resolve(agregator.results);
  8421. }
  8422. return null;
  8423. }, function (reason) {
  8424. if (!agregator.rootPromise.isRejected) {
  8425. agregator.rootPromise._reject(reason);
  8426. }
  8427. });
  8428. };
  8429. InternalPromise.all = function (promises) {
  8430. var newPromise = new InternalPromise();
  8431. var agregator = new FulFillmentAgregator();
  8432. agregator.target = promises.length;
  8433. agregator.rootPromise = newPromise;
  8434. for (var index = 0; index < promises.length; index++) {
  8435. InternalPromise._RegisterForFulfillment(promises[index], agregator, index);
  8436. }
  8437. return newPromise;
  8438. };
  8439. return InternalPromise;
  8440. }());
  8441. /**
  8442. * Helper class that provides a small promise polyfill
  8443. */
  8444. var PromisePolyfill = /** @class */ (function () {
  8445. function PromisePolyfill() {
  8446. }
  8447. /**
  8448. * Static function used to check if the polyfill is required
  8449. * If this is the case then the function will inject the polyfill to window.Promise
  8450. * @param force defines a boolean used to force the injection (mostly for testing purposes)
  8451. */
  8452. PromisePolyfill.Apply = function (force) {
  8453. if (force === void 0) { force = false; }
  8454. if (force || typeof Promise === 'undefined') {
  8455. var root = window;
  8456. root.Promise = InternalPromise;
  8457. }
  8458. };
  8459. return PromisePolyfill;
  8460. }());
  8461. BABYLON.PromisePolyfill = PromisePolyfill;
  8462. })(BABYLON || (BABYLON = {}));
  8463. //# sourceMappingURL=babylon.promise.js.map
  8464. var BABYLON;
  8465. (function (BABYLON) {
  8466. var _AlphaState = /** @class */ (function () {
  8467. /**
  8468. * Initializes the state.
  8469. */
  8470. function _AlphaState() {
  8471. this._isAlphaBlendDirty = false;
  8472. this._isBlendFunctionParametersDirty = false;
  8473. this._isBlendEquationParametersDirty = false;
  8474. this._isBlendConstantsDirty = false;
  8475. this._alphaBlend = false;
  8476. this._blendFunctionParameters = new Array(4);
  8477. this._blendEquationParameters = new Array(2);
  8478. this._blendConstants = new Array(4);
  8479. this.reset();
  8480. }
  8481. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  8482. get: function () {
  8483. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  8484. },
  8485. enumerable: true,
  8486. configurable: true
  8487. });
  8488. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  8489. get: function () {
  8490. return this._alphaBlend;
  8491. },
  8492. set: function (value) {
  8493. if (this._alphaBlend === value) {
  8494. return;
  8495. }
  8496. this._alphaBlend = value;
  8497. this._isAlphaBlendDirty = true;
  8498. },
  8499. enumerable: true,
  8500. configurable: true
  8501. });
  8502. _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
  8503. if (this._blendConstants[0] === r &&
  8504. this._blendConstants[1] === g &&
  8505. this._blendConstants[2] === b &&
  8506. this._blendConstants[3] === a) {
  8507. return;
  8508. }
  8509. this._blendConstants[0] = r;
  8510. this._blendConstants[1] = g;
  8511. this._blendConstants[2] = b;
  8512. this._blendConstants[3] = a;
  8513. this._isBlendConstantsDirty = true;
  8514. };
  8515. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  8516. if (this._blendFunctionParameters[0] === value0 &&
  8517. this._blendFunctionParameters[1] === value1 &&
  8518. this._blendFunctionParameters[2] === value2 &&
  8519. this._blendFunctionParameters[3] === value3) {
  8520. return;
  8521. }
  8522. this._blendFunctionParameters[0] = value0;
  8523. this._blendFunctionParameters[1] = value1;
  8524. this._blendFunctionParameters[2] = value2;
  8525. this._blendFunctionParameters[3] = value3;
  8526. this._isBlendFunctionParametersDirty = true;
  8527. };
  8528. _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
  8529. if (this._blendEquationParameters[0] === rgb &&
  8530. this._blendEquationParameters[1] === alpha) {
  8531. return;
  8532. }
  8533. this._blendEquationParameters[0] = rgb;
  8534. this._blendEquationParameters[1] = alpha;
  8535. this._isBlendEquationParametersDirty = true;
  8536. };
  8537. _AlphaState.prototype.reset = function () {
  8538. this._alphaBlend = false;
  8539. this._blendFunctionParameters[0] = null;
  8540. this._blendFunctionParameters[1] = null;
  8541. this._blendFunctionParameters[2] = null;
  8542. this._blendFunctionParameters[3] = null;
  8543. this._blendEquationParameters[0] = null;
  8544. this._blendEquationParameters[1] = null;
  8545. this._blendConstants[0] = null;
  8546. this._blendConstants[1] = null;
  8547. this._blendConstants[2] = null;
  8548. this._blendConstants[3] = null;
  8549. this._isAlphaBlendDirty = true;
  8550. this._isBlendFunctionParametersDirty = false;
  8551. this._isBlendEquationParametersDirty = false;
  8552. this._isBlendConstantsDirty = false;
  8553. };
  8554. _AlphaState.prototype.apply = function (gl) {
  8555. if (!this.isDirty) {
  8556. return;
  8557. }
  8558. // Alpha blend
  8559. if (this._isAlphaBlendDirty) {
  8560. if (this._alphaBlend) {
  8561. gl.enable(gl.BLEND);
  8562. }
  8563. else {
  8564. gl.disable(gl.BLEND);
  8565. }
  8566. this._isAlphaBlendDirty = false;
  8567. }
  8568. // Alpha function
  8569. if (this._isBlendFunctionParametersDirty) {
  8570. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  8571. this._isBlendFunctionParametersDirty = false;
  8572. }
  8573. // Alpha equation
  8574. if (this._isBlendEquationParametersDirty) {
  8575. gl.blendEquationSeparate(this._isBlendEquationParametersDirty[0], this._isBlendEquationParametersDirty[1]);
  8576. this._isBlendEquationParametersDirty = false;
  8577. }
  8578. // Constants
  8579. if (this._isBlendConstantsDirty) {
  8580. gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
  8581. this._isBlendConstantsDirty = false;
  8582. }
  8583. };
  8584. return _AlphaState;
  8585. }());
  8586. BABYLON._AlphaState = _AlphaState;
  8587. })(BABYLON || (BABYLON = {}));
  8588. //# sourceMappingURL=babylon.alphaCullingState.js.map
  8589. var BABYLON;
  8590. (function (BABYLON) {
  8591. var _DepthCullingState = /** @class */ (function () {
  8592. /**
  8593. * Initializes the state.
  8594. */
  8595. function _DepthCullingState() {
  8596. this._isDepthTestDirty = false;
  8597. this._isDepthMaskDirty = false;
  8598. this._isDepthFuncDirty = false;
  8599. this._isCullFaceDirty = false;
  8600. this._isCullDirty = false;
  8601. this._isZOffsetDirty = false;
  8602. this._isFrontFaceDirty = false;
  8603. this.reset();
  8604. }
  8605. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  8606. get: function () {
  8607. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty || this._isFrontFaceDirty;
  8608. },
  8609. enumerable: true,
  8610. configurable: true
  8611. });
  8612. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  8613. get: function () {
  8614. return this._zOffset;
  8615. },
  8616. set: function (value) {
  8617. if (this._zOffset === value) {
  8618. return;
  8619. }
  8620. this._zOffset = value;
  8621. this._isZOffsetDirty = true;
  8622. },
  8623. enumerable: true,
  8624. configurable: true
  8625. });
  8626. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  8627. get: function () {
  8628. return this._cullFace;
  8629. },
  8630. set: function (value) {
  8631. if (this._cullFace === value) {
  8632. return;
  8633. }
  8634. this._cullFace = value;
  8635. this._isCullFaceDirty = true;
  8636. },
  8637. enumerable: true,
  8638. configurable: true
  8639. });
  8640. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  8641. get: function () {
  8642. return this._cull;
  8643. },
  8644. set: function (value) {
  8645. if (this._cull === value) {
  8646. return;
  8647. }
  8648. this._cull = value;
  8649. this._isCullDirty = true;
  8650. },
  8651. enumerable: true,
  8652. configurable: true
  8653. });
  8654. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  8655. get: function () {
  8656. return this._depthFunc;
  8657. },
  8658. set: function (value) {
  8659. if (this._depthFunc === value) {
  8660. return;
  8661. }
  8662. this._depthFunc = value;
  8663. this._isDepthFuncDirty = true;
  8664. },
  8665. enumerable: true,
  8666. configurable: true
  8667. });
  8668. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  8669. get: function () {
  8670. return this._depthMask;
  8671. },
  8672. set: function (value) {
  8673. if (this._depthMask === value) {
  8674. return;
  8675. }
  8676. this._depthMask = value;
  8677. this._isDepthMaskDirty = true;
  8678. },
  8679. enumerable: true,
  8680. configurable: true
  8681. });
  8682. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  8683. get: function () {
  8684. return this._depthTest;
  8685. },
  8686. set: function (value) {
  8687. if (this._depthTest === value) {
  8688. return;
  8689. }
  8690. this._depthTest = value;
  8691. this._isDepthTestDirty = true;
  8692. },
  8693. enumerable: true,
  8694. configurable: true
  8695. });
  8696. Object.defineProperty(_DepthCullingState.prototype, "frontFace", {
  8697. get: function () {
  8698. return this._frontFace;
  8699. },
  8700. set: function (value) {
  8701. if (this._frontFace === value) {
  8702. return;
  8703. }
  8704. this._frontFace = value;
  8705. this._isFrontFaceDirty = true;
  8706. },
  8707. enumerable: true,
  8708. configurable: true
  8709. });
  8710. _DepthCullingState.prototype.reset = function () {
  8711. this._depthMask = true;
  8712. this._depthTest = true;
  8713. this._depthFunc = null;
  8714. this._cullFace = null;
  8715. this._cull = null;
  8716. this._zOffset = 0;
  8717. this._frontFace = null;
  8718. this._isDepthTestDirty = true;
  8719. this._isDepthMaskDirty = true;
  8720. this._isDepthFuncDirty = false;
  8721. this._isCullFaceDirty = false;
  8722. this._isCullDirty = false;
  8723. this._isZOffsetDirty = false;
  8724. this._isFrontFaceDirty = false;
  8725. };
  8726. _DepthCullingState.prototype.apply = function (gl) {
  8727. if (!this.isDirty) {
  8728. return;
  8729. }
  8730. // Cull
  8731. if (this._isCullDirty) {
  8732. if (this.cull) {
  8733. gl.enable(gl.CULL_FACE);
  8734. }
  8735. else {
  8736. gl.disable(gl.CULL_FACE);
  8737. }
  8738. this._isCullDirty = false;
  8739. }
  8740. // Cull face
  8741. if (this._isCullFaceDirty) {
  8742. gl.cullFace(this.cullFace);
  8743. this._isCullFaceDirty = false;
  8744. }
  8745. // Depth mask
  8746. if (this._isDepthMaskDirty) {
  8747. gl.depthMask(this.depthMask);
  8748. this._isDepthMaskDirty = false;
  8749. }
  8750. // Depth test
  8751. if (this._isDepthTestDirty) {
  8752. if (this.depthTest) {
  8753. gl.enable(gl.DEPTH_TEST);
  8754. }
  8755. else {
  8756. gl.disable(gl.DEPTH_TEST);
  8757. }
  8758. this._isDepthTestDirty = false;
  8759. }
  8760. // Depth func
  8761. if (this._isDepthFuncDirty) {
  8762. gl.depthFunc(this.depthFunc);
  8763. this._isDepthFuncDirty = false;
  8764. }
  8765. // zOffset
  8766. if (this._isZOffsetDirty) {
  8767. if (this.zOffset) {
  8768. gl.enable(gl.POLYGON_OFFSET_FILL);
  8769. gl.polygonOffset(this.zOffset, 0);
  8770. }
  8771. else {
  8772. gl.disable(gl.POLYGON_OFFSET_FILL);
  8773. }
  8774. this._isZOffsetDirty = false;
  8775. }
  8776. // Front face
  8777. if (this._isFrontFaceDirty) {
  8778. gl.frontFace(this.frontFace);
  8779. this._isFrontFaceDirty = false;
  8780. }
  8781. };
  8782. return _DepthCullingState;
  8783. }());
  8784. BABYLON._DepthCullingState = _DepthCullingState;
  8785. })(BABYLON || (BABYLON = {}));
  8786. //# sourceMappingURL=babylon.depthCullingState.js.map
  8787. var BABYLON;
  8788. (function (BABYLON) {
  8789. var _StencilState = /** @class */ (function () {
  8790. function _StencilState() {
  8791. this._isStencilTestDirty = false;
  8792. this._isStencilMaskDirty = false;
  8793. this._isStencilFuncDirty = false;
  8794. this._isStencilOpDirty = false;
  8795. this.reset();
  8796. }
  8797. Object.defineProperty(_StencilState.prototype, "isDirty", {
  8798. get: function () {
  8799. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  8800. },
  8801. enumerable: true,
  8802. configurable: true
  8803. });
  8804. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  8805. get: function () {
  8806. return this._stencilFunc;
  8807. },
  8808. set: function (value) {
  8809. if (this._stencilFunc === value) {
  8810. return;
  8811. }
  8812. this._stencilFunc = value;
  8813. this._isStencilFuncDirty = true;
  8814. },
  8815. enumerable: true,
  8816. configurable: true
  8817. });
  8818. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  8819. get: function () {
  8820. return this._stencilFuncRef;
  8821. },
  8822. set: function (value) {
  8823. if (this._stencilFuncRef === value) {
  8824. return;
  8825. }
  8826. this._stencilFuncRef = value;
  8827. this._isStencilFuncDirty = true;
  8828. },
  8829. enumerable: true,
  8830. configurable: true
  8831. });
  8832. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  8833. get: function () {
  8834. return this._stencilFuncMask;
  8835. },
  8836. set: function (value) {
  8837. if (this._stencilFuncMask === value) {
  8838. return;
  8839. }
  8840. this._stencilFuncMask = value;
  8841. this._isStencilFuncDirty = true;
  8842. },
  8843. enumerable: true,
  8844. configurable: true
  8845. });
  8846. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  8847. get: function () {
  8848. return this._stencilOpStencilFail;
  8849. },
  8850. set: function (value) {
  8851. if (this._stencilOpStencilFail === value) {
  8852. return;
  8853. }
  8854. this._stencilOpStencilFail = value;
  8855. this._isStencilOpDirty = true;
  8856. },
  8857. enumerable: true,
  8858. configurable: true
  8859. });
  8860. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  8861. get: function () {
  8862. return this._stencilOpDepthFail;
  8863. },
  8864. set: function (value) {
  8865. if (this._stencilOpDepthFail === value) {
  8866. return;
  8867. }
  8868. this._stencilOpDepthFail = value;
  8869. this._isStencilOpDirty = true;
  8870. },
  8871. enumerable: true,
  8872. configurable: true
  8873. });
  8874. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  8875. get: function () {
  8876. return this._stencilOpStencilDepthPass;
  8877. },
  8878. set: function (value) {
  8879. if (this._stencilOpStencilDepthPass === value) {
  8880. return;
  8881. }
  8882. this._stencilOpStencilDepthPass = value;
  8883. this._isStencilOpDirty = true;
  8884. },
  8885. enumerable: true,
  8886. configurable: true
  8887. });
  8888. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  8889. get: function () {
  8890. return this._stencilMask;
  8891. },
  8892. set: function (value) {
  8893. if (this._stencilMask === value) {
  8894. return;
  8895. }
  8896. this._stencilMask = value;
  8897. this._isStencilMaskDirty = true;
  8898. },
  8899. enumerable: true,
  8900. configurable: true
  8901. });
  8902. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  8903. get: function () {
  8904. return this._stencilTest;
  8905. },
  8906. set: function (value) {
  8907. if (this._stencilTest === value) {
  8908. return;
  8909. }
  8910. this._stencilTest = value;
  8911. this._isStencilTestDirty = true;
  8912. },
  8913. enumerable: true,
  8914. configurable: true
  8915. });
  8916. _StencilState.prototype.reset = function () {
  8917. this._stencilTest = false;
  8918. this._stencilMask = 0xFF;
  8919. this._stencilFunc = BABYLON.Engine.ALWAYS;
  8920. this._stencilFuncRef = 1;
  8921. this._stencilFuncMask = 0xFF;
  8922. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  8923. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  8924. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  8925. this._isStencilTestDirty = true;
  8926. this._isStencilMaskDirty = true;
  8927. this._isStencilFuncDirty = true;
  8928. this._isStencilOpDirty = true;
  8929. };
  8930. _StencilState.prototype.apply = function (gl) {
  8931. if (!this.isDirty) {
  8932. return;
  8933. }
  8934. // Stencil test
  8935. if (this._isStencilTestDirty) {
  8936. if (this.stencilTest) {
  8937. gl.enable(gl.STENCIL_TEST);
  8938. }
  8939. else {
  8940. gl.disable(gl.STENCIL_TEST);
  8941. }
  8942. this._isStencilTestDirty = false;
  8943. }
  8944. // Stencil mask
  8945. if (this._isStencilMaskDirty) {
  8946. gl.stencilMask(this.stencilMask);
  8947. this._isStencilMaskDirty = false;
  8948. }
  8949. // Stencil func
  8950. if (this._isStencilFuncDirty) {
  8951. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  8952. this._isStencilFuncDirty = false;
  8953. }
  8954. // Stencil op
  8955. if (this._isStencilOpDirty) {
  8956. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  8957. this._isStencilOpDirty = false;
  8958. }
  8959. };
  8960. return _StencilState;
  8961. }());
  8962. BABYLON._StencilState = _StencilState;
  8963. })(BABYLON || (BABYLON = {}));
  8964. //# sourceMappingURL=babylon.stencilState.js.map
  8965. var BABYLON;
  8966. (function (BABYLON) {
  8967. var compileShader = function (gl, source, type, defines, shaderVersion) {
  8968. return compileRawShader(gl, shaderVersion + (defines ? defines + "\n" : "") + source, type);
  8969. };
  8970. var compileRawShader = function (gl, source, type) {
  8971. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  8972. gl.shaderSource(shader, source);
  8973. gl.compileShader(shader);
  8974. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  8975. var log = gl.getShaderInfoLog(shader);
  8976. if (log) {
  8977. throw new Error(log);
  8978. }
  8979. }
  8980. if (!shader) {
  8981. throw new Error("Something went wrong while compile the shader.");
  8982. }
  8983. return shader;
  8984. };
  8985. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  8986. var magFilter = gl.NEAREST;
  8987. var minFilter = gl.NEAREST;
  8988. switch (samplingMode) {
  8989. case BABYLON.Texture.BILINEAR_SAMPLINGMODE:
  8990. magFilter = gl.LINEAR;
  8991. if (generateMipMaps) {
  8992. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  8993. }
  8994. else {
  8995. minFilter = gl.LINEAR;
  8996. }
  8997. break;
  8998. case BABYLON.Texture.TRILINEAR_SAMPLINGMODE:
  8999. magFilter = gl.LINEAR;
  9000. if (generateMipMaps) {
  9001. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  9002. }
  9003. else {
  9004. minFilter = gl.LINEAR;
  9005. }
  9006. break;
  9007. case BABYLON.Texture.NEAREST_SAMPLINGMODE:
  9008. magFilter = gl.NEAREST;
  9009. if (generateMipMaps) {
  9010. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  9011. }
  9012. else {
  9013. minFilter = gl.NEAREST;
  9014. }
  9015. break;
  9016. case BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST:
  9017. magFilter = gl.NEAREST;
  9018. if (generateMipMaps) {
  9019. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  9020. }
  9021. else {
  9022. minFilter = gl.NEAREST;
  9023. }
  9024. break;
  9025. case BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST:
  9026. magFilter = gl.NEAREST;
  9027. if (generateMipMaps) {
  9028. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  9029. }
  9030. else {
  9031. minFilter = gl.LINEAR;
  9032. }
  9033. break;
  9034. case BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR:
  9035. magFilter = gl.NEAREST;
  9036. if (generateMipMaps) {
  9037. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  9038. }
  9039. else {
  9040. minFilter = gl.LINEAR;
  9041. }
  9042. break;
  9043. case BABYLON.Texture.NEAREST_LINEAR:
  9044. magFilter = gl.NEAREST;
  9045. minFilter = gl.LINEAR;
  9046. break;
  9047. case BABYLON.Texture.NEAREST_NEAREST:
  9048. magFilter = gl.NEAREST;
  9049. minFilter = gl.NEAREST;
  9050. break;
  9051. case BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST:
  9052. magFilter = gl.LINEAR;
  9053. if (generateMipMaps) {
  9054. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  9055. }
  9056. else {
  9057. minFilter = gl.NEAREST;
  9058. }
  9059. break;
  9060. case BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR:
  9061. magFilter = gl.LINEAR;
  9062. if (generateMipMaps) {
  9063. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  9064. }
  9065. else {
  9066. minFilter = gl.NEAREST;
  9067. }
  9068. break;
  9069. case BABYLON.Texture.LINEAR_LINEAR:
  9070. magFilter = gl.LINEAR;
  9071. minFilter = gl.LINEAR;
  9072. break;
  9073. case BABYLON.Texture.LINEAR_NEAREST:
  9074. magFilter = gl.LINEAR;
  9075. minFilter = gl.NEAREST;
  9076. break;
  9077. }
  9078. return {
  9079. min: minFilter,
  9080. mag: magFilter
  9081. };
  9082. };
  9083. var partialLoadImg = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  9084. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  9085. var img;
  9086. var onload = function () {
  9087. loadedImages[index] = img;
  9088. loadedImages._internalCount++;
  9089. if (scene) {
  9090. scene._removePendingData(img);
  9091. }
  9092. if (loadedImages._internalCount === 6) {
  9093. onfinish(loadedImages);
  9094. }
  9095. };
  9096. var onerror = function (message, exception) {
  9097. if (scene) {
  9098. scene._removePendingData(img);
  9099. }
  9100. if (onErrorCallBack) {
  9101. onErrorCallBack(message, exception);
  9102. }
  9103. };
  9104. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  9105. if (scene) {
  9106. scene._addPendingData(img);
  9107. }
  9108. };
  9109. var cascadeLoadImgs = function (rootUrl, scene, onfinish, files, onError) {
  9110. if (onError === void 0) { onError = null; }
  9111. var loadedImages = [];
  9112. loadedImages._internalCount = 0;
  9113. for (var index = 0; index < 6; index++) {
  9114. partialLoadImg(files[index], index, loadedImages, scene, onfinish, onError);
  9115. }
  9116. };
  9117. var BufferPointer = /** @class */ (function () {
  9118. function BufferPointer() {
  9119. }
  9120. return BufferPointer;
  9121. }());
  9122. var InstancingAttributeInfo = /** @class */ (function () {
  9123. function InstancingAttributeInfo() {
  9124. }
  9125. return InstancingAttributeInfo;
  9126. }());
  9127. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  9128. /**
  9129. * Define options used to create a render target texture
  9130. */
  9131. var RenderTargetCreationOptions = /** @class */ (function () {
  9132. function RenderTargetCreationOptions() {
  9133. }
  9134. return RenderTargetCreationOptions;
  9135. }());
  9136. BABYLON.RenderTargetCreationOptions = RenderTargetCreationOptions;
  9137. /**
  9138. * Regroup several parameters relative to the browser in use
  9139. */
  9140. var EngineCapabilities = /** @class */ (function () {
  9141. function EngineCapabilities() {
  9142. }
  9143. return EngineCapabilities;
  9144. }());
  9145. BABYLON.EngineCapabilities = EngineCapabilities;
  9146. /**
  9147. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  9148. */
  9149. var Engine = /** @class */ (function () {
  9150. /**
  9151. * @constructor
  9152. * @param canvasOrContext defines the canvas or WebGL context to use for rendering
  9153. * @param antialias defines enable antialiasing (default: false)
  9154. * @param options defines further options to be sent to the getContext() function
  9155. * @param adaptToDeviceRatio defines whether to adapt to the device's viewport characteristics (default: false)
  9156. */
  9157. function Engine(canvasOrContext, antialias, options, adaptToDeviceRatio) {
  9158. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  9159. var _this = this;
  9160. // Public members
  9161. this.forcePOTTextures = false;
  9162. this.isFullscreen = false;
  9163. this.isPointerLock = false;
  9164. this.cullBackFaces = true;
  9165. this.renderEvenInBackground = true;
  9166. this.preventCacheWipeBetweenFrames = false;
  9167. // To enable/disable IDB support and avoid XHR on .manifest
  9168. this.enableOfflineSupport = false;
  9169. this.scenes = new Array();
  9170. this.postProcesses = new Array();
  9171. // Observables
  9172. /**
  9173. * Observable event triggered each time the rendering canvas is resized
  9174. */
  9175. this.onResizeObservable = new BABYLON.Observable();
  9176. /**
  9177. * Observable event triggered each time the canvas loses focus
  9178. */
  9179. this.onCanvasBlurObservable = new BABYLON.Observable();
  9180. /**
  9181. * Observable event triggered each time the canvas gains focus
  9182. */
  9183. this.onCanvasFocusObservable = new BABYLON.Observable();
  9184. /**
  9185. * Observable event triggered each time the canvas receives pointerout event
  9186. */
  9187. this.onCanvasPointerOutObservable = new BABYLON.Observable();
  9188. /**
  9189. * Observable event triggered before each texture is initialized
  9190. */
  9191. this.onBeforeTextureInitObservable = new BABYLON.Observable();
  9192. //WebVR
  9193. this._vrDisplay = undefined;
  9194. this._vrSupported = false;
  9195. this._vrExclusivePointerMode = false;
  9196. // Uniform buffers list
  9197. this.disableUniformBuffers = false;
  9198. this._uniformBuffers = new Array();
  9199. // Observables
  9200. /**
  9201. * Observable raised when the engine begins a new frame
  9202. */
  9203. this.onBeginFrameObservable = new BABYLON.Observable();
  9204. /**
  9205. * Observable raised when the engine ends the current frame
  9206. */
  9207. this.onEndFrameObservable = new BABYLON.Observable();
  9208. /**
  9209. * Observable raised when the engine is about to compile a shader
  9210. */
  9211. this.onBeforeShaderCompilationObservable = new BABYLON.Observable();
  9212. /**
  9213. * Observable raised when the engine has jsut compiled a shader
  9214. */
  9215. this.onAfterShaderCompilationObservable = new BABYLON.Observable();
  9216. this._windowIsBackground = false;
  9217. this._webGLVersion = 1.0;
  9218. this._badOS = false;
  9219. this._badDesktopOS = false;
  9220. /**
  9221. * Gets or sets a value indicating if we want to disable texture binding optmization.
  9222. * This could be required on some buggy drivers which wants to have textures bound in a progressive order
  9223. * By default Babylon.js will try to let textures bound where they are and only update the samplers to point where the texture is.
  9224. */
  9225. this.disableTextureBindingOptimization = false;
  9226. this.onVRDisplayChangedObservable = new BABYLON.Observable();
  9227. this.onVRRequestPresentComplete = new BABYLON.Observable();
  9228. this.onVRRequestPresentStart = new BABYLON.Observable();
  9229. this._colorWrite = true;
  9230. this._drawCalls = new BABYLON.PerfCounter();
  9231. this._textureCollisions = new BABYLON.PerfCounter();
  9232. this._renderingQueueLaunched = false;
  9233. this._activeRenderLoops = new Array();
  9234. // Deterministic lockstepMaxSteps
  9235. this._deterministicLockstep = false;
  9236. this._lockstepMaxSteps = 4;
  9237. // Lost context
  9238. this.onContextLostObservable = new BABYLON.Observable();
  9239. this.onContextRestoredObservable = new BABYLON.Observable();
  9240. this._contextWasLost = false;
  9241. this._doNotHandleContextLost = false;
  9242. // FPS
  9243. this._performanceMonitor = new BABYLON.PerformanceMonitor();
  9244. this._fps = 60;
  9245. this._deltaTime = 0;
  9246. /**
  9247. * Turn this value on if you want to pause FPS computation when in background
  9248. */
  9249. this.disablePerformanceMonitorInBackground = false;
  9250. // States
  9251. this._depthCullingState = new BABYLON._DepthCullingState();
  9252. this._stencilState = new BABYLON._StencilState();
  9253. this._alphaState = new BABYLON._AlphaState();
  9254. this._alphaMode = Engine.ALPHA_DISABLE;
  9255. // Cache
  9256. this._internalTexturesCache = new Array();
  9257. this._activeChannel = 0;
  9258. this._currentTextureChannel = -1;
  9259. this._boundTexturesCache = {};
  9260. this._compiledEffects = {};
  9261. this._vertexAttribArraysEnabled = [];
  9262. this._uintIndicesCurrentlySet = false;
  9263. this._currentBoundBuffer = new Array();
  9264. this._currentBufferPointers = new Array();
  9265. this._currentInstanceLocations = new Array();
  9266. this._currentInstanceBuffers = new Array();
  9267. this._firstBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  9268. this._lastBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  9269. this._vaoRecordInProgress = false;
  9270. this._mustWipeVertexAttributes = false;
  9271. this._nextFreeTextureSlots = new Array();
  9272. this._maxSimultaneousTextures = 0;
  9273. this._activeRequests = new Array();
  9274. // Hardware supported Compressed Textures
  9275. this._texturesSupported = new Array();
  9276. this._onVRFullScreenTriggered = function () {
  9277. if (_this._vrDisplay && _this._vrDisplay.isPresenting) {
  9278. //get the old size before we change
  9279. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  9280. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  9281. //get the width and height, change the render size
  9282. var leftEye = _this._vrDisplay.getEyeParameters('left');
  9283. _this.setHardwareScalingLevel(1);
  9284. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  9285. }
  9286. else {
  9287. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  9288. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  9289. }
  9290. };
  9291. this._boundUniforms = {};
  9292. // Register promises
  9293. BABYLON.PromisePolyfill.Apply();
  9294. var canvas = null;
  9295. Engine.Instances.push(this);
  9296. if (!canvasOrContext) {
  9297. return;
  9298. }
  9299. options = options || {};
  9300. if (canvasOrContext.getContext) {
  9301. canvas = canvasOrContext;
  9302. this._renderingCanvas = canvas;
  9303. if (antialias != null) {
  9304. options.antialias = antialias;
  9305. }
  9306. if (options.deterministicLockstep === undefined) {
  9307. options.deterministicLockstep = false;
  9308. }
  9309. if (options.lockstepMaxSteps === undefined) {
  9310. options.lockstepMaxSteps = 4;
  9311. }
  9312. if (options.preserveDrawingBuffer === undefined) {
  9313. options.preserveDrawingBuffer = false;
  9314. }
  9315. if (options.audioEngine === undefined) {
  9316. options.audioEngine = true;
  9317. }
  9318. if (options.stencil === undefined) {
  9319. options.stencil = true;
  9320. }
  9321. this._deterministicLockstep = options.deterministicLockstep;
  9322. this._lockstepMaxSteps = options.lockstepMaxSteps;
  9323. this._doNotHandleContextLost = options.doNotHandleContextLost ? true : false;
  9324. // Exceptions
  9325. if (navigator && navigator.userAgent) {
  9326. var ua = navigator.userAgent;
  9327. for (var _i = 0, _a = Engine.ExceptionList; _i < _a.length; _i++) {
  9328. var exception = _a[_i];
  9329. var key = exception.key;
  9330. var targets = exception.targets;
  9331. if (ua.indexOf(key) > -1) {
  9332. if (exception.capture && exception.captureConstraint) {
  9333. var capture = exception.capture;
  9334. var constraint = exception.captureConstraint;
  9335. var regex = new RegExp(capture);
  9336. var matches = regex.exec(ua);
  9337. if (matches && matches.length > 0) {
  9338. var capturedValue = parseInt(matches[matches.length - 1]);
  9339. if (capturedValue >= constraint) {
  9340. continue;
  9341. }
  9342. }
  9343. }
  9344. for (var _b = 0, targets_1 = targets; _b < targets_1.length; _b++) {
  9345. var target = targets_1[_b];
  9346. switch (target) {
  9347. case "uniformBuffer":
  9348. this.disableUniformBuffers = true;
  9349. break;
  9350. case "textureBindingOptimization":
  9351. this.disableTextureBindingOptimization = true;
  9352. break;
  9353. }
  9354. }
  9355. break;
  9356. }
  9357. }
  9358. }
  9359. // GL
  9360. if (!options.disableWebGL2Support) {
  9361. try {
  9362. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  9363. if (this._gl) {
  9364. this._webGLVersion = 2.0;
  9365. }
  9366. }
  9367. catch (e) {
  9368. // Do nothing
  9369. }
  9370. }
  9371. if (!this._gl) {
  9372. if (!canvas) {
  9373. throw new Error("The provided canvas is null or undefined.");
  9374. }
  9375. try {
  9376. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  9377. }
  9378. catch (e) {
  9379. throw new Error("WebGL not supported");
  9380. }
  9381. }
  9382. if (!this._gl) {
  9383. throw new Error("WebGL not supported");
  9384. }
  9385. this._onCanvasFocus = function () {
  9386. _this.onCanvasFocusObservable.notifyObservers(_this);
  9387. };
  9388. this._onCanvasBlur = function () {
  9389. _this.onCanvasBlurObservable.notifyObservers(_this);
  9390. };
  9391. canvas.addEventListener("focus", this._onCanvasFocus);
  9392. canvas.addEventListener("blur", this._onCanvasBlur);
  9393. this._onBlur = function () {
  9394. if (_this.disablePerformanceMonitorInBackground) {
  9395. _this._performanceMonitor.disable();
  9396. }
  9397. _this._windowIsBackground = true;
  9398. };
  9399. this._onFocus = function () {
  9400. if (_this.disablePerformanceMonitorInBackground) {
  9401. _this._performanceMonitor.enable();
  9402. }
  9403. _this._windowIsBackground = false;
  9404. };
  9405. this._onCanvasPointerOut = function () {
  9406. _this.onCanvasPointerOutObservable.notifyObservers(_this);
  9407. };
  9408. window.addEventListener("blur", this._onBlur);
  9409. window.addEventListener("focus", this._onFocus);
  9410. canvas.addEventListener("pointerout", this._onCanvasPointerOut);
  9411. // Context lost
  9412. if (!this._doNotHandleContextLost) {
  9413. this._onContextLost = function (evt) {
  9414. evt.preventDefault();
  9415. _this._contextWasLost = true;
  9416. BABYLON.Tools.Warn("WebGL context lost.");
  9417. _this.onContextLostObservable.notifyObservers(_this);
  9418. };
  9419. this._onContextRestored = function (evt) {
  9420. // Adding a timeout to avoid race condition at browser level
  9421. setTimeout(function () {
  9422. // Rebuild gl context
  9423. _this._initGLContext();
  9424. // Rebuild effects
  9425. _this._rebuildEffects();
  9426. // Rebuild textures
  9427. _this._rebuildInternalTextures();
  9428. // Rebuild buffers
  9429. _this._rebuildBuffers();
  9430. // Cache
  9431. _this.wipeCaches(true);
  9432. BABYLON.Tools.Warn("WebGL context successfully restored.");
  9433. _this.onContextRestoredObservable.notifyObservers(_this);
  9434. _this._contextWasLost = false;
  9435. }, 0);
  9436. };
  9437. canvas.addEventListener("webglcontextlost", this._onContextLost, false);
  9438. canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
  9439. }
  9440. }
  9441. else {
  9442. this._gl = canvasOrContext;
  9443. this._renderingCanvas = this._gl.canvas;
  9444. if (this._gl.renderbufferStorageMultisample) {
  9445. this._webGLVersion = 2.0;
  9446. }
  9447. options.stencil = this._gl.getContextAttributes().stencil;
  9448. }
  9449. // Viewport
  9450. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  9451. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  9452. this.resize();
  9453. this._isStencilEnable = options.stencil ? true : false;
  9454. this._initGLContext();
  9455. if (canvas) {
  9456. // Fullscreen
  9457. this._onFullscreenChange = function () {
  9458. if (document.fullscreen !== undefined) {
  9459. _this.isFullscreen = document.fullscreen;
  9460. }
  9461. else if (document.mozFullScreen !== undefined) {
  9462. _this.isFullscreen = document.mozFullScreen;
  9463. }
  9464. else if (document.webkitIsFullScreen !== undefined) {
  9465. _this.isFullscreen = document.webkitIsFullScreen;
  9466. }
  9467. else if (document.msIsFullScreen !== undefined) {
  9468. _this.isFullscreen = document.msIsFullScreen;
  9469. }
  9470. // Pointer lock
  9471. if (_this.isFullscreen && _this._pointerLockRequested && canvas) {
  9472. canvas.requestPointerLock = canvas.requestPointerLock ||
  9473. canvas.msRequestPointerLock ||
  9474. canvas.mozRequestPointerLock ||
  9475. canvas.webkitRequestPointerLock;
  9476. if (canvas.requestPointerLock) {
  9477. canvas.requestPointerLock();
  9478. }
  9479. }
  9480. };
  9481. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  9482. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  9483. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  9484. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  9485. // Pointer lock
  9486. this._onPointerLockChange = function () {
  9487. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  9488. document.webkitPointerLockElement === canvas ||
  9489. document.msPointerLockElement === canvas ||
  9490. document.pointerLockElement === canvas);
  9491. };
  9492. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  9493. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  9494. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  9495. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  9496. this._onVRDisplayPointerRestricted = function () {
  9497. if (canvas) {
  9498. canvas.requestPointerLock();
  9499. }
  9500. };
  9501. this._onVRDisplayPointerUnrestricted = function () {
  9502. document.exitPointerLock();
  9503. };
  9504. window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
  9505. window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
  9506. }
  9507. if (options.audioEngine && BABYLON.AudioEngine && !Engine.audioEngine) {
  9508. Engine.audioEngine = new BABYLON.AudioEngine();
  9509. }
  9510. // Prepare buffer pointers
  9511. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  9512. this._currentBufferPointers[i] = new BufferPointer();
  9513. }
  9514. this._linkTrackers(this._firstBoundInternalTextureTracker, this._lastBoundInternalTextureTracker);
  9515. // Load WebVR Devices
  9516. if (options.autoEnableWebVR) {
  9517. this.initWebVR();
  9518. }
  9519. // Detect if we are running on a faulty buggy OS.
  9520. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  9521. // Detect if we are running on a faulty buggy desktop OS.
  9522. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  9523. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  9524. this.enableOfflineSupport = (BABYLON.Database !== undefined);
  9525. }
  9526. Object.defineProperty(Engine, "LastCreatedEngine", {
  9527. get: function () {
  9528. if (Engine.Instances.length === 0) {
  9529. return null;
  9530. }
  9531. return Engine.Instances[Engine.Instances.length - 1];
  9532. },
  9533. enumerable: true,
  9534. configurable: true
  9535. });
  9536. Object.defineProperty(Engine, "LastCreatedScene", {
  9537. get: function () {
  9538. var lastCreatedEngine = Engine.LastCreatedEngine;
  9539. if (!lastCreatedEngine) {
  9540. return null;
  9541. }
  9542. if (lastCreatedEngine.scenes.length === 0) {
  9543. return null;
  9544. }
  9545. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  9546. },
  9547. enumerable: true,
  9548. configurable: true
  9549. });
  9550. /**
  9551. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  9552. */
  9553. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  9554. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  9555. var engine = Engine.Instances[engineIndex];
  9556. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  9557. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  9558. }
  9559. }
  9560. };
  9561. Object.defineProperty(Engine, "NEVER", {
  9562. get: function () {
  9563. return Engine._NEVER;
  9564. },
  9565. enumerable: true,
  9566. configurable: true
  9567. });
  9568. Object.defineProperty(Engine, "ALWAYS", {
  9569. get: function () {
  9570. return Engine._ALWAYS;
  9571. },
  9572. enumerable: true,
  9573. configurable: true
  9574. });
  9575. Object.defineProperty(Engine, "LESS", {
  9576. get: function () {
  9577. return Engine._LESS;
  9578. },
  9579. enumerable: true,
  9580. configurable: true
  9581. });
  9582. Object.defineProperty(Engine, "EQUAL", {
  9583. get: function () {
  9584. return Engine._EQUAL;
  9585. },
  9586. enumerable: true,
  9587. configurable: true
  9588. });
  9589. Object.defineProperty(Engine, "LEQUAL", {
  9590. get: function () {
  9591. return Engine._LEQUAL;
  9592. },
  9593. enumerable: true,
  9594. configurable: true
  9595. });
  9596. Object.defineProperty(Engine, "GREATER", {
  9597. get: function () {
  9598. return Engine._GREATER;
  9599. },
  9600. enumerable: true,
  9601. configurable: true
  9602. });
  9603. Object.defineProperty(Engine, "GEQUAL", {
  9604. get: function () {
  9605. return Engine._GEQUAL;
  9606. },
  9607. enumerable: true,
  9608. configurable: true
  9609. });
  9610. Object.defineProperty(Engine, "NOTEQUAL", {
  9611. get: function () {
  9612. return Engine._NOTEQUAL;
  9613. },
  9614. enumerable: true,
  9615. configurable: true
  9616. });
  9617. Object.defineProperty(Engine, "KEEP", {
  9618. get: function () {
  9619. return Engine._KEEP;
  9620. },
  9621. enumerable: true,
  9622. configurable: true
  9623. });
  9624. Object.defineProperty(Engine, "REPLACE", {
  9625. get: function () {
  9626. return Engine._REPLACE;
  9627. },
  9628. enumerable: true,
  9629. configurable: true
  9630. });
  9631. Object.defineProperty(Engine, "INCR", {
  9632. get: function () {
  9633. return Engine._INCR;
  9634. },
  9635. enumerable: true,
  9636. configurable: true
  9637. });
  9638. Object.defineProperty(Engine, "DECR", {
  9639. get: function () {
  9640. return Engine._DECR;
  9641. },
  9642. enumerable: true,
  9643. configurable: true
  9644. });
  9645. Object.defineProperty(Engine, "INVERT", {
  9646. get: function () {
  9647. return Engine._INVERT;
  9648. },
  9649. enumerable: true,
  9650. configurable: true
  9651. });
  9652. Object.defineProperty(Engine, "INCR_WRAP", {
  9653. get: function () {
  9654. return Engine._INCR_WRAP;
  9655. },
  9656. enumerable: true,
  9657. configurable: true
  9658. });
  9659. Object.defineProperty(Engine, "DECR_WRAP", {
  9660. get: function () {
  9661. return Engine._DECR_WRAP;
  9662. },
  9663. enumerable: true,
  9664. configurable: true
  9665. });
  9666. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  9667. get: function () {
  9668. return Engine._ALPHA_DISABLE;
  9669. },
  9670. enumerable: true,
  9671. configurable: true
  9672. });
  9673. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  9674. get: function () {
  9675. return Engine._ALPHA_ONEONE;
  9676. },
  9677. enumerable: true,
  9678. configurable: true
  9679. });
  9680. Object.defineProperty(Engine, "ALPHA_ADD", {
  9681. get: function () {
  9682. return Engine._ALPHA_ADD;
  9683. },
  9684. enumerable: true,
  9685. configurable: true
  9686. });
  9687. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  9688. get: function () {
  9689. return Engine._ALPHA_COMBINE;
  9690. },
  9691. enumerable: true,
  9692. configurable: true
  9693. });
  9694. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  9695. get: function () {
  9696. return Engine._ALPHA_SUBTRACT;
  9697. },
  9698. enumerable: true,
  9699. configurable: true
  9700. });
  9701. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  9702. get: function () {
  9703. return Engine._ALPHA_MULTIPLY;
  9704. },
  9705. enumerable: true,
  9706. configurable: true
  9707. });
  9708. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  9709. get: function () {
  9710. return Engine._ALPHA_MAXIMIZED;
  9711. },
  9712. enumerable: true,
  9713. configurable: true
  9714. });
  9715. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED", {
  9716. get: function () {
  9717. return Engine._ALPHA_PREMULTIPLIED;
  9718. },
  9719. enumerable: true,
  9720. configurable: true
  9721. });
  9722. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED_PORTERDUFF", {
  9723. get: function () {
  9724. return Engine._ALPHA_PREMULTIPLIED_PORTERDUFF;
  9725. },
  9726. enumerable: true,
  9727. configurable: true
  9728. });
  9729. Object.defineProperty(Engine, "ALPHA_INTERPOLATE", {
  9730. get: function () {
  9731. return Engine._ALPHA_INTERPOLATE;
  9732. },
  9733. enumerable: true,
  9734. configurable: true
  9735. });
  9736. Object.defineProperty(Engine, "ALPHA_SCREENMODE", {
  9737. get: function () {
  9738. return Engine._ALPHA_SCREENMODE;
  9739. },
  9740. enumerable: true,
  9741. configurable: true
  9742. });
  9743. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  9744. get: function () {
  9745. return Engine._DELAYLOADSTATE_NONE;
  9746. },
  9747. enumerable: true,
  9748. configurable: true
  9749. });
  9750. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  9751. get: function () {
  9752. return Engine._DELAYLOADSTATE_LOADED;
  9753. },
  9754. enumerable: true,
  9755. configurable: true
  9756. });
  9757. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  9758. get: function () {
  9759. return Engine._DELAYLOADSTATE_LOADING;
  9760. },
  9761. enumerable: true,
  9762. configurable: true
  9763. });
  9764. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  9765. get: function () {
  9766. return Engine._DELAYLOADSTATE_NOTLOADED;
  9767. },
  9768. enumerable: true,
  9769. configurable: true
  9770. });
  9771. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  9772. get: function () {
  9773. return Engine._TEXTUREFORMAT_ALPHA;
  9774. },
  9775. enumerable: true,
  9776. configurable: true
  9777. });
  9778. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  9779. get: function () {
  9780. return Engine._TEXTUREFORMAT_LUMINANCE;
  9781. },
  9782. enumerable: true,
  9783. configurable: true
  9784. });
  9785. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  9786. get: function () {
  9787. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  9788. },
  9789. enumerable: true,
  9790. configurable: true
  9791. });
  9792. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  9793. get: function () {
  9794. return Engine._TEXTUREFORMAT_RGB;
  9795. },
  9796. enumerable: true,
  9797. configurable: true
  9798. });
  9799. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  9800. get: function () {
  9801. return Engine._TEXTUREFORMAT_RGBA;
  9802. },
  9803. enumerable: true,
  9804. configurable: true
  9805. });
  9806. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  9807. get: function () {
  9808. return Engine._TEXTURETYPE_UNSIGNED_INT;
  9809. },
  9810. enumerable: true,
  9811. configurable: true
  9812. });
  9813. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  9814. get: function () {
  9815. return Engine._TEXTURETYPE_FLOAT;
  9816. },
  9817. enumerable: true,
  9818. configurable: true
  9819. });
  9820. Object.defineProperty(Engine, "TEXTURETYPE_HALF_FLOAT", {
  9821. get: function () {
  9822. return Engine._TEXTURETYPE_HALF_FLOAT;
  9823. },
  9824. enumerable: true,
  9825. configurable: true
  9826. });
  9827. Object.defineProperty(Engine, "SCALEMODE_FLOOR", {
  9828. get: function () {
  9829. return Engine._SCALEMODE_FLOOR;
  9830. },
  9831. enumerable: true,
  9832. configurable: true
  9833. });
  9834. Object.defineProperty(Engine, "SCALEMODE_NEAREST", {
  9835. get: function () {
  9836. return Engine._SCALEMODE_NEAREST;
  9837. },
  9838. enumerable: true,
  9839. configurable: true
  9840. });
  9841. Object.defineProperty(Engine, "SCALEMODE_CEILING", {
  9842. get: function () {
  9843. return Engine._SCALEMODE_CEILING;
  9844. },
  9845. enumerable: true,
  9846. configurable: true
  9847. });
  9848. Object.defineProperty(Engine, "Version", {
  9849. get: function () {
  9850. return "3.2.0-alpha6";
  9851. },
  9852. enumerable: true,
  9853. configurable: true
  9854. });
  9855. Object.defineProperty(Engine.prototype, "isInVRExclusivePointerMode", {
  9856. get: function () {
  9857. return this._vrExclusivePointerMode;
  9858. },
  9859. enumerable: true,
  9860. configurable: true
  9861. });
  9862. Object.defineProperty(Engine.prototype, "supportsUniformBuffers", {
  9863. get: function () {
  9864. return this.webGLVersion > 1 && !this.disableUniformBuffers;
  9865. },
  9866. enumerable: true,
  9867. configurable: true
  9868. });
  9869. Object.defineProperty(Engine.prototype, "needPOTTextures", {
  9870. get: function () {
  9871. return this._webGLVersion < 2 || this.forcePOTTextures;
  9872. },
  9873. enumerable: true,
  9874. configurable: true
  9875. });
  9876. Object.defineProperty(Engine.prototype, "badOS", {
  9877. get: function () {
  9878. return this._badOS;
  9879. },
  9880. enumerable: true,
  9881. configurable: true
  9882. });
  9883. Object.defineProperty(Engine.prototype, "badDesktopOS", {
  9884. get: function () {
  9885. return this._badDesktopOS;
  9886. },
  9887. enumerable: true,
  9888. configurable: true
  9889. });
  9890. Object.defineProperty(Engine.prototype, "performanceMonitor", {
  9891. get: function () {
  9892. return this._performanceMonitor;
  9893. },
  9894. enumerable: true,
  9895. configurable: true
  9896. });
  9897. Object.defineProperty(Engine.prototype, "texturesSupported", {
  9898. get: function () {
  9899. return this._texturesSupported;
  9900. },
  9901. enumerable: true,
  9902. configurable: true
  9903. });
  9904. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  9905. get: function () {
  9906. return this._textureFormatInUse;
  9907. },
  9908. enumerable: true,
  9909. configurable: true
  9910. });
  9911. Object.defineProperty(Engine.prototype, "currentViewport", {
  9912. get: function () {
  9913. return this._cachedViewport;
  9914. },
  9915. enumerable: true,
  9916. configurable: true
  9917. });
  9918. Object.defineProperty(Engine.prototype, "emptyTexture", {
  9919. // Empty texture
  9920. get: function () {
  9921. if (!this._emptyTexture) {
  9922. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  9923. }
  9924. return this._emptyTexture;
  9925. },
  9926. enumerable: true,
  9927. configurable: true
  9928. });
  9929. Object.defineProperty(Engine.prototype, "emptyTexture3D", {
  9930. get: function () {
  9931. if (!this._emptyTexture3D) {
  9932. this._emptyTexture3D = this.createRawTexture3D(new Uint8Array(4), 1, 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  9933. }
  9934. return this._emptyTexture3D;
  9935. },
  9936. enumerable: true,
  9937. configurable: true
  9938. });
  9939. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  9940. get: function () {
  9941. if (!this._emptyCubeTexture) {
  9942. var faceData = new Uint8Array(4);
  9943. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  9944. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, Engine.TEXTUREFORMAT_RGBA, Engine.TEXTURETYPE_UNSIGNED_INT, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  9945. }
  9946. return this._emptyCubeTexture;
  9947. },
  9948. enumerable: true,
  9949. configurable: true
  9950. });
  9951. Engine.prototype._rebuildInternalTextures = function () {
  9952. var currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
  9953. for (var _i = 0, currentState_1 = currentState; _i < currentState_1.length; _i++) {
  9954. var internalTexture = currentState_1[_i];
  9955. internalTexture._rebuild();
  9956. }
  9957. };
  9958. Engine.prototype._rebuildEffects = function () {
  9959. for (var key in this._compiledEffects) {
  9960. var effect = this._compiledEffects[key];
  9961. effect._prepareEffect();
  9962. }
  9963. BABYLON.Effect.ResetCache();
  9964. };
  9965. Engine.prototype._rebuildBuffers = function () {
  9966. // Index / Vertex
  9967. for (var _i = 0, _a = this.scenes; _i < _a.length; _i++) {
  9968. var scene = _a[_i];
  9969. scene.resetCachedMaterial();
  9970. scene._rebuildGeometries();
  9971. scene._rebuildTextures();
  9972. }
  9973. // Uniforms
  9974. for (var _b = 0, _c = this._uniformBuffers; _b < _c.length; _b++) {
  9975. var uniformBuffer = _c[_b];
  9976. uniformBuffer._rebuild();
  9977. }
  9978. };
  9979. Engine.prototype._initGLContext = function () {
  9980. // Caps
  9981. this._caps = new EngineCapabilities();
  9982. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  9983. this._caps.maxCombinedTexturesImageUnits = this._gl.getParameter(this._gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS);
  9984. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  9985. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  9986. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  9987. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  9988. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  9989. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  9990. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  9991. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  9992. // Infos
  9993. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  9994. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  9995. if (rendererInfo != null) {
  9996. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  9997. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  9998. }
  9999. if (!this._glVendor) {
  10000. this._glVendor = "Unknown vendor";
  10001. }
  10002. if (!this._glRenderer) {
  10003. this._glRenderer = "Unknown renderer";
  10004. }
  10005. // Constants
  10006. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  10007. if (this._gl.RGBA16F !== 0x881A) {
  10008. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  10009. }
  10010. if (this._gl.RGBA32F !== 0x8814) {
  10011. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  10012. }
  10013. if (this._gl.DEPTH24_STENCIL8 !== 35056) {
  10014. this._gl.DEPTH24_STENCIL8 = 35056;
  10015. }
  10016. // Extensions
  10017. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  10018. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  10019. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  10020. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  10021. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  10022. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  10023. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  10024. 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');
  10025. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  10026. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  10027. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  10028. this._caps.highPrecisionShaderSupported = true;
  10029. this._caps.timerQuery = this._gl.getExtension('EXT_disjoint_timer_query_webgl2') || this._gl.getExtension("EXT_disjoint_timer_query");
  10030. if (this._caps.timerQuery) {
  10031. if (this._webGLVersion === 1) {
  10032. this._gl.getQuery = this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery);
  10033. }
  10034. this._caps.canUseTimestampForTimerQuery = this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT, this._caps.timerQuery.QUERY_COUNTER_BITS_EXT) > 0;
  10035. }
  10036. // Checks if some of the format renders first to allow the use of webgl inspector.
  10037. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  10038. this._caps.textureFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float');
  10039. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear');
  10040. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer();
  10041. this._caps.textureHalfFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float');
  10042. this._caps.textureHalfFloatLinearFiltering = this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'));
  10043. if (this._webGLVersion > 1) {
  10044. this._gl.HALF_FLOAT_OES = 0x140B;
  10045. }
  10046. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  10047. this._caps.textureLOD = this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod');
  10048. // Draw buffers
  10049. if (this._webGLVersion > 1) {
  10050. this._caps.drawBuffersExtension = true;
  10051. }
  10052. else {
  10053. var drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  10054. if (drawBuffersExtension !== null) {
  10055. this._caps.drawBuffersExtension = true;
  10056. this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension);
  10057. this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;
  10058. for (var i = 0; i < 16; i++) {
  10059. this._gl["COLOR_ATTACHMENT" + i + "_WEBGL"] = drawBuffersExtension["COLOR_ATTACHMENT" + i + "_WEBGL"];
  10060. }
  10061. }
  10062. else {
  10063. this._caps.drawBuffersExtension = false;
  10064. }
  10065. }
  10066. // Depth Texture
  10067. if (this._webGLVersion > 1) {
  10068. this._caps.depthTextureExtension = true;
  10069. }
  10070. else {
  10071. var depthTextureExtension = this._gl.getExtension('WEBGL_depth_texture');
  10072. if (depthTextureExtension != null) {
  10073. this._caps.depthTextureExtension = true;
  10074. }
  10075. }
  10076. // Vertex array object
  10077. if (this._webGLVersion > 1) {
  10078. this._caps.vertexArrayObject = true;
  10079. }
  10080. else {
  10081. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  10082. if (vertexArrayObjectExtension != null) {
  10083. this._caps.vertexArrayObject = true;
  10084. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  10085. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  10086. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  10087. }
  10088. else {
  10089. this._caps.vertexArrayObject = false;
  10090. }
  10091. }
  10092. // Instances count
  10093. if (this._webGLVersion > 1) {
  10094. this._caps.instancedArrays = true;
  10095. }
  10096. else {
  10097. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  10098. if (instanceExtension != null) {
  10099. this._caps.instancedArrays = true;
  10100. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  10101. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  10102. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  10103. }
  10104. else {
  10105. this._caps.instancedArrays = false;
  10106. }
  10107. }
  10108. // Intelligently add supported compressed formats in order to check for.
  10109. // Check for ASTC support first as it is most powerful and to be very cross platform.
  10110. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  10111. // Likely no hardware which supports both PVR & DXT, so order matters little.
  10112. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  10113. if (this._caps.astc)
  10114. this.texturesSupported.push('-astc.ktx');
  10115. if (this._caps.s3tc)
  10116. this.texturesSupported.push('-dxt.ktx');
  10117. if (this._caps.pvrtc)
  10118. this.texturesSupported.push('-pvrtc.ktx');
  10119. if (this._caps.etc2)
  10120. this.texturesSupported.push('-etc2.ktx');
  10121. if (this._caps.etc1)
  10122. this.texturesSupported.push('-etc1.ktx');
  10123. if (this._gl.getShaderPrecisionFormat) {
  10124. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  10125. if (highp) {
  10126. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  10127. }
  10128. }
  10129. // Depth buffer
  10130. this.setDepthBuffer(true);
  10131. this.setDepthFunctionToLessOrEqual();
  10132. this.setDepthWrite(true);
  10133. // Texture maps
  10134. this._maxSimultaneousTextures = this._caps.maxCombinedTexturesImageUnits;
  10135. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  10136. this._nextFreeTextureSlots.push(slot);
  10137. }
  10138. };
  10139. Object.defineProperty(Engine.prototype, "webGLVersion", {
  10140. get: function () {
  10141. return this._webGLVersion;
  10142. },
  10143. enumerable: true,
  10144. configurable: true
  10145. });
  10146. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  10147. /**
  10148. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  10149. */
  10150. get: function () {
  10151. return this._isStencilEnable;
  10152. },
  10153. enumerable: true,
  10154. configurable: true
  10155. });
  10156. Engine.prototype._prepareWorkingCanvas = function () {
  10157. if (this._workingCanvas) {
  10158. return;
  10159. }
  10160. this._workingCanvas = document.createElement("canvas");
  10161. var context = this._workingCanvas.getContext("2d");
  10162. if (context) {
  10163. this._workingContext = context;
  10164. }
  10165. };
  10166. Engine.prototype.resetTextureCache = function () {
  10167. for (var key in this._boundTexturesCache) {
  10168. var boundTexture = this._boundTexturesCache[key];
  10169. if (boundTexture) {
  10170. this._removeDesignatedSlot(boundTexture);
  10171. }
  10172. this._boundTexturesCache[key] = null;
  10173. }
  10174. this._nextFreeTextureSlots = [];
  10175. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  10176. this._nextFreeTextureSlots.push(slot);
  10177. }
  10178. this._currentTextureChannel = -1;
  10179. };
  10180. Engine.prototype.isDeterministicLockStep = function () {
  10181. return this._deterministicLockstep;
  10182. };
  10183. Engine.prototype.getLockstepMaxSteps = function () {
  10184. return this._lockstepMaxSteps;
  10185. };
  10186. Engine.prototype.getGlInfo = function () {
  10187. return {
  10188. vendor: this._glVendor,
  10189. renderer: this._glRenderer,
  10190. version: this._glVersion
  10191. };
  10192. };
  10193. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  10194. if (useScreen === void 0) { useScreen = false; }
  10195. var viewport = camera.viewport;
  10196. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  10197. };
  10198. Engine.prototype.getRenderWidth = function (useScreen) {
  10199. if (useScreen === void 0) { useScreen = false; }
  10200. if (!useScreen && this._currentRenderTarget) {
  10201. return this._currentRenderTarget.width;
  10202. }
  10203. return this._gl.drawingBufferWidth;
  10204. };
  10205. Engine.prototype.getRenderHeight = function (useScreen) {
  10206. if (useScreen === void 0) { useScreen = false; }
  10207. if (!useScreen && this._currentRenderTarget) {
  10208. return this._currentRenderTarget.height;
  10209. }
  10210. return this._gl.drawingBufferHeight;
  10211. };
  10212. Engine.prototype.getRenderingCanvas = function () {
  10213. return this._renderingCanvas;
  10214. };
  10215. Engine.prototype.getRenderingCanvasClientRect = function () {
  10216. if (!this._renderingCanvas) {
  10217. return null;
  10218. }
  10219. return this._renderingCanvas.getBoundingClientRect();
  10220. };
  10221. Engine.prototype.setHardwareScalingLevel = function (level) {
  10222. this._hardwareScalingLevel = level;
  10223. this.resize();
  10224. };
  10225. Engine.prototype.getHardwareScalingLevel = function () {
  10226. return this._hardwareScalingLevel;
  10227. };
  10228. Engine.prototype.getLoadedTexturesCache = function () {
  10229. return this._internalTexturesCache;
  10230. };
  10231. Engine.prototype.getCaps = function () {
  10232. return this._caps;
  10233. };
  10234. Object.defineProperty(Engine.prototype, "drawCalls", {
  10235. /** The number of draw calls submitted last frame */
  10236. get: function () {
  10237. BABYLON.Tools.Warn("drawCalls is deprecated. Please use SceneInstrumentation class");
  10238. return 0;
  10239. },
  10240. enumerable: true,
  10241. configurable: true
  10242. });
  10243. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  10244. get: function () {
  10245. BABYLON.Tools.Warn("drawCallsPerfCounter is deprecated. Please use SceneInstrumentation class");
  10246. return null;
  10247. },
  10248. enumerable: true,
  10249. configurable: true
  10250. });
  10251. Engine.prototype.getDepthFunction = function () {
  10252. return this._depthCullingState.depthFunc;
  10253. };
  10254. Engine.prototype.setDepthFunction = function (depthFunc) {
  10255. this._depthCullingState.depthFunc = depthFunc;
  10256. };
  10257. Engine.prototype.setDepthFunctionToGreater = function () {
  10258. this._depthCullingState.depthFunc = this._gl.GREATER;
  10259. };
  10260. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  10261. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  10262. };
  10263. Engine.prototype.setDepthFunctionToLess = function () {
  10264. this._depthCullingState.depthFunc = this._gl.LESS;
  10265. };
  10266. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  10267. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  10268. };
  10269. Engine.prototype.getStencilBuffer = function () {
  10270. return this._stencilState.stencilTest;
  10271. };
  10272. Engine.prototype.setStencilBuffer = function (enable) {
  10273. this._stencilState.stencilTest = enable;
  10274. };
  10275. Engine.prototype.getStencilMask = function () {
  10276. return this._stencilState.stencilMask;
  10277. };
  10278. Engine.prototype.setStencilMask = function (mask) {
  10279. this._stencilState.stencilMask = mask;
  10280. };
  10281. Engine.prototype.getStencilFunction = function () {
  10282. return this._stencilState.stencilFunc;
  10283. };
  10284. Engine.prototype.getStencilFunctionReference = function () {
  10285. return this._stencilState.stencilFuncRef;
  10286. };
  10287. Engine.prototype.getStencilFunctionMask = function () {
  10288. return this._stencilState.stencilFuncMask;
  10289. };
  10290. Engine.prototype.setStencilFunction = function (stencilFunc) {
  10291. this._stencilState.stencilFunc = stencilFunc;
  10292. };
  10293. Engine.prototype.setStencilFunctionReference = function (reference) {
  10294. this._stencilState.stencilFuncRef = reference;
  10295. };
  10296. Engine.prototype.setStencilFunctionMask = function (mask) {
  10297. this._stencilState.stencilFuncMask = mask;
  10298. };
  10299. Engine.prototype.getStencilOperationFail = function () {
  10300. return this._stencilState.stencilOpStencilFail;
  10301. };
  10302. Engine.prototype.getStencilOperationDepthFail = function () {
  10303. return this._stencilState.stencilOpDepthFail;
  10304. };
  10305. Engine.prototype.getStencilOperationPass = function () {
  10306. return this._stencilState.stencilOpStencilDepthPass;
  10307. };
  10308. Engine.prototype.setStencilOperationFail = function (operation) {
  10309. this._stencilState.stencilOpStencilFail = operation;
  10310. };
  10311. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  10312. this._stencilState.stencilOpDepthFail = operation;
  10313. };
  10314. Engine.prototype.setStencilOperationPass = function (operation) {
  10315. this._stencilState.stencilOpStencilDepthPass = operation;
  10316. };
  10317. Engine.prototype.setDitheringState = function (value) {
  10318. if (value) {
  10319. this._gl.enable(this._gl.DITHER);
  10320. }
  10321. else {
  10322. this._gl.disable(this._gl.DITHER);
  10323. }
  10324. };
  10325. Engine.prototype.setRasterizerState = function (value) {
  10326. if (value) {
  10327. this._gl.disable(this._gl.RASTERIZER_DISCARD);
  10328. }
  10329. else {
  10330. this._gl.enable(this._gl.RASTERIZER_DISCARD);
  10331. }
  10332. };
  10333. /**
  10334. * stop executing a render loop function and remove it from the execution array
  10335. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  10336. */
  10337. Engine.prototype.stopRenderLoop = function (renderFunction) {
  10338. if (!renderFunction) {
  10339. this._activeRenderLoops = [];
  10340. return;
  10341. }
  10342. var index = this._activeRenderLoops.indexOf(renderFunction);
  10343. if (index >= 0) {
  10344. this._activeRenderLoops.splice(index, 1);
  10345. }
  10346. };
  10347. Engine.prototype._renderLoop = function () {
  10348. if (!this._contextWasLost) {
  10349. var shouldRender = true;
  10350. if (!this.renderEvenInBackground && this._windowIsBackground) {
  10351. shouldRender = false;
  10352. }
  10353. if (shouldRender) {
  10354. // Start new frame
  10355. this.beginFrame();
  10356. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  10357. var renderFunction = this._activeRenderLoops[index];
  10358. renderFunction();
  10359. }
  10360. // Present
  10361. this.endFrame();
  10362. }
  10363. }
  10364. if (this._activeRenderLoops.length > 0) {
  10365. // Register new frame
  10366. var requester = null;
  10367. if (this._vrDisplay && this._vrDisplay.isPresenting)
  10368. requester = this._vrDisplay;
  10369. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, requester);
  10370. }
  10371. else {
  10372. this._renderingQueueLaunched = false;
  10373. }
  10374. };
  10375. /**
  10376. * Register and execute a render loop. The engine can have more than one render function.
  10377. * @param {Function} renderFunction - the function to continuously execute starting the next render loop.
  10378. * @example
  10379. * engine.runRenderLoop(function () {
  10380. * scene.render()
  10381. * })
  10382. */
  10383. Engine.prototype.runRenderLoop = function (renderFunction) {
  10384. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  10385. return;
  10386. }
  10387. this._activeRenderLoops.push(renderFunction);
  10388. if (!this._renderingQueueLaunched) {
  10389. this._renderingQueueLaunched = true;
  10390. this._bindedRenderFunction = this._renderLoop.bind(this);
  10391. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  10392. }
  10393. };
  10394. /**
  10395. * Toggle full screen mode.
  10396. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  10397. * @param {any} options - an options object to be sent to the requestFullscreen function
  10398. */
  10399. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  10400. if (this.isFullscreen) {
  10401. BABYLON.Tools.ExitFullscreen();
  10402. }
  10403. else {
  10404. this._pointerLockRequested = requestPointerLock;
  10405. if (this._renderingCanvas) {
  10406. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  10407. }
  10408. }
  10409. };
  10410. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  10411. if (stencil === void 0) { stencil = false; }
  10412. this.applyStates();
  10413. var mode = 0;
  10414. if (backBuffer && color) {
  10415. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  10416. mode |= this._gl.COLOR_BUFFER_BIT;
  10417. }
  10418. if (depth) {
  10419. this._gl.clearDepth(1.0);
  10420. mode |= this._gl.DEPTH_BUFFER_BIT;
  10421. }
  10422. if (stencil) {
  10423. this._gl.clearStencil(0);
  10424. mode |= this._gl.STENCIL_BUFFER_BIT;
  10425. }
  10426. this._gl.clear(mode);
  10427. };
  10428. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  10429. var gl = this._gl;
  10430. // Save state
  10431. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  10432. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  10433. // Change state
  10434. gl.enable(gl.SCISSOR_TEST);
  10435. gl.scissor(x, y, width, height);
  10436. // Clear
  10437. this.clear(clearColor, true, true, true);
  10438. // Restore state
  10439. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  10440. if (curScissor === true) {
  10441. gl.enable(gl.SCISSOR_TEST);
  10442. }
  10443. else {
  10444. gl.disable(gl.SCISSOR_TEST);
  10445. }
  10446. };
  10447. /**
  10448. * Set the WebGL's viewport
  10449. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  10450. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  10451. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  10452. */
  10453. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  10454. var width = requiredWidth || this.getRenderWidth();
  10455. var height = requiredHeight || this.getRenderHeight();
  10456. var x = viewport.x || 0;
  10457. var y = viewport.y || 0;
  10458. this._cachedViewport = viewport;
  10459. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  10460. };
  10461. /**
  10462. * Directly set the WebGL Viewport
  10463. * The x, y, width & height are directly passed to the WebGL call
  10464. * @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.
  10465. */
  10466. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  10467. var currentViewport = this._cachedViewport;
  10468. this._cachedViewport = null;
  10469. this._gl.viewport(x, y, width, height);
  10470. return currentViewport;
  10471. };
  10472. Engine.prototype.beginFrame = function () {
  10473. this.onBeginFrameObservable.notifyObservers(this);
  10474. this._measureFps();
  10475. };
  10476. Engine.prototype.endFrame = function () {
  10477. //force a flush in case we are using a bad OS.
  10478. if (this._badOS) {
  10479. this.flushFramebuffer();
  10480. }
  10481. //submit frame to the vr device, if enabled
  10482. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  10483. // TODO: We should only submit the frame if we read frameData successfully.
  10484. this._vrDisplay.submitFrame();
  10485. }
  10486. this.onEndFrameObservable.notifyObservers(this);
  10487. };
  10488. /**
  10489. * resize the view according to the canvas' size.
  10490. * @example
  10491. * window.addEventListener("resize", function () {
  10492. * engine.resize();
  10493. * });
  10494. */
  10495. Engine.prototype.resize = function () {
  10496. // We're not resizing the size of the canvas while in VR mode & presenting
  10497. if (!(this._vrDisplay && this._vrDisplay.isPresenting)) {
  10498. var width = this._renderingCanvas ? this._renderingCanvas.clientWidth : window.innerWidth;
  10499. var height = this._renderingCanvas ? this._renderingCanvas.clientHeight : window.innerHeight;
  10500. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  10501. }
  10502. };
  10503. /**
  10504. * force a specific size of the canvas
  10505. * @param {number} width - the new canvas' width
  10506. * @param {number} height - the new canvas' height
  10507. */
  10508. Engine.prototype.setSize = function (width, height) {
  10509. if (!this._renderingCanvas) {
  10510. return;
  10511. }
  10512. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  10513. return;
  10514. }
  10515. this._renderingCanvas.width = width;
  10516. this._renderingCanvas.height = height;
  10517. for (var index = 0; index < this.scenes.length; index++) {
  10518. var scene = this.scenes[index];
  10519. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  10520. var cam = scene.cameras[camIndex];
  10521. cam._currentRenderId = 0;
  10522. }
  10523. }
  10524. if (this.onResizeObservable.hasObservers) {
  10525. this.onResizeObservable.notifyObservers(this);
  10526. }
  10527. };
  10528. // WebVR functions
  10529. Engine.prototype.isVRDevicePresent = function () {
  10530. return !!this._vrDisplay;
  10531. };
  10532. Engine.prototype.getVRDevice = function () {
  10533. return this._vrDisplay;
  10534. };
  10535. Engine.prototype.initWebVR = function () {
  10536. var _this = this;
  10537. var notifyObservers = function () {
  10538. var eventArgs = {
  10539. vrDisplay: _this._vrDisplay,
  10540. vrSupported: _this._vrSupported
  10541. };
  10542. _this.onVRDisplayChangedObservable.notifyObservers(eventArgs);
  10543. };
  10544. if (!this._onVrDisplayConnect) {
  10545. this._onVrDisplayConnect = function (event) {
  10546. _this._vrDisplay = event.display;
  10547. notifyObservers();
  10548. };
  10549. this._onVrDisplayDisconnect = function () {
  10550. _this._vrDisplay.cancelAnimationFrame(_this._frameHandler);
  10551. _this._vrDisplay = undefined;
  10552. _this._frameHandler = BABYLON.Tools.QueueNewFrame(_this._bindedRenderFunction);
  10553. notifyObservers();
  10554. };
  10555. this._onVrDisplayPresentChange = function () {
  10556. _this._vrExclusivePointerMode = _this._vrDisplay && _this._vrDisplay.isPresenting;
  10557. };
  10558. window.addEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  10559. window.addEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  10560. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  10561. }
  10562. this._getVRDisplays(notifyObservers);
  10563. return this.onVRDisplayChangedObservable;
  10564. };
  10565. Engine.prototype.enableVR = function () {
  10566. var _this = this;
  10567. if (this._vrDisplay && !this._vrDisplay.isPresenting) {
  10568. var onResolved = function () {
  10569. _this.onVRRequestPresentComplete.notifyObservers(true);
  10570. _this._onVRFullScreenTriggered();
  10571. };
  10572. var onRejected = function () {
  10573. _this.onVRRequestPresentComplete.notifyObservers(false);
  10574. };
  10575. this.onVRRequestPresentStart.notifyObservers(this);
  10576. this._vrDisplay.requestPresent([{ source: this.getRenderingCanvas() }]).then(onResolved).catch(onRejected);
  10577. }
  10578. };
  10579. Engine.prototype.disableVR = function () {
  10580. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  10581. this._vrDisplay.exitPresent().then(this._onVRFullScreenTriggered).catch(this._onVRFullScreenTriggered);
  10582. }
  10583. };
  10584. Engine.prototype._getVRDisplays = function (callback) {
  10585. var _this = this;
  10586. var getWebVRDevices = function (devices) {
  10587. _this._vrSupported = true;
  10588. // note that devices may actually be an empty array. This is fine;
  10589. // we expect this._vrDisplay to be undefined in this case.
  10590. return _this._vrDisplay = devices[0];
  10591. };
  10592. if (navigator.getVRDisplays) {
  10593. navigator.getVRDisplays().then(getWebVRDevices).then(callback).catch(function (error) {
  10594. // TODO: System CANNOT support WebVR, despite API presence.
  10595. _this._vrSupported = false;
  10596. callback();
  10597. });
  10598. }
  10599. else {
  10600. // TODO: Browser does not support WebVR
  10601. this._vrDisplay = undefined;
  10602. this._vrSupported = false;
  10603. callback();
  10604. }
  10605. };
  10606. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
  10607. if (this._currentRenderTarget) {
  10608. this.unBindFramebuffer(this._currentRenderTarget);
  10609. }
  10610. this._currentRenderTarget = texture;
  10611. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  10612. var gl = this._gl;
  10613. if (texture.isCube) {
  10614. if (faceIndex === undefined) {
  10615. faceIndex = 0;
  10616. }
  10617. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  10618. }
  10619. if (this._cachedViewport && !forceFullscreenViewport) {
  10620. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  10621. }
  10622. else {
  10623. gl.viewport(0, 0, requiredWidth || texture.width, requiredHeight || texture.height);
  10624. }
  10625. this.wipeCaches();
  10626. };
  10627. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  10628. if (this._currentFramebuffer !== framebuffer) {
  10629. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  10630. this._currentFramebuffer = framebuffer;
  10631. }
  10632. };
  10633. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  10634. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  10635. this._currentRenderTarget = null;
  10636. // If MSAA, we need to bitblt back to main texture
  10637. var gl = this._gl;
  10638. if (texture._MSAAFramebuffer) {
  10639. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  10640. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  10641. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  10642. }
  10643. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  10644. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  10645. gl.generateMipmap(gl.TEXTURE_2D);
  10646. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  10647. }
  10648. if (onBeforeUnbind) {
  10649. if (texture._MSAAFramebuffer) {
  10650. // Bind the correct framebuffer
  10651. this.bindUnboundFramebuffer(texture._framebuffer);
  10652. }
  10653. onBeforeUnbind();
  10654. }
  10655. this.bindUnboundFramebuffer(null);
  10656. };
  10657. Engine.prototype.unBindMultiColorAttachmentFramebuffer = function (textures, disableGenerateMipMaps, onBeforeUnbind) {
  10658. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  10659. this._currentRenderTarget = null;
  10660. // If MSAA, we need to bitblt back to main texture
  10661. var gl = this._gl;
  10662. if (textures[0]._MSAAFramebuffer) {
  10663. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, textures[0]._MSAAFramebuffer);
  10664. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, textures[0]._framebuffer);
  10665. var attachments = textures[0]._attachments;
  10666. if (!attachments) {
  10667. attachments = new Array(textures.length);
  10668. textures[0]._attachments = attachments;
  10669. }
  10670. for (var i = 0; i < textures.length; i++) {
  10671. var texture = textures[i];
  10672. for (var j = 0; j < attachments.length; j++) {
  10673. attachments[j] = gl.NONE;
  10674. }
  10675. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  10676. gl.readBuffer(attachments[i]);
  10677. gl.drawBuffers(attachments);
  10678. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  10679. }
  10680. for (var i = 0; i < attachments.length; i++) {
  10681. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  10682. }
  10683. gl.drawBuffers(attachments);
  10684. }
  10685. for (var i = 0; i < textures.length; i++) {
  10686. var texture = textures[i];
  10687. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  10688. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  10689. gl.generateMipmap(gl.TEXTURE_2D);
  10690. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  10691. }
  10692. }
  10693. if (onBeforeUnbind) {
  10694. if (textures[0]._MSAAFramebuffer) {
  10695. // Bind the correct framebuffer
  10696. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  10697. }
  10698. onBeforeUnbind();
  10699. }
  10700. this.bindUnboundFramebuffer(null);
  10701. };
  10702. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  10703. if (texture.generateMipMaps) {
  10704. var gl = this._gl;
  10705. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  10706. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  10707. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10708. }
  10709. };
  10710. Engine.prototype.flushFramebuffer = function () {
  10711. this._gl.flush();
  10712. };
  10713. Engine.prototype.restoreDefaultFramebuffer = function () {
  10714. if (this._currentRenderTarget) {
  10715. this.unBindFramebuffer(this._currentRenderTarget);
  10716. }
  10717. else {
  10718. this.bindUnboundFramebuffer(null);
  10719. }
  10720. if (this._cachedViewport) {
  10721. this.setViewport(this._cachedViewport);
  10722. }
  10723. this.wipeCaches();
  10724. };
  10725. // UBOs
  10726. Engine.prototype.createUniformBuffer = function (elements) {
  10727. var ubo = this._gl.createBuffer();
  10728. if (!ubo) {
  10729. throw new Error("Unable to create uniform buffer");
  10730. }
  10731. this.bindUniformBuffer(ubo);
  10732. if (elements instanceof Float32Array) {
  10733. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  10734. }
  10735. else {
  10736. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  10737. }
  10738. this.bindUniformBuffer(null);
  10739. ubo.references = 1;
  10740. return ubo;
  10741. };
  10742. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  10743. var ubo = this._gl.createBuffer();
  10744. if (!ubo) {
  10745. throw new Error("Unable to create dynamic uniform buffer");
  10746. }
  10747. this.bindUniformBuffer(ubo);
  10748. if (elements instanceof Float32Array) {
  10749. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  10750. }
  10751. else {
  10752. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  10753. }
  10754. this.bindUniformBuffer(null);
  10755. ubo.references = 1;
  10756. return ubo;
  10757. };
  10758. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  10759. this.bindUniformBuffer(uniformBuffer);
  10760. if (offset === undefined) {
  10761. offset = 0;
  10762. }
  10763. if (count === undefined) {
  10764. if (elements instanceof Float32Array) {
  10765. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  10766. }
  10767. else {
  10768. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  10769. }
  10770. }
  10771. else {
  10772. if (elements instanceof Float32Array) {
  10773. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  10774. }
  10775. else {
  10776. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  10777. }
  10778. }
  10779. this.bindUniformBuffer(null);
  10780. };
  10781. // VBOs
  10782. Engine.prototype._resetVertexBufferBinding = function () {
  10783. this.bindArrayBuffer(null);
  10784. this._cachedVertexBuffers = null;
  10785. };
  10786. Engine.prototype.createVertexBuffer = function (vertices) {
  10787. var vbo = this._gl.createBuffer();
  10788. if (!vbo) {
  10789. throw new Error("Unable to create vertex buffer");
  10790. }
  10791. this.bindArrayBuffer(vbo);
  10792. if (vertices instanceof Float32Array) {
  10793. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.STATIC_DRAW);
  10794. }
  10795. else {
  10796. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  10797. }
  10798. this._resetVertexBufferBinding();
  10799. vbo.references = 1;
  10800. return vbo;
  10801. };
  10802. Engine.prototype.createDynamicVertexBuffer = function (vertices) {
  10803. var vbo = this._gl.createBuffer();
  10804. if (!vbo) {
  10805. throw new Error("Unable to create dynamic vertex buffer");
  10806. }
  10807. this.bindArrayBuffer(vbo);
  10808. if (vertices instanceof Float32Array) {
  10809. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.DYNAMIC_DRAW);
  10810. }
  10811. else {
  10812. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.DYNAMIC_DRAW);
  10813. }
  10814. this._resetVertexBufferBinding();
  10815. vbo.references = 1;
  10816. return vbo;
  10817. };
  10818. Engine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  10819. if (offset === void 0) { offset = 0; }
  10820. // Force cache update
  10821. this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER] = null;
  10822. this.bindIndexBuffer(indexBuffer);
  10823. var arrayBuffer;
  10824. if (indices instanceof Uint16Array || indices instanceof Uint32Array) {
  10825. arrayBuffer = indices;
  10826. }
  10827. else {
  10828. arrayBuffer = indexBuffer.is32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  10829. }
  10830. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.DYNAMIC_DRAW);
  10831. this._resetIndexBufferBinding();
  10832. };
  10833. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset, count) {
  10834. this.bindArrayBuffer(vertexBuffer);
  10835. if (offset === undefined) {
  10836. offset = 0;
  10837. }
  10838. if (count === undefined) {
  10839. if (vertices instanceof Float32Array) {
  10840. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  10841. }
  10842. else {
  10843. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  10844. }
  10845. }
  10846. else {
  10847. if (vertices instanceof Float32Array) {
  10848. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, vertices.subarray(offset, offset + count));
  10849. }
  10850. else {
  10851. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(vertices).subarray(offset, offset + count));
  10852. }
  10853. }
  10854. this._resetVertexBufferBinding();
  10855. };
  10856. Engine.prototype._resetIndexBufferBinding = function () {
  10857. this.bindIndexBuffer(null);
  10858. this._cachedIndexBuffer = null;
  10859. };
  10860. Engine.prototype.createIndexBuffer = function (indices, updatable) {
  10861. var vbo = this._gl.createBuffer();
  10862. if (!vbo) {
  10863. throw new Error("Unable to create index buffer");
  10864. }
  10865. this.bindIndexBuffer(vbo);
  10866. // Check for 32 bits indices
  10867. var arrayBuffer;
  10868. var need32Bits = false;
  10869. if (indices instanceof Uint16Array) {
  10870. arrayBuffer = indices;
  10871. }
  10872. else {
  10873. //check 32 bit support
  10874. if (this._caps.uintIndices) {
  10875. if (indices instanceof Uint32Array) {
  10876. arrayBuffer = indices;
  10877. need32Bits = true;
  10878. }
  10879. else {
  10880. //number[] or Int32Array, check if 32 bit is necessary
  10881. for (var index = 0; index < indices.length; index++) {
  10882. if (indices[index] > 65535) {
  10883. need32Bits = true;
  10884. break;
  10885. }
  10886. }
  10887. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  10888. }
  10889. }
  10890. else {
  10891. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  10892. arrayBuffer = new Uint16Array(indices);
  10893. }
  10894. }
  10895. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, updatable ? this._gl.DYNAMIC_DRAW : this._gl.STATIC_DRAW);
  10896. this._resetIndexBufferBinding();
  10897. vbo.references = 1;
  10898. vbo.is32Bits = need32Bits;
  10899. return vbo;
  10900. };
  10901. Engine.prototype.bindArrayBuffer = function (buffer) {
  10902. if (!this._vaoRecordInProgress) {
  10903. this._unbindVertexArrayObject();
  10904. }
  10905. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  10906. };
  10907. Engine.prototype.bindUniformBuffer = function (buffer) {
  10908. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  10909. };
  10910. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  10911. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  10912. };
  10913. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  10914. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  10915. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  10916. };
  10917. ;
  10918. Engine.prototype.bindIndexBuffer = function (buffer) {
  10919. if (!this._vaoRecordInProgress) {
  10920. this._unbindVertexArrayObject();
  10921. }
  10922. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  10923. };
  10924. Engine.prototype.bindBuffer = function (buffer, target) {
  10925. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  10926. this._gl.bindBuffer(target, buffer);
  10927. this._currentBoundBuffer[target] = buffer;
  10928. }
  10929. };
  10930. Engine.prototype.updateArrayBuffer = function (data) {
  10931. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  10932. };
  10933. Engine.prototype.vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  10934. var pointer = this._currentBufferPointers[indx];
  10935. var changed = false;
  10936. if (!pointer.active) {
  10937. changed = true;
  10938. pointer.active = true;
  10939. pointer.index = indx;
  10940. pointer.size = size;
  10941. pointer.type = type;
  10942. pointer.normalized = normalized;
  10943. pointer.stride = stride;
  10944. pointer.offset = offset;
  10945. pointer.buffer = buffer;
  10946. }
  10947. else {
  10948. if (pointer.buffer !== buffer) {
  10949. pointer.buffer = buffer;
  10950. changed = true;
  10951. }
  10952. if (pointer.size !== size) {
  10953. pointer.size = size;
  10954. changed = true;
  10955. }
  10956. if (pointer.type !== type) {
  10957. pointer.type = type;
  10958. changed = true;
  10959. }
  10960. if (pointer.normalized !== normalized) {
  10961. pointer.normalized = normalized;
  10962. changed = true;
  10963. }
  10964. if (pointer.stride !== stride) {
  10965. pointer.stride = stride;
  10966. changed = true;
  10967. }
  10968. if (pointer.offset !== offset) {
  10969. pointer.offset = offset;
  10970. changed = true;
  10971. }
  10972. }
  10973. if (changed || this._vaoRecordInProgress) {
  10974. this.bindArrayBuffer(buffer);
  10975. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  10976. }
  10977. };
  10978. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  10979. if (indexBuffer == null) {
  10980. return;
  10981. }
  10982. if (this._cachedIndexBuffer !== indexBuffer) {
  10983. this._cachedIndexBuffer = indexBuffer;
  10984. this.bindIndexBuffer(indexBuffer);
  10985. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  10986. }
  10987. };
  10988. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  10989. var attributes = effect.getAttributesNames();
  10990. if (!this._vaoRecordInProgress) {
  10991. this._unbindVertexArrayObject();
  10992. }
  10993. this.unbindAllAttributes();
  10994. for (var index = 0; index < attributes.length; index++) {
  10995. var order = effect.getAttributeLocation(index);
  10996. if (order >= 0) {
  10997. var vertexBuffer = vertexBuffers[attributes[index]];
  10998. if (!vertexBuffer) {
  10999. continue;
  11000. }
  11001. this._gl.enableVertexAttribArray(order);
  11002. if (!this._vaoRecordInProgress) {
  11003. this._vertexAttribArraysEnabled[order] = true;
  11004. }
  11005. var buffer = vertexBuffer.getBuffer();
  11006. if (buffer) {
  11007. this.vertexAttribPointer(buffer, order, vertexBuffer.getSize(), this._gl.FLOAT, false, vertexBuffer.getStrideSize() * 4, vertexBuffer.getOffset() * 4);
  11008. if (vertexBuffer.getIsInstanced()) {
  11009. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  11010. if (!this._vaoRecordInProgress) {
  11011. this._currentInstanceLocations.push(order);
  11012. this._currentInstanceBuffers.push(buffer);
  11013. }
  11014. }
  11015. }
  11016. }
  11017. }
  11018. };
  11019. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  11020. var vao = this._gl.createVertexArray();
  11021. this._vaoRecordInProgress = true;
  11022. this._gl.bindVertexArray(vao);
  11023. this._mustWipeVertexAttributes = true;
  11024. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  11025. this.bindIndexBuffer(indexBuffer);
  11026. this._vaoRecordInProgress = false;
  11027. this._gl.bindVertexArray(null);
  11028. return vao;
  11029. };
  11030. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  11031. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  11032. this._cachedVertexArrayObject = vertexArrayObject;
  11033. this._gl.bindVertexArray(vertexArrayObject);
  11034. this._cachedVertexBuffers = null;
  11035. this._cachedIndexBuffer = null;
  11036. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  11037. this._mustWipeVertexAttributes = true;
  11038. }
  11039. };
  11040. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  11041. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  11042. this._cachedVertexBuffers = vertexBuffer;
  11043. this._cachedEffectForVertexBuffers = effect;
  11044. var attributesCount = effect.getAttributesCount();
  11045. this._unbindVertexArrayObject();
  11046. this.unbindAllAttributes();
  11047. var offset = 0;
  11048. for (var index = 0; index < attributesCount; index++) {
  11049. if (index < vertexDeclaration.length) {
  11050. var order = effect.getAttributeLocation(index);
  11051. if (order >= 0) {
  11052. this._gl.enableVertexAttribArray(order);
  11053. this._vertexAttribArraysEnabled[order] = true;
  11054. this.vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  11055. }
  11056. offset += vertexDeclaration[index] * 4;
  11057. }
  11058. }
  11059. }
  11060. this._bindIndexBufferWithCache(indexBuffer);
  11061. };
  11062. Engine.prototype._unbindVertexArrayObject = function () {
  11063. if (!this._cachedVertexArrayObject) {
  11064. return;
  11065. }
  11066. this._cachedVertexArrayObject = null;
  11067. this._gl.bindVertexArray(null);
  11068. };
  11069. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  11070. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  11071. this._cachedVertexBuffers = vertexBuffers;
  11072. this._cachedEffectForVertexBuffers = effect;
  11073. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  11074. }
  11075. this._bindIndexBufferWithCache(indexBuffer);
  11076. };
  11077. Engine.prototype.unbindInstanceAttributes = function () {
  11078. var boundBuffer;
  11079. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  11080. var instancesBuffer = this._currentInstanceBuffers[i];
  11081. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  11082. boundBuffer = instancesBuffer;
  11083. this.bindArrayBuffer(instancesBuffer);
  11084. }
  11085. var offsetLocation = this._currentInstanceLocations[i];
  11086. this._gl.vertexAttribDivisor(offsetLocation, 0);
  11087. }
  11088. this._currentInstanceBuffers.length = 0;
  11089. this._currentInstanceLocations.length = 0;
  11090. };
  11091. Engine.prototype.releaseVertexArrayObject = function (vao) {
  11092. this._gl.deleteVertexArray(vao);
  11093. };
  11094. Engine.prototype._releaseBuffer = function (buffer) {
  11095. buffer.references--;
  11096. if (buffer.references === 0) {
  11097. this._gl.deleteBuffer(buffer);
  11098. return true;
  11099. }
  11100. return false;
  11101. };
  11102. Engine.prototype.createInstancesBuffer = function (capacity) {
  11103. var buffer = this._gl.createBuffer();
  11104. if (!buffer) {
  11105. throw new Error("Unable to create instance buffer");
  11106. }
  11107. buffer.capacity = capacity;
  11108. this.bindArrayBuffer(buffer);
  11109. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  11110. return buffer;
  11111. };
  11112. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  11113. this._gl.deleteBuffer(buffer);
  11114. };
  11115. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  11116. this.bindArrayBuffer(instancesBuffer);
  11117. if (data) {
  11118. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  11119. }
  11120. if (offsetLocations[0].index !== undefined) {
  11121. var stride = 0;
  11122. for (var i = 0; i < offsetLocations.length; i++) {
  11123. var ai = offsetLocations[i];
  11124. stride += ai.attributeSize * 4;
  11125. }
  11126. for (var i = 0; i < offsetLocations.length; i++) {
  11127. var ai = offsetLocations[i];
  11128. if (!this._vertexAttribArraysEnabled[ai.index]) {
  11129. this._gl.enableVertexAttribArray(ai.index);
  11130. this._vertexAttribArraysEnabled[ai.index] = true;
  11131. }
  11132. this.vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  11133. this._gl.vertexAttribDivisor(ai.index, 1);
  11134. this._currentInstanceLocations.push(ai.index);
  11135. this._currentInstanceBuffers.push(instancesBuffer);
  11136. }
  11137. }
  11138. else {
  11139. for (var index = 0; index < 4; index++) {
  11140. var offsetLocation = offsetLocations[index];
  11141. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  11142. this._gl.enableVertexAttribArray(offsetLocation);
  11143. this._vertexAttribArraysEnabled[offsetLocation] = true;
  11144. }
  11145. this.vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  11146. this._gl.vertexAttribDivisor(offsetLocation, 1);
  11147. this._currentInstanceLocations.push(offsetLocation);
  11148. this._currentInstanceBuffers.push(instancesBuffer);
  11149. }
  11150. }
  11151. };
  11152. Engine.prototype.applyStates = function () {
  11153. this._depthCullingState.apply(this._gl);
  11154. this._stencilState.apply(this._gl);
  11155. this._alphaState.apply(this._gl);
  11156. };
  11157. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  11158. this.drawElementsType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, indexStart, indexCount, instancesCount);
  11159. };
  11160. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  11161. this.drawArraysType(BABYLON.Material.PointFillMode, verticesStart, verticesCount, instancesCount);
  11162. };
  11163. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  11164. this.drawArraysType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, verticesStart, verticesCount, instancesCount);
  11165. };
  11166. Engine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  11167. // Apply states
  11168. this.applyStates();
  11169. this._drawCalls.addCount(1, false);
  11170. // Render
  11171. var drawMode = this.DrawMode(fillMode);
  11172. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  11173. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  11174. if (instancesCount) {
  11175. this._gl.drawElementsInstanced(drawMode, indexCount, indexFormat, indexStart * mult, instancesCount);
  11176. }
  11177. else {
  11178. this._gl.drawElements(drawMode, indexCount, indexFormat, indexStart * mult);
  11179. }
  11180. };
  11181. Engine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  11182. // Apply states
  11183. this.applyStates();
  11184. this._drawCalls.addCount(1, false);
  11185. var drawMode = this.DrawMode(fillMode);
  11186. if (instancesCount) {
  11187. this._gl.drawArraysInstanced(drawMode, verticesStart, verticesCount, instancesCount);
  11188. }
  11189. else {
  11190. this._gl.drawArrays(drawMode, verticesStart, verticesCount);
  11191. }
  11192. };
  11193. Engine.prototype.DrawMode = function (fillMode) {
  11194. switch (fillMode) {
  11195. // Triangle views
  11196. case BABYLON.Material.TriangleFillMode:
  11197. return this._gl.TRIANGLES;
  11198. case BABYLON.Material.PointFillMode:
  11199. return this._gl.POINTS;
  11200. case BABYLON.Material.WireFrameFillMode:
  11201. return this._gl.LINES;
  11202. // Draw modes
  11203. case BABYLON.Material.PointListDrawMode:
  11204. return this._gl.POINTS;
  11205. case BABYLON.Material.LineListDrawMode:
  11206. return this._gl.LINES;
  11207. case BABYLON.Material.LineLoopDrawMode:
  11208. return this._gl.LINE_LOOP;
  11209. case BABYLON.Material.LineStripDrawMode:
  11210. return this._gl.LINE_STRIP;
  11211. case BABYLON.Material.TriangleStripDrawMode:
  11212. return this._gl.TRIANGLE_STRIP;
  11213. case BABYLON.Material.TriangleFanDrawMode:
  11214. return this._gl.TRIANGLE_FAN;
  11215. default:
  11216. return this._gl.TRIANGLES;
  11217. }
  11218. };
  11219. // Shaders
  11220. Engine.prototype._releaseEffect = function (effect) {
  11221. if (this._compiledEffects[effect._key]) {
  11222. delete this._compiledEffects[effect._key];
  11223. this._deleteProgram(effect.getProgram());
  11224. }
  11225. };
  11226. Engine.prototype._deleteProgram = function (program) {
  11227. if (program) {
  11228. program.__SPECTOR_rebuildProgram = null;
  11229. if (program.transformFeedback) {
  11230. this.deleteTransformFeedback(program.transformFeedback);
  11231. program.transformFeedback = null;
  11232. }
  11233. this._gl.deleteProgram(program);
  11234. }
  11235. };
  11236. /**
  11237. * @param baseName The base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  11238. * @param samplers An array of string used to represent textures
  11239. */
  11240. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  11241. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  11242. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  11243. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  11244. if (this._compiledEffects[name]) {
  11245. var compiledEffect = this._compiledEffects[name];
  11246. if (onCompiled && compiledEffect.isReady()) {
  11247. onCompiled(compiledEffect);
  11248. }
  11249. return compiledEffect;
  11250. }
  11251. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  11252. effect._key = name;
  11253. this._compiledEffects[name] = effect;
  11254. return effect;
  11255. };
  11256. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  11257. if (uniformsNames === void 0) { uniformsNames = []; }
  11258. if (samplers === void 0) { samplers = []; }
  11259. if (defines === void 0) { defines = ""; }
  11260. return this.createEffect({
  11261. vertex: "particles",
  11262. fragmentElement: fragmentName
  11263. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  11264. };
  11265. Engine.prototype.createRawShaderProgram = function (vertexCode, fragmentCode, context, transformFeedbackVaryings) {
  11266. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  11267. context = context || this._gl;
  11268. var vertexShader = compileRawShader(context, vertexCode, "vertex");
  11269. var fragmentShader = compileRawShader(context, fragmentCode, "fragment");
  11270. return this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  11271. };
  11272. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context, transformFeedbackVaryings) {
  11273. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  11274. context = context || this._gl;
  11275. this.onBeforeShaderCompilationObservable.notifyObservers(this);
  11276. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n" : "";
  11277. var vertexShader = compileShader(context, vertexCode, "vertex", defines, shaderVersion);
  11278. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines, shaderVersion);
  11279. var program = this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  11280. this.onAfterShaderCompilationObservable.notifyObservers(this);
  11281. return program;
  11282. };
  11283. Engine.prototype._createShaderProgram = function (vertexShader, fragmentShader, context, transformFeedbackVaryings) {
  11284. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  11285. var shaderProgram = context.createProgram();
  11286. if (!shaderProgram) {
  11287. throw new Error("Unable to create program");
  11288. }
  11289. context.attachShader(shaderProgram, vertexShader);
  11290. context.attachShader(shaderProgram, fragmentShader);
  11291. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  11292. var transformFeedback = this.createTransformFeedback();
  11293. this.bindTransformFeedback(transformFeedback);
  11294. this.setTranformFeedbackVaryings(shaderProgram, transformFeedbackVaryings);
  11295. shaderProgram.transformFeedback = transformFeedback;
  11296. }
  11297. context.linkProgram(shaderProgram);
  11298. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  11299. this.bindTransformFeedback(null);
  11300. }
  11301. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  11302. if (!linked) {
  11303. context.validateProgram(shaderProgram);
  11304. var error = context.getProgramInfoLog(shaderProgram);
  11305. if (error) {
  11306. throw new Error(error);
  11307. }
  11308. }
  11309. context.deleteShader(vertexShader);
  11310. context.deleteShader(fragmentShader);
  11311. return shaderProgram;
  11312. };
  11313. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  11314. var results = new Array();
  11315. for (var index = 0; index < uniformsNames.length; index++) {
  11316. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  11317. }
  11318. return results;
  11319. };
  11320. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  11321. var results = [];
  11322. for (var index = 0; index < attributesNames.length; index++) {
  11323. try {
  11324. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  11325. }
  11326. catch (e) {
  11327. results.push(-1);
  11328. }
  11329. }
  11330. return results;
  11331. };
  11332. Engine.prototype.enableEffect = function (effect) {
  11333. if (!effect) {
  11334. return;
  11335. }
  11336. // Use program
  11337. this.bindSamplers(effect);
  11338. this._currentEffect = effect;
  11339. if (effect.onBind) {
  11340. effect.onBind(effect);
  11341. }
  11342. effect.onBindObservable.notifyObservers(effect);
  11343. };
  11344. Engine.prototype.setIntArray = function (uniform, array) {
  11345. if (!uniform)
  11346. return;
  11347. this._gl.uniform1iv(uniform, array);
  11348. };
  11349. Engine.prototype.setIntArray2 = function (uniform, array) {
  11350. if (!uniform || array.length % 2 !== 0)
  11351. return;
  11352. this._gl.uniform2iv(uniform, array);
  11353. };
  11354. Engine.prototype.setIntArray3 = function (uniform, array) {
  11355. if (!uniform || array.length % 3 !== 0)
  11356. return;
  11357. this._gl.uniform3iv(uniform, array);
  11358. };
  11359. Engine.prototype.setIntArray4 = function (uniform, array) {
  11360. if (!uniform || array.length % 4 !== 0)
  11361. return;
  11362. this._gl.uniform4iv(uniform, array);
  11363. };
  11364. Engine.prototype.setFloatArray = function (uniform, array) {
  11365. if (!uniform)
  11366. return;
  11367. this._gl.uniform1fv(uniform, array);
  11368. };
  11369. Engine.prototype.setFloatArray2 = function (uniform, array) {
  11370. if (!uniform || array.length % 2 !== 0)
  11371. return;
  11372. this._gl.uniform2fv(uniform, array);
  11373. };
  11374. Engine.prototype.setFloatArray3 = function (uniform, array) {
  11375. if (!uniform || array.length % 3 !== 0)
  11376. return;
  11377. this._gl.uniform3fv(uniform, array);
  11378. };
  11379. Engine.prototype.setFloatArray4 = function (uniform, array) {
  11380. if (!uniform || array.length % 4 !== 0)
  11381. return;
  11382. this._gl.uniform4fv(uniform, array);
  11383. };
  11384. Engine.prototype.setArray = function (uniform, array) {
  11385. if (!uniform)
  11386. return;
  11387. this._gl.uniform1fv(uniform, array);
  11388. };
  11389. Engine.prototype.setArray2 = function (uniform, array) {
  11390. if (!uniform || array.length % 2 !== 0)
  11391. return;
  11392. this._gl.uniform2fv(uniform, array);
  11393. };
  11394. Engine.prototype.setArray3 = function (uniform, array) {
  11395. if (!uniform || array.length % 3 !== 0)
  11396. return;
  11397. this._gl.uniform3fv(uniform, array);
  11398. };
  11399. Engine.prototype.setArray4 = function (uniform, array) {
  11400. if (!uniform || array.length % 4 !== 0)
  11401. return;
  11402. this._gl.uniform4fv(uniform, array);
  11403. };
  11404. Engine.prototype.setMatrices = function (uniform, matrices) {
  11405. if (!uniform)
  11406. return;
  11407. this._gl.uniformMatrix4fv(uniform, false, matrices);
  11408. };
  11409. Engine.prototype.setMatrix = function (uniform, matrix) {
  11410. if (!uniform)
  11411. return;
  11412. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  11413. };
  11414. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  11415. if (!uniform)
  11416. return;
  11417. this._gl.uniformMatrix3fv(uniform, false, matrix);
  11418. };
  11419. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  11420. if (!uniform)
  11421. return;
  11422. this._gl.uniformMatrix2fv(uniform, false, matrix);
  11423. };
  11424. Engine.prototype.setInt = function (uniform, value) {
  11425. if (!uniform)
  11426. return;
  11427. this._gl.uniform1i(uniform, value);
  11428. };
  11429. Engine.prototype.setFloat = function (uniform, value) {
  11430. if (!uniform)
  11431. return;
  11432. this._gl.uniform1f(uniform, value);
  11433. };
  11434. Engine.prototype.setFloat2 = function (uniform, x, y) {
  11435. if (!uniform)
  11436. return;
  11437. this._gl.uniform2f(uniform, x, y);
  11438. };
  11439. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  11440. if (!uniform)
  11441. return;
  11442. this._gl.uniform3f(uniform, x, y, z);
  11443. };
  11444. Engine.prototype.setBool = function (uniform, bool) {
  11445. if (!uniform)
  11446. return;
  11447. this._gl.uniform1i(uniform, bool);
  11448. };
  11449. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  11450. if (!uniform)
  11451. return;
  11452. this._gl.uniform4f(uniform, x, y, z, w);
  11453. };
  11454. Engine.prototype.setColor3 = function (uniform, color3) {
  11455. if (!uniform)
  11456. return;
  11457. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  11458. };
  11459. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  11460. if (!uniform)
  11461. return;
  11462. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  11463. };
  11464. // States
  11465. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  11466. if (zOffset === void 0) { zOffset = 0; }
  11467. if (reverseSide === void 0) { reverseSide = false; }
  11468. // Culling
  11469. if (this._depthCullingState.cull !== culling || force) {
  11470. this._depthCullingState.cull = culling;
  11471. }
  11472. // Cull face
  11473. var cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  11474. if (this._depthCullingState.cullFace !== cullFace || force) {
  11475. this._depthCullingState.cullFace = cullFace;
  11476. }
  11477. // Z offset
  11478. this.setZOffset(zOffset);
  11479. // Front face
  11480. var frontFace = reverseSide ? this._gl.CW : this._gl.CCW;
  11481. if (this._depthCullingState.frontFace !== frontFace || force) {
  11482. this._depthCullingState.frontFace = frontFace;
  11483. }
  11484. };
  11485. Engine.prototype.setZOffset = function (value) {
  11486. this._depthCullingState.zOffset = value;
  11487. };
  11488. Engine.prototype.getZOffset = function () {
  11489. return this._depthCullingState.zOffset;
  11490. };
  11491. Engine.prototype.setDepthBuffer = function (enable) {
  11492. this._depthCullingState.depthTest = enable;
  11493. };
  11494. Engine.prototype.getDepthWrite = function () {
  11495. return this._depthCullingState.depthMask;
  11496. };
  11497. Engine.prototype.setDepthWrite = function (enable) {
  11498. this._depthCullingState.depthMask = enable;
  11499. };
  11500. Engine.prototype.setColorWrite = function (enable) {
  11501. this._gl.colorMask(enable, enable, enable, enable);
  11502. this._colorWrite = enable;
  11503. };
  11504. Engine.prototype.getColorWrite = function () {
  11505. return this._colorWrite;
  11506. };
  11507. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  11508. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  11509. };
  11510. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  11511. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  11512. if (this._alphaMode === mode) {
  11513. return;
  11514. }
  11515. switch (mode) {
  11516. case Engine.ALPHA_DISABLE:
  11517. this._alphaState.alphaBlend = false;
  11518. break;
  11519. case Engine.ALPHA_PREMULTIPLIED:
  11520. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  11521. this._alphaState.alphaBlend = true;
  11522. break;
  11523. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  11524. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  11525. this._alphaState.alphaBlend = true;
  11526. break;
  11527. case Engine.ALPHA_COMBINE:
  11528. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  11529. this._alphaState.alphaBlend = true;
  11530. break;
  11531. case Engine.ALPHA_ONEONE:
  11532. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  11533. this._alphaState.alphaBlend = true;
  11534. break;
  11535. case Engine.ALPHA_ADD:
  11536. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  11537. this._alphaState.alphaBlend = true;
  11538. break;
  11539. case Engine.ALPHA_SUBTRACT:
  11540. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  11541. this._alphaState.alphaBlend = true;
  11542. break;
  11543. case Engine.ALPHA_MULTIPLY:
  11544. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  11545. this._alphaState.alphaBlend = true;
  11546. break;
  11547. case Engine.ALPHA_MAXIMIZED:
  11548. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  11549. this._alphaState.alphaBlend = true;
  11550. break;
  11551. case Engine.ALPHA_INTERPOLATE:
  11552. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  11553. this._alphaState.alphaBlend = true;
  11554. break;
  11555. case Engine.ALPHA_SCREENMODE:
  11556. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  11557. this._alphaState.alphaBlend = true;
  11558. break;
  11559. }
  11560. if (!noDepthWriteChange) {
  11561. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  11562. }
  11563. this._alphaMode = mode;
  11564. };
  11565. Engine.prototype.getAlphaMode = function () {
  11566. return this._alphaMode;
  11567. };
  11568. // Textures
  11569. Engine.prototype.wipeCaches = function (bruteForce) {
  11570. if (this.preventCacheWipeBetweenFrames && !bruteForce) {
  11571. return;
  11572. }
  11573. this._currentEffect = null;
  11574. // 6/8/2017: deltakosh: Should not be required anymore.
  11575. // This message is then mostly for the future myself who will scream out loud when seeing that it was actually required :)
  11576. if (bruteForce) {
  11577. this.resetTextureCache();
  11578. this._currentProgram = null;
  11579. this._stencilState.reset();
  11580. this._depthCullingState.reset();
  11581. this.setDepthFunctionToLessOrEqual();
  11582. this._alphaState.reset();
  11583. }
  11584. this._resetVertexBufferBinding();
  11585. this._cachedIndexBuffer = null;
  11586. this._cachedEffectForVertexBuffers = null;
  11587. this._unbindVertexArrayObject();
  11588. this.bindIndexBuffer(null);
  11589. };
  11590. /**
  11591. * Set the compressed texture format to use, based on the formats you have, and the formats
  11592. * supported by the hardware / browser.
  11593. *
  11594. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  11595. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  11596. * to API arguments needed to compressed textures. This puts the burden on the container
  11597. * generator to house the arcane code for determining these for current & future formats.
  11598. *
  11599. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  11600. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  11601. *
  11602. * Note: The result of this call is not taken into account when a texture is base64.
  11603. *
  11604. * @param {Array<string>} formatsAvailable- The list of those format families you have created
  11605. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  11606. *
  11607. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  11608. * @returns The extension selected.
  11609. */
  11610. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  11611. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  11612. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  11613. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  11614. return this._textureFormatInUse = this._texturesSupported[i];
  11615. }
  11616. }
  11617. }
  11618. // actively set format to nothing, to allow this to be called more than once
  11619. // and possibly fail the 2nd time
  11620. this._textureFormatInUse = null;
  11621. return null;
  11622. };
  11623. Engine.prototype._createTexture = function () {
  11624. var texture = this._gl.createTexture();
  11625. if (!texture) {
  11626. throw new Error("Unable to create texture");
  11627. }
  11628. return texture;
  11629. };
  11630. /**
  11631. * Usually called from BABYLON.Texture.ts. Passed information to create a WebGLTexture.
  11632. * @param {string} urlArg- This contains one of the following:
  11633. * 1. A conventional http URL, e.g. 'http://...' or 'file://...'
  11634. * 2. A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  11635. * 3. An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  11636. *
  11637. * @param {boolean} noMipmap- When true, no mipmaps shall be generated. Ignored for compressed textures. They must be in the file.
  11638. * @param {boolean} invertY- When true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file.
  11639. * @param {Scene} scene- Needed for loading to the correct scene.
  11640. * @param {number} samplingMode- Mode with should be used sample / access the texture. Default: TRILINEAR
  11641. * @param {callback} onLoad- Optional callback to be called upon successful completion.
  11642. * @param {callback} onError- Optional callback to be called upon failure.
  11643. * @param {ArrayBuffer | HTMLImageElement} buffer- A source of a file previously fetched as either an ArrayBuffer (compressed or image format) or HTMLImageElement (image format)
  11644. * @param {WebGLTexture} fallback- An internal argument in case the function must be called again, due to etc1 not having alpha capabilities.
  11645. * @param {number} format- Internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures.
  11646. *
  11647. * @returns {WebGLTexture} for assignment back into BABYLON.Texture
  11648. */
  11649. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  11650. var _this = this;
  11651. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  11652. if (onLoad === void 0) { onLoad = null; }
  11653. if (onError === void 0) { onError = null; }
  11654. if (buffer === void 0) { buffer = null; }
  11655. if (fallBack === void 0) { fallBack = null; }
  11656. if (format === void 0) { format = null; }
  11657. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  11658. var fromData = url.substr(0, 5) === "data:";
  11659. var fromBlob = url.substr(0, 5) === "blob:";
  11660. var isBase64 = fromData && url.indexOf("base64") !== -1;
  11661. var texture = fallBack ? fallBack : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  11662. // establish the file extension, if possible
  11663. var lastDot = url.lastIndexOf('.');
  11664. var extension = (lastDot > 0) ? url.substring(lastDot).toLowerCase() : "";
  11665. var isDDS = this.getCaps().s3tc && (extension.indexOf(".dds") === 0);
  11666. var isTGA = (extension.indexOf(".tga") === 0);
  11667. // determine if a ktx file should be substituted
  11668. var isKTX = false;
  11669. if (this._textureFormatInUse && !isBase64 && !fallBack) {
  11670. url = url.substring(0, lastDot) + this._textureFormatInUse;
  11671. isKTX = true;
  11672. }
  11673. if (scene) {
  11674. scene._addPendingData(texture);
  11675. }
  11676. texture.url = url;
  11677. texture.generateMipMaps = !noMipmap;
  11678. texture.samplingMode = samplingMode;
  11679. texture.invertY = invertY;
  11680. if (!this._doNotHandleContextLost) {
  11681. // Keep a link to the buffer only if we plan to handle context lost
  11682. texture._buffer = buffer;
  11683. }
  11684. var onLoadObserver = null;
  11685. if (onLoad && !fallBack) {
  11686. onLoadObserver = texture.onLoadedObservable.add(onLoad);
  11687. }
  11688. if (!fallBack)
  11689. this._internalTexturesCache.push(texture);
  11690. var onerror = function (message, exception) {
  11691. if (scene) {
  11692. scene._removePendingData(texture);
  11693. }
  11694. if (onLoadObserver) {
  11695. texture.onLoadedObservable.remove(onLoadObserver);
  11696. }
  11697. // fallback for when compressed file not found to try again. For instance, etc1 does not have an alpha capable type
  11698. if (isKTX) {
  11699. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  11700. }
  11701. else if (BABYLON.Tools.UseFallbackTexture) {
  11702. _this.createTexture(BABYLON.Tools.fallbackTexture, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  11703. }
  11704. if (onError) {
  11705. onError(message || "Unknown error", exception);
  11706. }
  11707. };
  11708. var callback = null;
  11709. // processing for non-image formats
  11710. if (isKTX || isTGA || isDDS) {
  11711. if (isKTX) {
  11712. callback = function (data) {
  11713. var ktx = new BABYLON.KhronosTextureContainer(data, 1);
  11714. _this._prepareWebGLTexture(texture, scene, ktx.pixelWidth, ktx.pixelHeight, invertY, false, true, function () {
  11715. ktx.uploadLevels(_this._gl, !noMipmap);
  11716. return false;
  11717. }, samplingMode);
  11718. };
  11719. }
  11720. else if (isTGA) {
  11721. callback = function (arrayBuffer) {
  11722. var data = new Uint8Array(arrayBuffer);
  11723. var header = BABYLON.TGATools.GetTGAHeader(data);
  11724. _this._prepareWebGLTexture(texture, scene, header.width, header.height, invertY, noMipmap, false, function () {
  11725. BABYLON.TGATools.UploadContent(_this._gl, data);
  11726. return false;
  11727. }, samplingMode);
  11728. };
  11729. }
  11730. else if (isDDS) {
  11731. callback = function (data) {
  11732. var info = BABYLON.DDSTools.GetDDSInfo(data);
  11733. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  11734. _this._prepareWebGLTexture(texture, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  11735. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 1);
  11736. return false;
  11737. }, samplingMode);
  11738. };
  11739. }
  11740. if (!buffer) {
  11741. this._loadFile(url, function (data) {
  11742. if (callback) {
  11743. callback(data);
  11744. }
  11745. }, undefined, scene ? scene.database : undefined, true, function (request, exception) {
  11746. onerror("Unable to load " + (request ? request.responseURL : url, exception));
  11747. });
  11748. }
  11749. else {
  11750. if (callback) {
  11751. callback(buffer);
  11752. }
  11753. }
  11754. // image format processing
  11755. }
  11756. else {
  11757. var onload = function (img) {
  11758. if (fromBlob && !_this._doNotHandleContextLost) {
  11759. // We need to store the image if we need to rebuild the texture
  11760. // in case of a webgl context lost
  11761. texture._buffer = img;
  11762. }
  11763. _this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight, continuationCallback) {
  11764. var gl = _this._gl;
  11765. var isPot = (img.width === potWidth && img.height === potHeight);
  11766. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  11767. if (isPot) {
  11768. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  11769. return false;
  11770. }
  11771. // Using shaders to rescale because canvas.drawImage is lossy
  11772. var source = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  11773. _this._bindTextureDirectly(gl.TEXTURE_2D, source, true);
  11774. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  11775. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  11776. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  11777. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  11778. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  11779. _this._rescaleTexture(source, texture, scene, internalFormat, function () {
  11780. _this._releaseTexture(source);
  11781. _this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  11782. continuationCallback();
  11783. });
  11784. return true;
  11785. }, samplingMode);
  11786. };
  11787. if (!fromData || isBase64)
  11788. if (buffer instanceof HTMLImageElement) {
  11789. onload(buffer);
  11790. }
  11791. else {
  11792. BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  11793. }
  11794. else if (buffer instanceof Array || typeof buffer === "string" || buffer instanceof ArrayBuffer)
  11795. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene ? scene.database : null);
  11796. else
  11797. onload(buffer);
  11798. }
  11799. return texture;
  11800. };
  11801. Engine.prototype._rescaleTexture = function (source, destination, scene, internalFormat, onComplete) {
  11802. var _this = this;
  11803. var rtt = this.createRenderTargetTexture({
  11804. width: destination.width,
  11805. height: destination.height,
  11806. }, {
  11807. generateMipMaps: false,
  11808. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  11809. samplingMode: BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  11810. generateDepthBuffer: false,
  11811. generateStencilBuffer: false
  11812. });
  11813. if (!this._rescalePostProcess) {
  11814. this._rescalePostProcess = new BABYLON.PassPostProcess("rescale", 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  11815. }
  11816. this._rescalePostProcess.getEffect().executeWhenCompiled(function () {
  11817. _this._rescalePostProcess.onApply = function (effect) {
  11818. effect._bindTexture("textureSampler", source);
  11819. };
  11820. var hostingScene = scene;
  11821. if (!hostingScene) {
  11822. hostingScene = _this.scenes[_this.scenes.length - 1];
  11823. }
  11824. hostingScene.postProcessManager.directRender([_this._rescalePostProcess], rtt, true);
  11825. _this._bindTextureDirectly(_this._gl.TEXTURE_2D, destination, true);
  11826. _this._gl.copyTexImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
  11827. _this.unBindFramebuffer(rtt);
  11828. _this._releaseTexture(rtt);
  11829. if (onComplete) {
  11830. onComplete();
  11831. }
  11832. });
  11833. };
  11834. Engine.prototype._getInternalFormat = function (format) {
  11835. var internalFormat = this._gl.RGBA;
  11836. switch (format) {
  11837. case Engine.TEXTUREFORMAT_ALPHA:
  11838. internalFormat = this._gl.ALPHA;
  11839. break;
  11840. case Engine.TEXTUREFORMAT_LUMINANCE:
  11841. internalFormat = this._gl.LUMINANCE;
  11842. break;
  11843. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  11844. internalFormat = this._gl.LUMINANCE_ALPHA;
  11845. break;
  11846. case Engine.TEXTUREFORMAT_RGB:
  11847. internalFormat = this._gl.RGB;
  11848. break;
  11849. case Engine.TEXTUREFORMAT_RGBA:
  11850. internalFormat = this._gl.RGBA;
  11851. break;
  11852. }
  11853. return internalFormat;
  11854. };
  11855. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression, type) {
  11856. if (compression === void 0) { compression = null; }
  11857. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  11858. if (!texture) {
  11859. return;
  11860. }
  11861. var internalFormat = this._getInternalFormat(format);
  11862. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  11863. var textureType = this._getWebGLTextureType(type);
  11864. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  11865. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  11866. if (!this._doNotHandleContextLost) {
  11867. texture._bufferView = data;
  11868. texture.format = format;
  11869. texture.type = type;
  11870. texture.invertY = invertY;
  11871. texture._compression = compression;
  11872. }
  11873. if (texture.width % 4 !== 0) {
  11874. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  11875. }
  11876. if (compression && data) {
  11877. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data);
  11878. }
  11879. else {
  11880. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, data);
  11881. }
  11882. if (texture.generateMipMaps) {
  11883. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  11884. }
  11885. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  11886. // this.resetTextureCache();
  11887. texture.isReady = true;
  11888. };
  11889. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression, type) {
  11890. if (compression === void 0) { compression = null; }
  11891. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  11892. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW);
  11893. texture.baseWidth = width;
  11894. texture.baseHeight = height;
  11895. texture.width = width;
  11896. texture.height = height;
  11897. texture.format = format;
  11898. texture.generateMipMaps = generateMipMaps;
  11899. texture.samplingMode = samplingMode;
  11900. texture.invertY = invertY;
  11901. texture._compression = compression;
  11902. texture.type = type;
  11903. if (!this._doNotHandleContextLost) {
  11904. texture._bufferView = data;
  11905. }
  11906. this.updateRawTexture(texture, data, format, invertY, compression, type);
  11907. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  11908. // Filters
  11909. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  11910. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  11911. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  11912. if (generateMipMaps) {
  11913. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  11914. }
  11915. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  11916. this._internalTexturesCache.push(texture);
  11917. return texture;
  11918. };
  11919. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  11920. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DYNAMIC);
  11921. texture.baseWidth = width;
  11922. texture.baseHeight = height;
  11923. if (generateMipMaps) {
  11924. width = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  11925. height = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  11926. }
  11927. // this.resetTextureCache();
  11928. texture.width = width;
  11929. texture.height = height;
  11930. texture.isReady = false;
  11931. texture.generateMipMaps = generateMipMaps;
  11932. texture.samplingMode = samplingMode;
  11933. this.updateTextureSamplingMode(samplingMode, texture);
  11934. this._internalTexturesCache.push(texture);
  11935. return texture;
  11936. };
  11937. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  11938. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  11939. if (texture.isCube) {
  11940. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  11941. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  11942. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  11943. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  11944. }
  11945. else if (texture.is3D) {
  11946. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  11947. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  11948. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  11949. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  11950. }
  11951. else {
  11952. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  11953. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  11954. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  11955. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  11956. }
  11957. texture.samplingMode = samplingMode;
  11958. };
  11959. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  11960. if (premulAlpha === void 0) { premulAlpha = false; }
  11961. if (!texture) {
  11962. return;
  11963. }
  11964. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  11965. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  11966. if (premulAlpha) {
  11967. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  11968. }
  11969. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  11970. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  11971. if (texture.generateMipMaps) {
  11972. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  11973. }
  11974. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  11975. if (premulAlpha) {
  11976. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  11977. }
  11978. texture.isReady = true;
  11979. };
  11980. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  11981. if (!texture || texture._isDisabled) {
  11982. return;
  11983. }
  11984. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  11985. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  11986. try {
  11987. // Testing video texture support
  11988. if (this._videoTextureSupported === undefined) {
  11989. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  11990. if (this._gl.getError() !== 0) {
  11991. this._videoTextureSupported = false;
  11992. }
  11993. else {
  11994. this._videoTextureSupported = true;
  11995. }
  11996. }
  11997. // Copy video through the current working canvas if video texture is not supported
  11998. if (!this._videoTextureSupported) {
  11999. if (!texture._workingCanvas) {
  12000. texture._workingCanvas = document.createElement("canvas");
  12001. var context = texture._workingCanvas.getContext("2d");
  12002. if (!context) {
  12003. throw new Error("Unable to get 2d context");
  12004. }
  12005. texture._workingContext = context;
  12006. texture._workingCanvas.width = texture.width;
  12007. texture._workingCanvas.height = texture.height;
  12008. }
  12009. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
  12010. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  12011. }
  12012. else {
  12013. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  12014. }
  12015. if (texture.generateMipMaps) {
  12016. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  12017. }
  12018. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  12019. // this.resetTextureCache();
  12020. texture.isReady = true;
  12021. }
  12022. catch (ex) {
  12023. // Something unexpected
  12024. // Let's disable the texture
  12025. texture._isDisabled = true;
  12026. }
  12027. };
  12028. Engine.prototype.createRenderTargetTexture = function (size, options) {
  12029. var fullOptions = new RenderTargetCreationOptions();
  12030. if (options !== undefined && typeof options === "object") {
  12031. fullOptions.generateMipMaps = options.generateMipMaps;
  12032. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  12033. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  12034. fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  12035. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  12036. }
  12037. else {
  12038. fullOptions.generateMipMaps = options;
  12039. fullOptions.generateDepthBuffer = true;
  12040. fullOptions.generateStencilBuffer = false;
  12041. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  12042. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  12043. }
  12044. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  12045. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  12046. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  12047. }
  12048. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  12049. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  12050. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  12051. }
  12052. var gl = this._gl;
  12053. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  12054. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  12055. var width = size.width || size;
  12056. var height = size.height || size;
  12057. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps ? true : false, gl);
  12058. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  12059. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  12060. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  12061. }
  12062. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  12063. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  12064. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  12065. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  12066. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type), width, height, 0, gl.RGBA, this._getWebGLTextureType(fullOptions.type), null);
  12067. // Create the framebuffer
  12068. var framebuffer = gl.createFramebuffer();
  12069. this.bindUnboundFramebuffer(framebuffer);
  12070. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  12071. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer ? true : false, fullOptions.generateDepthBuffer, width, height);
  12072. if (fullOptions.generateMipMaps) {
  12073. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  12074. }
  12075. // Unbind
  12076. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  12077. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  12078. this.bindUnboundFramebuffer(null);
  12079. texture._framebuffer = framebuffer;
  12080. texture.baseWidth = width;
  12081. texture.baseHeight = height;
  12082. texture.width = width;
  12083. texture.height = height;
  12084. texture.isReady = true;
  12085. texture.samples = 1;
  12086. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  12087. texture.samplingMode = fullOptions.samplingMode;
  12088. texture.type = fullOptions.type;
  12089. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  12090. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  12091. // this.resetTextureCache();
  12092. this._internalTexturesCache.push(texture);
  12093. return texture;
  12094. };
  12095. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  12096. var generateMipMaps = false;
  12097. var generateDepthBuffer = true;
  12098. var generateStencilBuffer = false;
  12099. var generateDepthTexture = false;
  12100. var textureCount = 1;
  12101. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  12102. var defaultSamplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  12103. var types = [], samplingModes = [];
  12104. if (options !== undefined) {
  12105. generateMipMaps = options.generateMipMaps;
  12106. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  12107. generateStencilBuffer = options.generateStencilBuffer;
  12108. generateDepthTexture = options.generateDepthTexture;
  12109. textureCount = options.textureCount || 1;
  12110. if (options.types) {
  12111. types = options.types;
  12112. }
  12113. if (options.samplingModes) {
  12114. samplingModes = options.samplingModes;
  12115. }
  12116. }
  12117. var gl = this._gl;
  12118. // Create the framebuffer
  12119. var framebuffer = gl.createFramebuffer();
  12120. this.bindUnboundFramebuffer(framebuffer);
  12121. var width = size.width || size;
  12122. var height = size.height || size;
  12123. var textures = [];
  12124. var attachments = [];
  12125. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  12126. for (var i = 0; i < textureCount; i++) {
  12127. var samplingMode = samplingModes[i] || defaultSamplingMode;
  12128. var type = types[i] || defaultType;
  12129. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  12130. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  12131. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  12132. }
  12133. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  12134. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  12135. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  12136. }
  12137. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  12138. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  12139. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  12140. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  12141. }
  12142. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  12143. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  12144. textures.push(texture);
  12145. attachments.push(attachment);
  12146. gl.activeTexture(gl["TEXTURE" + i]);
  12147. gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
  12148. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  12149. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  12150. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  12151. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  12152. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  12153. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
  12154. if (generateMipMaps) {
  12155. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  12156. }
  12157. // Unbind
  12158. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  12159. texture._framebuffer = framebuffer;
  12160. texture._depthStencilBuffer = depthStencilBuffer;
  12161. texture.baseWidth = width;
  12162. texture.baseHeight = height;
  12163. texture.width = width;
  12164. texture.height = height;
  12165. texture.isReady = true;
  12166. texture.samples = 1;
  12167. texture.generateMipMaps = generateMipMaps;
  12168. texture.samplingMode = samplingMode;
  12169. texture.type = type;
  12170. texture._generateDepthBuffer = generateDepthBuffer;
  12171. texture._generateStencilBuffer = generateStencilBuffer;
  12172. texture._attachments = attachments;
  12173. this._internalTexturesCache.push(texture);
  12174. }
  12175. if (generateDepthTexture && this._caps.depthTextureExtension) {
  12176. // Depth texture
  12177. var depthTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  12178. gl.activeTexture(gl.TEXTURE0);
  12179. gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
  12180. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  12181. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  12182. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  12183. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  12184. 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);
  12185. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._webGLTexture, 0);
  12186. depthTexture._framebuffer = framebuffer;
  12187. depthTexture.baseWidth = width;
  12188. depthTexture.baseHeight = height;
  12189. depthTexture.width = width;
  12190. depthTexture.height = height;
  12191. depthTexture.isReady = true;
  12192. depthTexture.samples = 1;
  12193. depthTexture.generateMipMaps = generateMipMaps;
  12194. depthTexture.samplingMode = gl.NEAREST;
  12195. depthTexture._generateDepthBuffer = generateDepthBuffer;
  12196. depthTexture._generateStencilBuffer = generateStencilBuffer;
  12197. textures.push(depthTexture);
  12198. this._internalTexturesCache.push(depthTexture);
  12199. }
  12200. gl.drawBuffers(attachments);
  12201. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  12202. this.bindUnboundFramebuffer(null);
  12203. this.resetTextureCache();
  12204. return textures;
  12205. };
  12206. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  12207. if (samples === void 0) { samples = 1; }
  12208. var depthStencilBuffer = null;
  12209. var gl = this._gl;
  12210. // Create the depth/stencil buffer
  12211. if (generateStencilBuffer) {
  12212. depthStencilBuffer = gl.createRenderbuffer();
  12213. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  12214. if (samples > 1) {
  12215. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  12216. }
  12217. else {
  12218. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  12219. }
  12220. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  12221. }
  12222. else if (generateDepthBuffer) {
  12223. depthStencilBuffer = gl.createRenderbuffer();
  12224. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  12225. if (samples > 1) {
  12226. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  12227. }
  12228. else {
  12229. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  12230. }
  12231. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  12232. }
  12233. return depthStencilBuffer;
  12234. };
  12235. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  12236. if (this.webGLVersion < 2 || !texture) {
  12237. return 1;
  12238. }
  12239. if (texture.samples === samples) {
  12240. return samples;
  12241. }
  12242. var gl = this._gl;
  12243. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  12244. // Dispose previous render buffers
  12245. if (texture._depthStencilBuffer) {
  12246. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  12247. texture._depthStencilBuffer = null;
  12248. }
  12249. if (texture._MSAAFramebuffer) {
  12250. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  12251. texture._MSAAFramebuffer = null;
  12252. }
  12253. if (texture._MSAARenderBuffer) {
  12254. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  12255. texture._MSAARenderBuffer = null;
  12256. }
  12257. if (samples > 1) {
  12258. var framebuffer = gl.createFramebuffer();
  12259. if (!framebuffer) {
  12260. throw new Error("Unable to create multi sampled framebuffer");
  12261. }
  12262. texture._MSAAFramebuffer = framebuffer;
  12263. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  12264. var colorRenderbuffer = gl.createRenderbuffer();
  12265. if (!colorRenderbuffer) {
  12266. throw new Error("Unable to create multi sampled framebuffer");
  12267. }
  12268. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  12269. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  12270. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  12271. texture._MSAARenderBuffer = colorRenderbuffer;
  12272. }
  12273. else {
  12274. this.bindUnboundFramebuffer(texture._framebuffer);
  12275. }
  12276. texture.samples = samples;
  12277. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
  12278. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  12279. this.bindUnboundFramebuffer(null);
  12280. return samples;
  12281. };
  12282. Engine.prototype.updateMultipleRenderTargetTextureSampleCount = function (textures, samples) {
  12283. if (this.webGLVersion < 2 || !textures || textures.length == 0) {
  12284. return 1;
  12285. }
  12286. if (textures[0].samples === samples) {
  12287. return samples;
  12288. }
  12289. var gl = this._gl;
  12290. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  12291. // Dispose previous render buffers
  12292. if (textures[0]._depthStencilBuffer) {
  12293. gl.deleteRenderbuffer(textures[0]._depthStencilBuffer);
  12294. textures[0]._depthStencilBuffer = null;
  12295. }
  12296. if (textures[0]._MSAAFramebuffer) {
  12297. gl.deleteFramebuffer(textures[0]._MSAAFramebuffer);
  12298. textures[0]._MSAAFramebuffer = null;
  12299. }
  12300. for (var i = 0; i < textures.length; i++) {
  12301. if (textures[i]._MSAARenderBuffer) {
  12302. gl.deleteRenderbuffer(textures[i]._MSAARenderBuffer);
  12303. textures[i]._MSAARenderBuffer = null;
  12304. }
  12305. }
  12306. if (samples > 1) {
  12307. var framebuffer = gl.createFramebuffer();
  12308. if (!framebuffer) {
  12309. throw new Error("Unable to create multi sampled framebuffer");
  12310. }
  12311. this.bindUnboundFramebuffer(framebuffer);
  12312. var depthStencilBuffer = this._setupFramebufferDepthAttachments(textures[0]._generateStencilBuffer, textures[0]._generateDepthBuffer, textures[0].width, textures[0].height, samples);
  12313. var attachments = [];
  12314. for (var i = 0; i < textures.length; i++) {
  12315. var texture = textures[i];
  12316. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  12317. var colorRenderbuffer = gl.createRenderbuffer();
  12318. if (!colorRenderbuffer) {
  12319. throw new Error("Unable to create multi sampled framebuffer");
  12320. }
  12321. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  12322. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  12323. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, attachment, gl.RENDERBUFFER, colorRenderbuffer);
  12324. texture._MSAAFramebuffer = framebuffer;
  12325. texture._MSAARenderBuffer = colorRenderbuffer;
  12326. texture.samples = samples;
  12327. texture._depthStencilBuffer = depthStencilBuffer;
  12328. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  12329. attachments.push(attachment);
  12330. }
  12331. gl.drawBuffers(attachments);
  12332. }
  12333. else {
  12334. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  12335. }
  12336. this.bindUnboundFramebuffer(null);
  12337. return samples;
  12338. };
  12339. Engine.prototype._uploadDataToTexture = function (target, lod, internalFormat, width, height, format, type, data) {
  12340. this._gl.texImage2D(target, lod, internalFormat, width, height, 0, format, type, data);
  12341. };
  12342. Engine.prototype._uploadCompressedDataToTexture = function (target, lod, internalFormat, width, height, data) {
  12343. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  12344. };
  12345. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  12346. var gl = this._gl;
  12347. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  12348. var generateMipMaps = true;
  12349. var generateDepthBuffer = true;
  12350. var generateStencilBuffer = false;
  12351. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  12352. if (options !== undefined) {
  12353. generateMipMaps = options.generateMipMaps === undefined ? true : options.generateMipMaps;
  12354. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  12355. generateStencilBuffer = (generateDepthBuffer && options.generateStencilBuffer) ? true : false;
  12356. if (options.samplingMode !== undefined) {
  12357. samplingMode = options.samplingMode;
  12358. }
  12359. }
  12360. texture.isCube = true;
  12361. texture.generateMipMaps = generateMipMaps;
  12362. texture.samples = 1;
  12363. texture.samplingMode = samplingMode;
  12364. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  12365. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  12366. for (var face = 0; face < 6; face++) {
  12367. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, gl.RGBA, size, size, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  12368. }
  12369. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  12370. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  12371. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  12372. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  12373. // Create the framebuffer
  12374. var framebuffer = gl.createFramebuffer();
  12375. this.bindUnboundFramebuffer(framebuffer);
  12376. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, size, size);
  12377. // Mipmaps
  12378. if (texture.generateMipMaps) {
  12379. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  12380. }
  12381. // Unbind
  12382. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  12383. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  12384. this.bindUnboundFramebuffer(null);
  12385. texture._framebuffer = framebuffer;
  12386. texture.width = size;
  12387. texture.height = size;
  12388. texture.isReady = true;
  12389. //this.resetTextureCache();
  12390. this._internalTexturesCache.push(texture);
  12391. return texture;
  12392. };
  12393. Engine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, scale, offset, onLoad, onError, format, forcedExtension) {
  12394. var _this = this;
  12395. if (onLoad === void 0) { onLoad = null; }
  12396. if (onError === void 0) { onError = null; }
  12397. if (forcedExtension === void 0) { forcedExtension = null; }
  12398. var callback = function (loadData) {
  12399. if (!loadData) {
  12400. if (onLoad) {
  12401. onLoad(null);
  12402. }
  12403. return;
  12404. }
  12405. var texture = loadData.texture;
  12406. texture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBEPREFILTERED;
  12407. texture._lodGenerationScale = scale;
  12408. texture._lodGenerationOffset = offset;
  12409. if (_this._caps.textureLOD) {
  12410. // Do not add extra process if texture lod is supported.
  12411. if (onLoad) {
  12412. onLoad(texture);
  12413. }
  12414. return;
  12415. }
  12416. var mipSlices = 3;
  12417. var gl = _this._gl;
  12418. var width = loadData.width;
  12419. if (!width) {
  12420. return;
  12421. }
  12422. var textures = [];
  12423. for (var i = 0; i < mipSlices; i++) {
  12424. //compute LOD from even spacing in smoothness (matching shader calculation)
  12425. var smoothness = i / (mipSlices - 1);
  12426. var roughness = 1 - smoothness;
  12427. var minLODIndex = offset; // roughness = 0
  12428. var maxLODIndex = BABYLON.Scalar.Log2(width) * scale + offset; // roughness = 1
  12429. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  12430. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  12431. var glTextureFromLod = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  12432. glTextureFromLod.isCube = true;
  12433. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod, true);
  12434. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  12435. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  12436. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  12437. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  12438. if (loadData.isDDS) {
  12439. var info = loadData.info;
  12440. var data = loadData.data;
  12441. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  12442. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, true, 6, mipmapIndex);
  12443. }
  12444. else {
  12445. BABYLON.Tools.Warn("DDS is the only prefiltered cube map supported so far.");
  12446. }
  12447. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  12448. // Wrap in a base texture for easy binding.
  12449. var lodTexture = new BABYLON.BaseTexture(scene);
  12450. lodTexture.isCube = true;
  12451. lodTexture._texture = glTextureFromLod;
  12452. glTextureFromLod.isReady = true;
  12453. textures.push(lodTexture);
  12454. }
  12455. texture._lodTextureHigh = textures[2];
  12456. texture._lodTextureMid = textures[1];
  12457. texture._lodTextureLow = textures[0];
  12458. if (onLoad) {
  12459. onLoad(texture);
  12460. }
  12461. };
  12462. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension);
  12463. };
  12464. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension) {
  12465. var _this = this;
  12466. if (onLoad === void 0) { onLoad = null; }
  12467. if (onError === void 0) { onError = null; }
  12468. if (forcedExtension === void 0) { forcedExtension = null; }
  12469. var gl = this._gl;
  12470. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBE);
  12471. texture.isCube = true;
  12472. texture.url = rootUrl;
  12473. texture.generateMipMaps = !noMipmap;
  12474. if (!this._doNotHandleContextLost) {
  12475. texture._extension = forcedExtension;
  12476. texture._files = files;
  12477. }
  12478. var isKTX = false;
  12479. var isDDS = false;
  12480. var lastDot = rootUrl.lastIndexOf('.');
  12481. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  12482. if (this._textureFormatInUse) {
  12483. extension = this._textureFormatInUse;
  12484. rootUrl = (lastDot > -1 ? rootUrl.substring(0, lastDot) : rootUrl) + this._textureFormatInUse;
  12485. isKTX = true;
  12486. }
  12487. else {
  12488. isDDS = (extension === ".dds");
  12489. }
  12490. var onerror = function (request, exception) {
  12491. if (onError && request) {
  12492. onError(request.status + " " + request.statusText, exception);
  12493. }
  12494. };
  12495. if (isKTX) {
  12496. this._loadFile(rootUrl, function (data) {
  12497. var ktx = new BABYLON.KhronosTextureContainer(data, 6);
  12498. var loadMipmap = ktx.numberOfMipmapLevels > 1 && !noMipmap;
  12499. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  12500. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  12501. ktx.uploadLevels(_this._gl, !noMipmap);
  12502. _this.setCubeMapTextureParams(gl, loadMipmap);
  12503. texture.width = ktx.pixelWidth;
  12504. texture.height = ktx.pixelHeight;
  12505. texture.isReady = true;
  12506. }, undefined, undefined, true, onerror);
  12507. }
  12508. else if (isDDS) {
  12509. if (files && files.length === 6) {
  12510. this._cascadeLoadFiles(rootUrl, scene, function (imgs) {
  12511. var info;
  12512. var loadMipmap = false;
  12513. var width = 0;
  12514. for (var index = 0; index < imgs.length; index++) {
  12515. var data = imgs[index];
  12516. info = BABYLON.DDSTools.GetDDSInfo(data);
  12517. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  12518. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  12519. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  12520. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6, -1, index);
  12521. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  12522. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  12523. }
  12524. texture.width = info.width;
  12525. texture.height = info.height;
  12526. texture.type = info.textureType;
  12527. width = info.width;
  12528. }
  12529. _this.setCubeMapTextureParams(gl, loadMipmap);
  12530. texture.isReady = true;
  12531. if (onLoad) {
  12532. onLoad({ isDDS: true, width: width, info: info, imgs: imgs, texture: texture });
  12533. }
  12534. }, files, onError);
  12535. }
  12536. else {
  12537. this._loadFile(rootUrl, function (data) {
  12538. var info = BABYLON.DDSTools.GetDDSInfo(data);
  12539. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  12540. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  12541. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  12542. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6);
  12543. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  12544. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  12545. }
  12546. _this.setCubeMapTextureParams(gl, loadMipmap);
  12547. texture.width = info.width;
  12548. texture.height = info.height;
  12549. texture.isReady = true;
  12550. texture.type = info.textureType;
  12551. if (onLoad) {
  12552. onLoad({ isDDS: true, width: info.width, info: info, data: data, texture: texture });
  12553. }
  12554. }, undefined, undefined, true, onerror);
  12555. }
  12556. }
  12557. else {
  12558. if (!files) {
  12559. throw new Error("Cannot load cubemap because files were not defined");
  12560. }
  12561. cascadeLoadImgs(rootUrl, scene, function (imgs) {
  12562. var width = _this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize) : imgs[0].width;
  12563. var height = width;
  12564. _this._prepareWorkingCanvas();
  12565. if (!_this._workingCanvas || !_this._workingContext) {
  12566. return;
  12567. }
  12568. _this._workingCanvas.width = width;
  12569. _this._workingCanvas.height = height;
  12570. var faces = [
  12571. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  12572. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  12573. ];
  12574. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  12575. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  12576. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  12577. for (var index = 0; index < faces.length; index++) {
  12578. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  12579. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  12580. }
  12581. if (!noMipmap) {
  12582. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  12583. }
  12584. _this.setCubeMapTextureParams(gl, !noMipmap);
  12585. texture.width = width;
  12586. texture.height = height;
  12587. texture.isReady = true;
  12588. if (format) {
  12589. texture.format = format;
  12590. }
  12591. texture.onLoadedObservable.notifyObservers(texture);
  12592. texture.onLoadedObservable.clear();
  12593. if (onLoad) {
  12594. onLoad();
  12595. }
  12596. }, files, onError);
  12597. }
  12598. this._internalTexturesCache.push(texture);
  12599. return texture;
  12600. };
  12601. Engine.prototype.setCubeMapTextureParams = function (gl, loadMipmap) {
  12602. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  12603. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  12604. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  12605. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  12606. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  12607. // this.resetTextureCache();
  12608. };
  12609. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  12610. if (compression === void 0) { compression = null; }
  12611. if (level === void 0) { level = 0; }
  12612. texture._bufferViewArray = data;
  12613. texture.format = format;
  12614. texture.type = type;
  12615. texture.invertY = invertY;
  12616. texture._compression = compression;
  12617. var gl = this._gl;
  12618. var textureType = this._getWebGLTextureType(type);
  12619. var internalFormat = this._getInternalFormat(format);
  12620. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  12621. var needConversion = false;
  12622. if (internalFormat === gl.RGB) {
  12623. internalFormat = gl.RGBA;
  12624. needConversion = true;
  12625. }
  12626. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  12627. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  12628. if (texture.width % 4 !== 0) {
  12629. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  12630. }
  12631. // Data are known to be in +X +Y +Z -X -Y -Z
  12632. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  12633. var faceData = data[faceIndex];
  12634. if (compression) {
  12635. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, (this.getCaps().s3tc)[compression], texture.width, texture.height, 0, faceData);
  12636. }
  12637. else {
  12638. if (needConversion) {
  12639. faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
  12640. }
  12641. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
  12642. }
  12643. }
  12644. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  12645. if (isPot && texture.generateMipMaps && level === 0) {
  12646. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  12647. }
  12648. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  12649. // this.resetTextureCache();
  12650. texture.isReady = true;
  12651. };
  12652. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  12653. if (compression === void 0) { compression = null; }
  12654. var gl = this._gl;
  12655. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBERAW);
  12656. texture.isCube = true;
  12657. texture.generateMipMaps = generateMipMaps;
  12658. texture.format = format;
  12659. texture.type = type;
  12660. if (!this._doNotHandleContextLost) {
  12661. texture._bufferViewArray = data;
  12662. }
  12663. var textureType = this._getWebGLTextureType(type);
  12664. var internalFormat = this._getInternalFormat(format);
  12665. if (internalFormat === gl.RGB) {
  12666. internalFormat = gl.RGBA;
  12667. }
  12668. var width = size;
  12669. var height = width;
  12670. texture.width = width;
  12671. texture.height = height;
  12672. // Double check on POT to generate Mips.
  12673. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  12674. if (!isPot) {
  12675. generateMipMaps = false;
  12676. }
  12677. // Upload data if needed. The texture won't be ready until then.
  12678. if (data) {
  12679. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  12680. }
  12681. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  12682. // Filters
  12683. if (data && generateMipMaps) {
  12684. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  12685. }
  12686. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  12687. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  12688. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  12689. }
  12690. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  12691. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  12692. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  12693. }
  12694. else {
  12695. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  12696. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  12697. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  12698. }
  12699. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  12700. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  12701. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  12702. return texture;
  12703. };
  12704. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmmapGenerator, onLoad, onError, samplingMode, invertY) {
  12705. var _this = this;
  12706. if (onLoad === void 0) { onLoad = null; }
  12707. if (onError === void 0) { onError = null; }
  12708. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  12709. if (invertY === void 0) { invertY = false; }
  12710. var gl = this._gl;
  12711. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  12712. scene._addPendingData(texture);
  12713. texture.url = url;
  12714. this._internalTexturesCache.push(texture);
  12715. var onerror = function (request, exception) {
  12716. scene._removePendingData(texture);
  12717. if (onError && request) {
  12718. onError(request.status + " " + request.statusText, exception);
  12719. }
  12720. };
  12721. var internalCallback = function (data) {
  12722. var width = texture.width;
  12723. var faceDataArrays = callback(data);
  12724. if (!faceDataArrays) {
  12725. return;
  12726. }
  12727. if (mipmmapGenerator) {
  12728. var textureType = _this._getWebGLTextureType(type);
  12729. var internalFormat = _this._getInternalFormat(format);
  12730. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  12731. var needConversion = false;
  12732. if (internalFormat === gl.RGB) {
  12733. internalFormat = gl.RGBA;
  12734. needConversion = true;
  12735. }
  12736. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  12737. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  12738. var mipData = mipmmapGenerator(faceDataArrays);
  12739. for (var level = 0; level < mipData.length; level++) {
  12740. var mipSize = width >> level;
  12741. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  12742. var mipFaceData = mipData[level][faceIndex];
  12743. if (needConversion) {
  12744. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  12745. }
  12746. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  12747. }
  12748. }
  12749. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  12750. }
  12751. else {
  12752. texture.generateMipMaps = !noMipmap;
  12753. _this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  12754. }
  12755. texture.isReady = true;
  12756. // this.resetTextureCache();
  12757. scene._removePendingData(texture);
  12758. if (onLoad) {
  12759. onLoad();
  12760. }
  12761. };
  12762. this._loadFile(url, function (data) {
  12763. internalCallback(data);
  12764. }, undefined, scene.database, true, onerror);
  12765. return texture;
  12766. };
  12767. ;
  12768. Engine.prototype.updateRawTexture3D = function (texture, data, format, invertY, compression) {
  12769. if (compression === void 0) { compression = null; }
  12770. var internalFormat = this._getInternalFormat(format);
  12771. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  12772. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  12773. if (!this._doNotHandleContextLost) {
  12774. texture._bufferView = data;
  12775. texture.format = format;
  12776. texture.invertY = invertY;
  12777. texture._compression = compression;
  12778. }
  12779. if (texture.width % 4 !== 0) {
  12780. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  12781. }
  12782. if (compression && data) {
  12783. this._gl.compressedTexImage3D(this._gl.TEXTURE_3D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, texture.depth, 0, data);
  12784. }
  12785. else {
  12786. this._gl.texImage3D(this._gl.TEXTURE_3D, 0, internalFormat, texture.width, texture.height, texture.depth, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  12787. }
  12788. if (texture.generateMipMaps) {
  12789. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  12790. }
  12791. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  12792. // this.resetTextureCache();
  12793. texture.isReady = true;
  12794. };
  12795. Engine.prototype.createRawTexture3D = function (data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression) {
  12796. if (compression === void 0) { compression = null; }
  12797. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW3D);
  12798. texture.baseWidth = width;
  12799. texture.baseHeight = height;
  12800. texture.baseDepth = depth;
  12801. texture.width = width;
  12802. texture.height = height;
  12803. texture.depth = depth;
  12804. texture.format = format;
  12805. texture.generateMipMaps = generateMipMaps;
  12806. texture.samplingMode = samplingMode;
  12807. texture.is3D = true;
  12808. if (!this._doNotHandleContextLost) {
  12809. texture._bufferView = data;
  12810. }
  12811. this.updateRawTexture3D(texture, data, format, invertY, compression);
  12812. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  12813. // Filters
  12814. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  12815. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  12816. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  12817. if (generateMipMaps) {
  12818. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  12819. }
  12820. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  12821. this._internalTexturesCache.push(texture);
  12822. return texture;
  12823. };
  12824. Engine.prototype._prepareWebGLTextureContinuation = function (texture, scene, noMipmap, isCompressed, samplingMode) {
  12825. var gl = this._gl;
  12826. if (!gl) {
  12827. return;
  12828. }
  12829. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  12830. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  12831. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  12832. if (!noMipmap && !isCompressed) {
  12833. gl.generateMipmap(gl.TEXTURE_2D);
  12834. }
  12835. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  12836. // this.resetTextureCache();
  12837. if (scene) {
  12838. scene._removePendingData(texture);
  12839. }
  12840. texture.onLoadedObservable.notifyObservers(texture);
  12841. texture.onLoadedObservable.clear();
  12842. };
  12843. Engine.prototype._prepareWebGLTexture = function (texture, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  12844. var _this = this;
  12845. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  12846. var potWidth = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this.getCaps().maxTextureSize) : width;
  12847. var potHeight = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this.getCaps().maxTextureSize) : height;
  12848. var gl = this._gl;
  12849. if (!gl) {
  12850. return;
  12851. }
  12852. if (!texture._webGLTexture) {
  12853. // this.resetTextureCache();
  12854. if (scene) {
  12855. scene._removePendingData(texture);
  12856. }
  12857. return;
  12858. }
  12859. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  12860. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  12861. texture.baseWidth = width;
  12862. texture.baseHeight = height;
  12863. texture.width = potWidth;
  12864. texture.height = potHeight;
  12865. texture.isReady = true;
  12866. if (processFunction(potWidth, potHeight, function () {
  12867. _this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  12868. })) {
  12869. // Returning as texture needs extra async steps
  12870. return;
  12871. }
  12872. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  12873. };
  12874. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  12875. // Create new RGBA data container.
  12876. var rgbaData;
  12877. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  12878. rgbaData = new Float32Array(width * height * 4);
  12879. }
  12880. else {
  12881. rgbaData = new Uint32Array(width * height * 4);
  12882. }
  12883. // Convert each pixel.
  12884. for (var x = 0; x < width; x++) {
  12885. for (var y = 0; y < height; y++) {
  12886. var index = (y * width + x) * 3;
  12887. var newIndex = (y * width + x) * 4;
  12888. // Map Old Value to new value.
  12889. rgbaData[newIndex + 0] = rgbData[index + 0];
  12890. rgbaData[newIndex + 1] = rgbData[index + 1];
  12891. rgbaData[newIndex + 2] = rgbData[index + 2];
  12892. // Add fully opaque alpha channel.
  12893. rgbaData[newIndex + 3] = 1;
  12894. }
  12895. }
  12896. return rgbaData;
  12897. };
  12898. Engine.prototype._releaseFramebufferObjects = function (texture) {
  12899. var gl = this._gl;
  12900. if (texture._framebuffer) {
  12901. gl.deleteFramebuffer(texture._framebuffer);
  12902. texture._framebuffer = null;
  12903. }
  12904. if (texture._depthStencilBuffer) {
  12905. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  12906. texture._depthStencilBuffer = null;
  12907. }
  12908. if (texture._MSAAFramebuffer) {
  12909. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  12910. texture._MSAAFramebuffer = null;
  12911. }
  12912. if (texture._MSAARenderBuffer) {
  12913. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  12914. texture._MSAARenderBuffer = null;
  12915. }
  12916. };
  12917. Engine.prototype._releaseTexture = function (texture) {
  12918. var gl = this._gl;
  12919. this._releaseFramebufferObjects(texture);
  12920. gl.deleteTexture(texture._webGLTexture);
  12921. // Unbind channels
  12922. this.unbindAllTextures();
  12923. var index = this._internalTexturesCache.indexOf(texture);
  12924. if (index !== -1) {
  12925. this._internalTexturesCache.splice(index, 1);
  12926. }
  12927. // Integrated fixed lod samplers.
  12928. if (texture._lodTextureHigh) {
  12929. texture._lodTextureHigh.dispose();
  12930. }
  12931. if (texture._lodTextureMid) {
  12932. texture._lodTextureMid.dispose();
  12933. }
  12934. if (texture._lodTextureLow) {
  12935. texture._lodTextureLow.dispose();
  12936. }
  12937. };
  12938. Engine.prototype.setProgram = function (program) {
  12939. if (this._currentProgram !== program) {
  12940. this._gl.useProgram(program);
  12941. this._currentProgram = program;
  12942. }
  12943. };
  12944. Engine.prototype.bindSamplers = function (effect) {
  12945. this.setProgram(effect.getProgram());
  12946. var samplers = effect.getSamplers();
  12947. for (var index = 0; index < samplers.length; index++) {
  12948. var uniform = effect.getUniform(samplers[index]);
  12949. if (uniform) {
  12950. this._boundUniforms[index] = uniform;
  12951. }
  12952. }
  12953. this._currentEffect = null;
  12954. };
  12955. Engine.prototype._moveBoundTextureOnTop = function (internalTexture) {
  12956. if (this.disableTextureBindingOptimization || this._lastBoundInternalTextureTracker.previous === internalTexture) {
  12957. return;
  12958. }
  12959. // Remove
  12960. this._linkTrackers(internalTexture.previous, internalTexture.next);
  12961. // Bind last to it
  12962. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, internalTexture);
  12963. // Bind to dummy
  12964. this._linkTrackers(internalTexture, this._lastBoundInternalTextureTracker);
  12965. };
  12966. Engine.prototype._getCorrectTextureChannel = function (channel, internalTexture) {
  12967. if (!internalTexture) {
  12968. return -1;
  12969. }
  12970. internalTexture._initialSlot = channel;
  12971. if (this.disableTextureBindingOptimization) {
  12972. if (channel !== internalTexture._designatedSlot) {
  12973. this._textureCollisions.addCount(1, false);
  12974. }
  12975. }
  12976. else {
  12977. if (channel !== internalTexture._designatedSlot) {
  12978. if (internalTexture._designatedSlot > -1) {
  12979. return internalTexture._designatedSlot;
  12980. }
  12981. else {
  12982. // No slot for this texture, let's pick a new one (if we find a free slot)
  12983. if (this._nextFreeTextureSlots.length) {
  12984. return this._nextFreeTextureSlots[0];
  12985. }
  12986. // We need to recycle the oldest bound texture, sorry.
  12987. this._textureCollisions.addCount(1, false);
  12988. return this._removeDesignatedSlot(this._firstBoundInternalTextureTracker.next);
  12989. }
  12990. }
  12991. }
  12992. return channel;
  12993. };
  12994. Engine.prototype._linkTrackers = function (previous, next) {
  12995. previous.next = next;
  12996. next.previous = previous;
  12997. };
  12998. Engine.prototype._removeDesignatedSlot = function (internalTexture) {
  12999. var currentSlot = internalTexture._designatedSlot;
  13000. if (currentSlot === -1) {
  13001. return -1;
  13002. }
  13003. internalTexture._designatedSlot = -1;
  13004. // Remove from bound list
  13005. this._linkTrackers(internalTexture.previous, internalTexture.next);
  13006. // Free the slot
  13007. this._boundTexturesCache[currentSlot] = null;
  13008. this._nextFreeTextureSlots.push(currentSlot);
  13009. return currentSlot;
  13010. };
  13011. Engine.prototype._activateCurrentTexture = function () {
  13012. if (this._currentTextureChannel !== this._activeChannel) {
  13013. this._gl.activeTexture(this._gl.TEXTURE0 + this._activeChannel);
  13014. this._currentTextureChannel = this._activeChannel;
  13015. }
  13016. };
  13017. Engine.prototype._bindTextureDirectly = function (target, texture, forTextureDataUpdate) {
  13018. if (forTextureDataUpdate === void 0) { forTextureDataUpdate = false; }
  13019. if (forTextureDataUpdate && texture && texture._designatedSlot > -1) {
  13020. this._activeChannel = texture._designatedSlot;
  13021. }
  13022. var currentTextureBound = this._boundTexturesCache[this._activeChannel];
  13023. var isTextureForRendering = texture && texture._initialSlot > -1;
  13024. if (currentTextureBound !== texture) {
  13025. if (currentTextureBound && !this.disableTextureBindingOptimization) {
  13026. this._removeDesignatedSlot(currentTextureBound);
  13027. }
  13028. this._activateCurrentTexture();
  13029. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  13030. this._boundTexturesCache[this._activeChannel] = texture;
  13031. if (texture) {
  13032. if (!this.disableTextureBindingOptimization) {
  13033. var slotIndex = this._nextFreeTextureSlots.indexOf(this._activeChannel);
  13034. if (slotIndex > -1) {
  13035. this._nextFreeTextureSlots.splice(slotIndex, 1);
  13036. }
  13037. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, texture);
  13038. this._linkTrackers(texture, this._lastBoundInternalTextureTracker);
  13039. }
  13040. texture._designatedSlot = this._activeChannel;
  13041. }
  13042. }
  13043. else if (forTextureDataUpdate) {
  13044. this._activateCurrentTexture();
  13045. }
  13046. if (isTextureForRendering && !forTextureDataUpdate) {
  13047. this._bindSamplerUniformToChannel(texture._initialSlot, this._activeChannel);
  13048. }
  13049. };
  13050. Engine.prototype._bindTexture = function (channel, texture) {
  13051. if (channel < 0) {
  13052. return;
  13053. }
  13054. if (texture) {
  13055. channel = this._getCorrectTextureChannel(channel, texture);
  13056. }
  13057. this._activeChannel = channel;
  13058. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  13059. };
  13060. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  13061. this._bindTexture(channel, postProcess ? postProcess._textures.data[postProcess._currentRenderTextureInd] : null);
  13062. };
  13063. Engine.prototype.unbindAllTextures = function () {
  13064. for (var channel = 0; channel < this._maxSimultaneousTextures; channel++) {
  13065. this._activeChannel = channel;
  13066. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13067. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  13068. if (this.webGLVersion > 1) {
  13069. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  13070. }
  13071. }
  13072. };
  13073. Engine.prototype.setTexture = function (channel, uniform, texture) {
  13074. if (channel < 0) {
  13075. return;
  13076. }
  13077. if (uniform) {
  13078. this._boundUniforms[channel] = uniform;
  13079. }
  13080. this._setTexture(channel, texture);
  13081. };
  13082. Engine.prototype._bindSamplerUniformToChannel = function (sourceSlot, destination) {
  13083. var uniform = this._boundUniforms[sourceSlot];
  13084. if (uniform._currentState === destination) {
  13085. return;
  13086. }
  13087. this._gl.uniform1i(uniform, destination);
  13088. uniform._currentState = destination;
  13089. };
  13090. Engine.prototype._setTexture = function (channel, texture, isPartOfTextureArray) {
  13091. if (isPartOfTextureArray === void 0) { isPartOfTextureArray = false; }
  13092. // Not ready?
  13093. if (!texture) {
  13094. if (this._boundTexturesCache[channel] != null) {
  13095. this._activeChannel = channel;
  13096. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13097. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  13098. if (this.webGLVersion > 1) {
  13099. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  13100. }
  13101. }
  13102. return false;
  13103. }
  13104. // Video
  13105. if (texture.video) {
  13106. this._activeChannel = channel;
  13107. texture.update();
  13108. }
  13109. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  13110. texture.delayLoad();
  13111. return false;
  13112. }
  13113. var internalTexture;
  13114. if (texture.isReady()) {
  13115. internalTexture = texture.getInternalTexture();
  13116. }
  13117. else if (texture.isCube) {
  13118. internalTexture = this.emptyCubeTexture;
  13119. }
  13120. else if (texture.is3D) {
  13121. internalTexture = this.emptyTexture3D;
  13122. }
  13123. else {
  13124. internalTexture = this.emptyTexture;
  13125. }
  13126. if (!isPartOfTextureArray) {
  13127. channel = this._getCorrectTextureChannel(channel, internalTexture);
  13128. }
  13129. if (this._boundTexturesCache[channel] === internalTexture) {
  13130. this._moveBoundTextureOnTop(internalTexture);
  13131. if (!isPartOfTextureArray) {
  13132. this._bindSamplerUniformToChannel(internalTexture._initialSlot, channel);
  13133. }
  13134. return false;
  13135. }
  13136. this._activeChannel = channel;
  13137. if (internalTexture && internalTexture.is3D) {
  13138. this._bindTextureDirectly(this._gl.TEXTURE_3D, internalTexture, isPartOfTextureArray);
  13139. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  13140. internalTexture._cachedWrapU = texture.wrapU;
  13141. switch (texture.wrapU) {
  13142. case BABYLON.Texture.WRAP_ADDRESSMODE:
  13143. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  13144. break;
  13145. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  13146. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  13147. break;
  13148. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  13149. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  13150. break;
  13151. }
  13152. }
  13153. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  13154. internalTexture._cachedWrapV = texture.wrapV;
  13155. switch (texture.wrapV) {
  13156. case BABYLON.Texture.WRAP_ADDRESSMODE:
  13157. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  13158. break;
  13159. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  13160. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  13161. break;
  13162. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  13163. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  13164. break;
  13165. }
  13166. }
  13167. if (internalTexture && internalTexture._cachedWrapR !== texture.wrapR) {
  13168. internalTexture._cachedWrapR = texture.wrapR;
  13169. switch (texture.wrapV) {
  13170. case BABYLON.Texture.WRAP_ADDRESSMODE:
  13171. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.REPEAT);
  13172. break;
  13173. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  13174. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.CLAMP_TO_EDGE);
  13175. break;
  13176. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  13177. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.MIRRORED_REPEAT);
  13178. break;
  13179. }
  13180. }
  13181. this._setAnisotropicLevel(this._gl.TEXTURE_3D, texture);
  13182. }
  13183. else if (internalTexture && internalTexture.isCube) {
  13184. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture, isPartOfTextureArray);
  13185. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  13186. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  13187. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  13188. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  13189. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  13190. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  13191. }
  13192. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  13193. }
  13194. else {
  13195. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture, isPartOfTextureArray);
  13196. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  13197. internalTexture._cachedWrapU = texture.wrapU;
  13198. switch (texture.wrapU) {
  13199. case BABYLON.Texture.WRAP_ADDRESSMODE:
  13200. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  13201. break;
  13202. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  13203. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  13204. break;
  13205. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  13206. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  13207. break;
  13208. }
  13209. }
  13210. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  13211. internalTexture._cachedWrapV = texture.wrapV;
  13212. switch (texture.wrapV) {
  13213. case BABYLON.Texture.WRAP_ADDRESSMODE:
  13214. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  13215. break;
  13216. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  13217. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  13218. break;
  13219. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  13220. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  13221. break;
  13222. }
  13223. }
  13224. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  13225. }
  13226. return true;
  13227. };
  13228. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  13229. if (channel < 0 || !uniform) {
  13230. return;
  13231. }
  13232. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  13233. this._textureUnits = new Int32Array(textures.length);
  13234. }
  13235. for (var i = 0; i < textures.length; i++) {
  13236. this._textureUnits[i] = this._getCorrectTextureChannel(channel + i, textures[i].getInternalTexture());
  13237. }
  13238. this._gl.uniform1iv(uniform, this._textureUnits);
  13239. for (var index = 0; index < textures.length; index++) {
  13240. this._setTexture(this._textureUnits[index], textures[index], true);
  13241. }
  13242. };
  13243. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  13244. var internalTexture = texture.getInternalTexture();
  13245. if (!internalTexture) {
  13246. return;
  13247. }
  13248. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  13249. var value = texture.anisotropicFilteringLevel;
  13250. if (internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST
  13251. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR
  13252. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR) {
  13253. value = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear
  13254. }
  13255. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  13256. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  13257. internalTexture._cachedAnisotropicFilteringLevel = value;
  13258. }
  13259. };
  13260. Engine.prototype.readPixels = function (x, y, width, height) {
  13261. var data = new Uint8Array(height * width * 4);
  13262. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  13263. return data;
  13264. };
  13265. /**
  13266. * Add an externaly attached data from its key.
  13267. * This method call will fail and return false, if such key already exists.
  13268. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  13269. * @param key the unique key that identifies the data
  13270. * @param data the data object to associate to the key for this Engine instance
  13271. * @return true if no such key were already present and the data was added successfully, false otherwise
  13272. */
  13273. Engine.prototype.addExternalData = function (key, data) {
  13274. if (!this._externalData) {
  13275. this._externalData = new BABYLON.StringDictionary();
  13276. }
  13277. return this._externalData.add(key, data);
  13278. };
  13279. /**
  13280. * Get an externaly attached data from its key
  13281. * @param key the unique key that identifies the data
  13282. * @return the associated data, if present (can be null), or undefined if not present
  13283. */
  13284. Engine.prototype.getExternalData = function (key) {
  13285. if (!this._externalData) {
  13286. this._externalData = new BABYLON.StringDictionary();
  13287. }
  13288. return this._externalData.get(key);
  13289. };
  13290. /**
  13291. * Get an externaly attached data from its key, create it using a factory if it's not already present
  13292. * @param key the unique key that identifies the data
  13293. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  13294. * @return the associated data, can be null if the factory returned null.
  13295. */
  13296. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  13297. if (!this._externalData) {
  13298. this._externalData = new BABYLON.StringDictionary();
  13299. }
  13300. return this._externalData.getOrAddWithFactory(key, factory);
  13301. };
  13302. /**
  13303. * Remove an externaly attached data from the Engine instance
  13304. * @param key the unique key that identifies the data
  13305. * @return true if the data was successfully removed, false if it doesn't exist
  13306. */
  13307. Engine.prototype.removeExternalData = function (key) {
  13308. if (!this._externalData) {
  13309. this._externalData = new BABYLON.StringDictionary();
  13310. }
  13311. return this._externalData.remove(key);
  13312. };
  13313. Engine.prototype.unbindAllAttributes = function () {
  13314. if (this._mustWipeVertexAttributes) {
  13315. this._mustWipeVertexAttributes = false;
  13316. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  13317. this._gl.disableVertexAttribArray(i);
  13318. this._vertexAttribArraysEnabled[i] = false;
  13319. this._currentBufferPointers[i].active = false;
  13320. }
  13321. return;
  13322. }
  13323. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  13324. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  13325. continue;
  13326. }
  13327. this._gl.disableVertexAttribArray(i);
  13328. this._vertexAttribArraysEnabled[i] = false;
  13329. this._currentBufferPointers[i].active = false;
  13330. }
  13331. };
  13332. Engine.prototype.releaseEffects = function () {
  13333. for (var name in this._compiledEffects) {
  13334. this._deleteProgram(this._compiledEffects[name]._program);
  13335. }
  13336. this._compiledEffects = {};
  13337. };
  13338. // Dispose
  13339. Engine.prototype.dispose = function () {
  13340. this.hideLoadingUI();
  13341. this.stopRenderLoop();
  13342. // Release postProcesses
  13343. while (this.postProcesses.length) {
  13344. this.postProcesses[0].dispose();
  13345. }
  13346. // Empty texture
  13347. if (this._emptyTexture) {
  13348. this._releaseTexture(this._emptyTexture);
  13349. this._emptyTexture = null;
  13350. }
  13351. if (this._emptyCubeTexture) {
  13352. this._releaseTexture(this._emptyCubeTexture);
  13353. this._emptyCubeTexture = null;
  13354. }
  13355. // Rescale PP
  13356. if (this._rescalePostProcess) {
  13357. this._rescalePostProcess.dispose();
  13358. }
  13359. // Release scenes
  13360. while (this.scenes.length) {
  13361. this.scenes[0].dispose();
  13362. }
  13363. // Release audio engine
  13364. if (Engine.audioEngine) {
  13365. Engine.audioEngine.dispose();
  13366. }
  13367. // Release effects
  13368. this.releaseEffects();
  13369. // Unbind
  13370. this.unbindAllAttributes();
  13371. if (this._dummyFramebuffer) {
  13372. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  13373. }
  13374. //WebVR
  13375. this.disableVR();
  13376. // Events
  13377. if (BABYLON.Tools.IsWindowObjectExist()) {
  13378. window.removeEventListener("blur", this._onBlur);
  13379. window.removeEventListener("focus", this._onFocus);
  13380. window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
  13381. window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
  13382. if (this._renderingCanvas) {
  13383. this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus);
  13384. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  13385. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasBlur);
  13386. if (!this._doNotHandleContextLost) {
  13387. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  13388. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  13389. }
  13390. }
  13391. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  13392. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  13393. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  13394. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  13395. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  13396. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  13397. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  13398. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  13399. if (this._onVrDisplayConnect) {
  13400. window.removeEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  13401. if (this._onVrDisplayDisconnect) {
  13402. window.removeEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  13403. }
  13404. if (this._onVrDisplayPresentChange) {
  13405. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  13406. }
  13407. this._onVrDisplayConnect = null;
  13408. this._onVrDisplayDisconnect = null;
  13409. }
  13410. }
  13411. // Remove from Instances
  13412. var index = Engine.Instances.indexOf(this);
  13413. if (index >= 0) {
  13414. Engine.Instances.splice(index, 1);
  13415. }
  13416. this._workingCanvas = null;
  13417. this._workingContext = null;
  13418. this._currentBufferPointers = [];
  13419. this._renderingCanvas = null;
  13420. this._currentProgram = null;
  13421. this.onResizeObservable.clear();
  13422. this.onCanvasBlurObservable.clear();
  13423. this.onCanvasFocusObservable.clear();
  13424. this.onCanvasPointerOutObservable.clear();
  13425. this.onBeginFrameObservable.clear();
  13426. this.onEndFrameObservable.clear();
  13427. BABYLON.Effect.ResetCache();
  13428. // Abort active requests
  13429. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  13430. var request = _a[_i];
  13431. request.abort();
  13432. }
  13433. };
  13434. // Loading screen
  13435. Engine.prototype.displayLoadingUI = function () {
  13436. if (!BABYLON.Tools.IsWindowObjectExist()) {
  13437. return;
  13438. }
  13439. var loadingScreen = this.loadingScreen;
  13440. if (loadingScreen) {
  13441. loadingScreen.displayLoadingUI();
  13442. }
  13443. };
  13444. Engine.prototype.hideLoadingUI = function () {
  13445. if (!BABYLON.Tools.IsWindowObjectExist()) {
  13446. return;
  13447. }
  13448. var loadingScreen = this.loadingScreen;
  13449. if (loadingScreen) {
  13450. loadingScreen.hideLoadingUI();
  13451. }
  13452. };
  13453. Object.defineProperty(Engine.prototype, "loadingScreen", {
  13454. get: function () {
  13455. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen && this._renderingCanvas)
  13456. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  13457. return this._loadingScreen;
  13458. },
  13459. set: function (loadingScreen) {
  13460. this._loadingScreen = loadingScreen;
  13461. },
  13462. enumerable: true,
  13463. configurable: true
  13464. });
  13465. Object.defineProperty(Engine.prototype, "loadingUIText", {
  13466. set: function (text) {
  13467. this.loadingScreen.loadingUIText = text;
  13468. },
  13469. enumerable: true,
  13470. configurable: true
  13471. });
  13472. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  13473. set: function (color) {
  13474. this.loadingScreen.loadingUIBackgroundColor = color;
  13475. },
  13476. enumerable: true,
  13477. configurable: true
  13478. });
  13479. Engine.prototype.attachContextLostEvent = function (callback) {
  13480. if (this._renderingCanvas) {
  13481. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  13482. }
  13483. };
  13484. Engine.prototype.attachContextRestoredEvent = function (callback) {
  13485. if (this._renderingCanvas) {
  13486. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  13487. }
  13488. };
  13489. Engine.prototype.getVertexShaderSource = function (program) {
  13490. var shaders = this._gl.getAttachedShaders(program);
  13491. if (!shaders) {
  13492. return null;
  13493. }
  13494. return this._gl.getShaderSource(shaders[0]);
  13495. };
  13496. Engine.prototype.getFragmentShaderSource = function (program) {
  13497. var shaders = this._gl.getAttachedShaders(program);
  13498. if (!shaders) {
  13499. return null;
  13500. }
  13501. return this._gl.getShaderSource(shaders[1]);
  13502. };
  13503. Engine.prototype.getError = function () {
  13504. return this._gl.getError();
  13505. };
  13506. // FPS
  13507. Engine.prototype.getFps = function () {
  13508. return this._fps;
  13509. };
  13510. Engine.prototype.getDeltaTime = function () {
  13511. return this._deltaTime;
  13512. };
  13513. Engine.prototype._measureFps = function () {
  13514. this._performanceMonitor.sampleFrame();
  13515. this._fps = this._performanceMonitor.averageFPS;
  13516. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  13517. };
  13518. Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex) {
  13519. if (faceIndex === void 0) { faceIndex = -1; }
  13520. var gl = this._gl;
  13521. if (!this._dummyFramebuffer) {
  13522. var dummy = gl.createFramebuffer();
  13523. if (!dummy) {
  13524. throw new Error("Unable to create dummy framebuffer");
  13525. }
  13526. this._dummyFramebuffer = dummy;
  13527. }
  13528. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  13529. if (faceIndex > -1) {
  13530. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  13531. }
  13532. else {
  13533. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  13534. }
  13535. var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  13536. var buffer;
  13537. switch (readType) {
  13538. case gl.UNSIGNED_BYTE:
  13539. buffer = new Uint8Array(4 * width * height);
  13540. readType = gl.UNSIGNED_BYTE;
  13541. break;
  13542. default:
  13543. buffer = new Float32Array(4 * width * height);
  13544. readType = gl.FLOAT;
  13545. break;
  13546. }
  13547. gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
  13548. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  13549. return buffer;
  13550. };
  13551. Engine.prototype._canRenderToFloatFramebuffer = function () {
  13552. if (this._webGLVersion > 1) {
  13553. return this._caps.colorBufferFloat;
  13554. }
  13555. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_FLOAT);
  13556. };
  13557. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  13558. if (this._webGLVersion > 1) {
  13559. return this._caps.colorBufferFloat;
  13560. }
  13561. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_HALF_FLOAT);
  13562. };
  13563. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  13564. Engine.prototype._canRenderToFramebuffer = function (type) {
  13565. var gl = this._gl;
  13566. //clear existing errors
  13567. while (gl.getError() !== gl.NO_ERROR) { }
  13568. var successful = true;
  13569. var texture = gl.createTexture();
  13570. gl.bindTexture(gl.TEXTURE_2D, texture);
  13571. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  13572. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  13573. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  13574. var fb = gl.createFramebuffer();
  13575. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  13576. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  13577. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  13578. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  13579. successful = successful && (gl.getError() === gl.NO_ERROR);
  13580. //try render by clearing frame buffer's color buffer
  13581. if (successful) {
  13582. gl.clear(gl.COLOR_BUFFER_BIT);
  13583. successful = successful && (gl.getError() === gl.NO_ERROR);
  13584. }
  13585. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  13586. if (successful) {
  13587. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  13588. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  13589. var readFormat = gl.RGBA;
  13590. var readType = gl.UNSIGNED_BYTE;
  13591. var buffer = new Uint8Array(4);
  13592. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  13593. successful = successful && (gl.getError() === gl.NO_ERROR);
  13594. }
  13595. //clean up
  13596. gl.deleteTexture(texture);
  13597. gl.deleteFramebuffer(fb);
  13598. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  13599. //clear accumulated errors
  13600. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  13601. return successful;
  13602. };
  13603. Engine.prototype._getWebGLTextureType = function (type) {
  13604. if (type === Engine.TEXTURETYPE_FLOAT) {
  13605. return this._gl.FLOAT;
  13606. }
  13607. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  13608. // Add Half Float Constant.
  13609. return this._gl.HALF_FLOAT_OES;
  13610. }
  13611. return this._gl.UNSIGNED_BYTE;
  13612. };
  13613. ;
  13614. Engine.prototype._getRGBABufferInternalSizedFormat = function (type) {
  13615. if (this._webGLVersion === 1) {
  13616. return this._gl.RGBA;
  13617. }
  13618. if (type === Engine.TEXTURETYPE_FLOAT) {
  13619. return this._gl.RGBA32F;
  13620. }
  13621. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  13622. return this._gl.RGBA16F;
  13623. }
  13624. return this._gl.RGBA;
  13625. };
  13626. ;
  13627. Engine.prototype._getRGBAMultiSampleBufferFormat = function (type) {
  13628. if (type === Engine.TEXTURETYPE_FLOAT) {
  13629. return this._gl.RGBA32F;
  13630. }
  13631. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  13632. return this._gl.RGBA16F;
  13633. }
  13634. return this._gl.RGBA8;
  13635. };
  13636. ;
  13637. Engine.prototype.createQuery = function () {
  13638. return this._gl.createQuery();
  13639. };
  13640. Engine.prototype.deleteQuery = function (query) {
  13641. this._gl.deleteQuery(query);
  13642. return this;
  13643. };
  13644. Engine.prototype.isQueryResultAvailable = function (query) {
  13645. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE);
  13646. };
  13647. Engine.prototype.getQueryResult = function (query) {
  13648. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT);
  13649. };
  13650. Engine.prototype.beginOcclusionQuery = function (algorithmType, query) {
  13651. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  13652. this._gl.beginQuery(glAlgorithm, query);
  13653. return this;
  13654. };
  13655. Engine.prototype.endOcclusionQuery = function (algorithmType) {
  13656. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  13657. this._gl.endQuery(glAlgorithm);
  13658. return this;
  13659. };
  13660. /* Time queries */
  13661. Engine.prototype._createTimeQuery = function () {
  13662. var timerQuery = this._caps.timerQuery;
  13663. if (timerQuery.createQueryEXT) {
  13664. return timerQuery.createQueryEXT();
  13665. }
  13666. return this.createQuery();
  13667. };
  13668. Engine.prototype._deleteTimeQuery = function (query) {
  13669. var timerQuery = this._caps.timerQuery;
  13670. if (timerQuery.deleteQueryEXT) {
  13671. timerQuery.deleteQueryEXT(query);
  13672. return;
  13673. }
  13674. this.deleteQuery(query);
  13675. };
  13676. Engine.prototype._getTimeQueryResult = function (query) {
  13677. var timerQuery = this._caps.timerQuery;
  13678. if (timerQuery.getQueryObjectEXT) {
  13679. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_EXT);
  13680. }
  13681. return this.getQueryResult(query);
  13682. };
  13683. Engine.prototype._getTimeQueryAvailability = function (query) {
  13684. var timerQuery = this._caps.timerQuery;
  13685. if (timerQuery.getQueryObjectEXT) {
  13686. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_AVAILABLE_EXT);
  13687. }
  13688. return this.isQueryResultAvailable(query);
  13689. };
  13690. Engine.prototype.startTimeQuery = function () {
  13691. var timerQuery = this._caps.timerQuery;
  13692. if (!timerQuery) {
  13693. return null;
  13694. }
  13695. var token = new BABYLON._TimeToken();
  13696. this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  13697. if (this._caps.canUseTimestampForTimerQuery) {
  13698. token._startTimeQuery = this._createTimeQuery();
  13699. timerQuery.queryCounterEXT(token._startTimeQuery, timerQuery.TIMESTAMP_EXT);
  13700. }
  13701. else {
  13702. if (this._currentNonTimestampToken) {
  13703. return this._currentNonTimestampToken;
  13704. }
  13705. token._timeElapsedQuery = this._createTimeQuery();
  13706. if (timerQuery.beginQueryEXT) {
  13707. timerQuery.beginQueryEXT(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  13708. }
  13709. else {
  13710. this._gl.beginQuery(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  13711. }
  13712. this._currentNonTimestampToken = token;
  13713. }
  13714. return token;
  13715. };
  13716. Engine.prototype.endTimeQuery = function (token) {
  13717. var timerQuery = this._caps.timerQuery;
  13718. if (!timerQuery || !token) {
  13719. return -1;
  13720. }
  13721. if (this._caps.canUseTimestampForTimerQuery) {
  13722. if (!token._startTimeQuery) {
  13723. return -1;
  13724. }
  13725. if (!token._endTimeQuery) {
  13726. token._endTimeQuery = this._createTimeQuery();
  13727. timerQuery.queryCounterEXT(token._endTimeQuery, timerQuery.TIMESTAMP_EXT);
  13728. }
  13729. }
  13730. else if (!token._timeElapsedQueryEnded) {
  13731. if (!token._timeElapsedQuery) {
  13732. return -1;
  13733. }
  13734. if (timerQuery.endQueryEXT) {
  13735. timerQuery.endQueryEXT(timerQuery.TIME_ELAPSED_EXT);
  13736. }
  13737. else {
  13738. this._gl.endQuery(timerQuery.TIME_ELAPSED_EXT);
  13739. }
  13740. token._timeElapsedQueryEnded = true;
  13741. }
  13742. var disjoint = this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  13743. var available = false;
  13744. if (token._endTimeQuery) {
  13745. available = this._getTimeQueryAvailability(token._endTimeQuery);
  13746. }
  13747. else if (token._timeElapsedQuery) {
  13748. available = this._getTimeQueryAvailability(token._timeElapsedQuery);
  13749. }
  13750. if (available && !disjoint) {
  13751. var result = 0;
  13752. if (this._caps.canUseTimestampForTimerQuery) {
  13753. if (!token._startTimeQuery || !token._endTimeQuery) {
  13754. return -1;
  13755. }
  13756. var timeStart = this._getTimeQueryResult(token._startTimeQuery);
  13757. var timeEnd = this._getTimeQueryResult(token._endTimeQuery);
  13758. result = timeEnd - timeStart;
  13759. this._deleteTimeQuery(token._startTimeQuery);
  13760. this._deleteTimeQuery(token._endTimeQuery);
  13761. token._startTimeQuery = null;
  13762. token._endTimeQuery = null;
  13763. }
  13764. else {
  13765. if (!token._timeElapsedQuery) {
  13766. return -1;
  13767. }
  13768. result = this._getTimeQueryResult(token._timeElapsedQuery);
  13769. this._deleteTimeQuery(token._timeElapsedQuery);
  13770. token._timeElapsedQuery = null;
  13771. token._timeElapsedQueryEnded = false;
  13772. this._currentNonTimestampToken = null;
  13773. }
  13774. return result;
  13775. }
  13776. return -1;
  13777. };
  13778. Engine.prototype.getGlAlgorithmType = function (algorithmType) {
  13779. return algorithmType === BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
  13780. };
  13781. // Transform feedback
  13782. Engine.prototype.createTransformFeedback = function () {
  13783. return this._gl.createTransformFeedback();
  13784. };
  13785. Engine.prototype.deleteTransformFeedback = function (value) {
  13786. this._gl.deleteTransformFeedback(value);
  13787. };
  13788. Engine.prototype.bindTransformFeedback = function (value) {
  13789. this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK, value);
  13790. };
  13791. Engine.prototype.beginTransformFeedback = function (usePoints) {
  13792. if (usePoints === void 0) { usePoints = true; }
  13793. this._gl.beginTransformFeedback(usePoints ? this._gl.POINTS : this._gl.TRIANGLES);
  13794. };
  13795. Engine.prototype.endTransformFeedback = function () {
  13796. this._gl.endTransformFeedback();
  13797. };
  13798. Engine.prototype.setTranformFeedbackVaryings = function (program, value) {
  13799. this._gl.transformFeedbackVaryings(program, value, this._gl.INTERLEAVED_ATTRIBS);
  13800. };
  13801. Engine.prototype.bindTransformFeedbackBuffer = function (value) {
  13802. this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER, 0, value);
  13803. };
  13804. Engine.prototype._loadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  13805. var _this = this;
  13806. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, database, useArrayBuffer, onError);
  13807. this._activeRequests.push(request);
  13808. request.onCompleteObservable.add(function (request) {
  13809. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  13810. });
  13811. return request;
  13812. };
  13813. /** @ignore */
  13814. Engine.prototype._loadFileAsync = function (url, database, useArrayBuffer) {
  13815. var _this = this;
  13816. return new Promise(function (resolve, reject) {
  13817. _this._loadFile(url, function (data) {
  13818. resolve(data);
  13819. }, undefined, database, useArrayBuffer, function (request, exception) {
  13820. reject(exception);
  13821. });
  13822. });
  13823. };
  13824. Engine.prototype._partialLoadFile = function (url, index, loadedFiles, scene, onfinish, onErrorCallBack) {
  13825. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  13826. var onload = function (data) {
  13827. loadedFiles[index] = data;
  13828. loadedFiles._internalCount++;
  13829. if (loadedFiles._internalCount === 6) {
  13830. onfinish(loadedFiles);
  13831. }
  13832. };
  13833. var onerror = function (request, exception) {
  13834. if (onErrorCallBack && request) {
  13835. onErrorCallBack(request.status + " " + request.statusText, exception);
  13836. }
  13837. };
  13838. this._loadFile(url, onload, undefined, undefined, true, onerror);
  13839. };
  13840. Engine.prototype._cascadeLoadFiles = function (rootUrl, scene, onfinish, files, onError) {
  13841. if (onError === void 0) { onError = null; }
  13842. var loadedFiles = [];
  13843. loadedFiles._internalCount = 0;
  13844. for (var index = 0; index < 6; index++) {
  13845. this._partialLoadFile(files[index], index, loadedFiles, scene, onfinish, onError);
  13846. }
  13847. };
  13848. // Statics
  13849. Engine.isSupported = function () {
  13850. try {
  13851. var tempcanvas = document.createElement("canvas");
  13852. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  13853. return gl != null && !!window.WebGLRenderingContext;
  13854. }
  13855. catch (e) {
  13856. return false;
  13857. }
  13858. };
  13859. /** Use this array to turn off some WebGL2 features on known buggy browsers version */
  13860. Engine.ExceptionList = [
  13861. { key: "Chrome/63.0", capture: "63\\.0\\.3239\\.(\\d+)", captureConstraint: 108, targets: ["uniformBuffer"] },
  13862. { key: "Firefox/58", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  13863. { key: "Macintosh", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  13864. ];
  13865. Engine.Instances = new Array();
  13866. // Const statics
  13867. Engine._ALPHA_DISABLE = 0;
  13868. Engine._ALPHA_ADD = 1;
  13869. Engine._ALPHA_COMBINE = 2;
  13870. Engine._ALPHA_SUBTRACT = 3;
  13871. Engine._ALPHA_MULTIPLY = 4;
  13872. Engine._ALPHA_MAXIMIZED = 5;
  13873. Engine._ALPHA_ONEONE = 6;
  13874. Engine._ALPHA_PREMULTIPLIED = 7;
  13875. Engine._ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  13876. Engine._ALPHA_INTERPOLATE = 9;
  13877. Engine._ALPHA_SCREENMODE = 10;
  13878. Engine._DELAYLOADSTATE_NONE = 0;
  13879. Engine._DELAYLOADSTATE_LOADED = 1;
  13880. Engine._DELAYLOADSTATE_LOADING = 2;
  13881. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  13882. Engine._TEXTUREFORMAT_ALPHA = 0;
  13883. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  13884. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  13885. Engine._TEXTUREFORMAT_RGB = 4;
  13886. Engine._TEXTUREFORMAT_RGBA = 5;
  13887. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  13888. Engine._TEXTURETYPE_FLOAT = 1;
  13889. Engine._TEXTURETYPE_HALF_FLOAT = 2;
  13890. // Depht or Stencil test Constants.
  13891. Engine._NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
  13892. 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.
  13893. 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.
  13894. 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.
  13895. 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.
  13896. 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.
  13897. 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.
  13898. 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.
  13899. // Stencil Actions Constants.
  13900. Engine._KEEP = 0x1E00;
  13901. Engine._REPLACE = 0x1E01;
  13902. Engine._INCR = 0x1E02;
  13903. Engine._DECR = 0x1E03;
  13904. Engine._INVERT = 0x150A;
  13905. Engine._INCR_WRAP = 0x8507;
  13906. Engine._DECR_WRAP = 0x8508;
  13907. // Texture rescaling mode
  13908. Engine._SCALEMODE_FLOOR = 1;
  13909. Engine._SCALEMODE_NEAREST = 2;
  13910. Engine._SCALEMODE_CEILING = 3;
  13911. // Updatable statics so stick with vars here
  13912. Engine.CollisionsEpsilon = 0.001;
  13913. Engine.CodeRepository = "src/";
  13914. Engine.ShadersRepository = "src/Shaders/";
  13915. return Engine;
  13916. }());
  13917. BABYLON.Engine = Engine;
  13918. })(BABYLON || (BABYLON = {}));
  13919. //# sourceMappingURL=babylon.engine.js.map
  13920. var BABYLON;
  13921. (function (BABYLON) {
  13922. /**
  13923. * Node is the basic class for all scene objects (Mesh, Light Camera).
  13924. */
  13925. var Node = /** @class */ (function () {
  13926. /**
  13927. * @constructor
  13928. * @param {string} name - the name and id to be given to this node
  13929. * @param {BABYLON.Scene} the scene this node will be added to
  13930. */
  13931. function Node(name, scene) {
  13932. if (scene === void 0) { scene = null; }
  13933. this.state = "";
  13934. this.metadata = null;
  13935. this.doNotSerialize = false;
  13936. this.animations = new Array();
  13937. this._ranges = {};
  13938. this._isEnabled = true;
  13939. this._isReady = true;
  13940. this._currentRenderId = -1;
  13941. this._parentRenderId = -1;
  13942. /**
  13943. * An event triggered when the mesh is disposed.
  13944. * @type {BABYLON.Observable}
  13945. */
  13946. this.onDisposeObservable = new BABYLON.Observable();
  13947. // Behaviors
  13948. this._behaviors = new Array();
  13949. this.name = name;
  13950. this.id = name;
  13951. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  13952. this.uniqueId = this._scene.getUniqueId();
  13953. this._initCache();
  13954. }
  13955. Object.defineProperty(Node.prototype, "parent", {
  13956. get: function () {
  13957. return this._parentNode;
  13958. },
  13959. set: function (parent) {
  13960. if (this._parentNode === parent) {
  13961. return;
  13962. }
  13963. // Remove self from list of children of parent
  13964. if (this._parentNode && this._parentNode._children !== undefined && this._parentNode._children !== null) {
  13965. var index = this._parentNode._children.indexOf(this);
  13966. if (index !== -1) {
  13967. this._parentNode._children.splice(index, 1);
  13968. }
  13969. }
  13970. // Store new parent
  13971. this._parentNode = parent;
  13972. // Add as child to new parent
  13973. if (this._parentNode) {
  13974. if (this._parentNode._children === undefined || this._parentNode._children === null) {
  13975. this._parentNode._children = new Array();
  13976. }
  13977. this._parentNode._children.push(this);
  13978. }
  13979. },
  13980. enumerable: true,
  13981. configurable: true
  13982. });
  13983. Node.prototype.getClassName = function () {
  13984. return "Node";
  13985. };
  13986. Object.defineProperty(Node.prototype, "onDispose", {
  13987. set: function (callback) {
  13988. if (this._onDisposeObserver) {
  13989. this.onDisposeObservable.remove(this._onDisposeObserver);
  13990. }
  13991. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  13992. },
  13993. enumerable: true,
  13994. configurable: true
  13995. });
  13996. Node.prototype.getScene = function () {
  13997. return this._scene;
  13998. };
  13999. Node.prototype.getEngine = function () {
  14000. return this._scene.getEngine();
  14001. };
  14002. Node.prototype.addBehavior = function (behavior) {
  14003. var _this = this;
  14004. var index = this._behaviors.indexOf(behavior);
  14005. if (index !== -1) {
  14006. return this;
  14007. }
  14008. behavior.init();
  14009. if (this._scene.isLoading) {
  14010. // We defer the attach when the scene will be loaded
  14011. var observer = this._scene.onDataLoadedObservable.add(function () {
  14012. behavior.attach(_this);
  14013. setTimeout(function () {
  14014. // Need to use a timeout to avoid removing an observer while iterating the list of observers
  14015. _this._scene.onDataLoadedObservable.remove(observer);
  14016. }, 0);
  14017. });
  14018. }
  14019. else {
  14020. behavior.attach(this);
  14021. }
  14022. this._behaviors.push(behavior);
  14023. return this;
  14024. };
  14025. Node.prototype.removeBehavior = function (behavior) {
  14026. var index = this._behaviors.indexOf(behavior);
  14027. if (index === -1) {
  14028. return this;
  14029. }
  14030. this._behaviors[index].detach();
  14031. this._behaviors.splice(index, 1);
  14032. return this;
  14033. };
  14034. Object.defineProperty(Node.prototype, "behaviors", {
  14035. get: function () {
  14036. return this._behaviors;
  14037. },
  14038. enumerable: true,
  14039. configurable: true
  14040. });
  14041. Node.prototype.getBehaviorByName = function (name) {
  14042. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  14043. var behavior = _a[_i];
  14044. if (behavior.name === name) {
  14045. return behavior;
  14046. }
  14047. }
  14048. return null;
  14049. };
  14050. // override it in derived class
  14051. Node.prototype.getWorldMatrix = function () {
  14052. return BABYLON.Matrix.Identity();
  14053. };
  14054. // override it in derived class if you add new variables to the cache
  14055. // and call the parent class method
  14056. Node.prototype._initCache = function () {
  14057. this._cache = {};
  14058. this._cache.parent = undefined;
  14059. };
  14060. Node.prototype.updateCache = function (force) {
  14061. if (!force && this.isSynchronized())
  14062. return;
  14063. this._cache.parent = this.parent;
  14064. this._updateCache();
  14065. };
  14066. // override it in derived class if you add new variables to the cache
  14067. // and call the parent class method if !ignoreParentClass
  14068. Node.prototype._updateCache = function (ignoreParentClass) {
  14069. };
  14070. // override it in derived class if you add new variables to the cache
  14071. Node.prototype._isSynchronized = function () {
  14072. return true;
  14073. };
  14074. Node.prototype._markSyncedWithParent = function () {
  14075. if (this.parent) {
  14076. this._parentRenderId = this.parent._currentRenderId;
  14077. }
  14078. };
  14079. Node.prototype.isSynchronizedWithParent = function () {
  14080. if (!this.parent) {
  14081. return true;
  14082. }
  14083. if (this._parentRenderId !== this.parent._currentRenderId) {
  14084. return false;
  14085. }
  14086. return this.parent.isSynchronized();
  14087. };
  14088. Node.prototype.isSynchronized = function (updateCache) {
  14089. var check = this.hasNewParent();
  14090. check = check || !this.isSynchronizedWithParent();
  14091. check = check || !this._isSynchronized();
  14092. if (updateCache)
  14093. this.updateCache(true);
  14094. return !check;
  14095. };
  14096. Node.prototype.hasNewParent = function (update) {
  14097. if (this._cache.parent === this.parent)
  14098. return false;
  14099. if (update)
  14100. this._cache.parent = this.parent;
  14101. return true;
  14102. };
  14103. /**
  14104. * Is this node ready to be used/rendered
  14105. * @return {boolean} is it ready
  14106. */
  14107. Node.prototype.isReady = function () {
  14108. return this._isReady;
  14109. };
  14110. /**
  14111. * Is this node enabled.
  14112. * If the node has a parent, all ancestors will be checked and false will be returned if any are false (not enabled), otherwise will return true.
  14113. * @param {boolean} [checkAncestors=true] - Indicates if this method should check the ancestors. The default is to check the ancestors. If set to false, the method will return the value of this node without checking ancestors.
  14114. * @return {boolean} whether this node (and its parent) is enabled.
  14115. * @see setEnabled
  14116. */
  14117. Node.prototype.isEnabled = function (checkAncestors) {
  14118. if (checkAncestors === void 0) { checkAncestors = true; }
  14119. if (checkAncestors === false) {
  14120. return this._isEnabled;
  14121. }
  14122. if (this._isEnabled === false) {
  14123. return false;
  14124. }
  14125. if (this.parent !== undefined && this.parent !== null) {
  14126. return this.parent.isEnabled(checkAncestors);
  14127. }
  14128. return true;
  14129. };
  14130. /**
  14131. * Set the enabled state of this node.
  14132. * @param {boolean} value - the new enabled state
  14133. * @see isEnabled
  14134. */
  14135. Node.prototype.setEnabled = function (value) {
  14136. this._isEnabled = value;
  14137. };
  14138. /**
  14139. * Is this node a descendant of the given node.
  14140. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined.
  14141. * @param {BABYLON.Node} ancestor - The parent node to inspect
  14142. * @see parent
  14143. */
  14144. Node.prototype.isDescendantOf = function (ancestor) {
  14145. if (this.parent) {
  14146. if (this.parent === ancestor) {
  14147. return true;
  14148. }
  14149. return this.parent.isDescendantOf(ancestor);
  14150. }
  14151. return false;
  14152. };
  14153. /**
  14154. * Evaluate the list of children and determine if they should be considered as descendants considering the given criterias
  14155. * @param {BABYLON.Node[]} results the result array containing the nodes matching the given criterias
  14156. * @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.
  14157. * @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.
  14158. */
  14159. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  14160. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  14161. if (!this._children) {
  14162. return;
  14163. }
  14164. for (var index = 0; index < this._children.length; index++) {
  14165. var item = this._children[index];
  14166. if (!predicate || predicate(item)) {
  14167. results.push(item);
  14168. }
  14169. if (!directDescendantsOnly) {
  14170. item._getDescendants(results, false, predicate);
  14171. }
  14172. }
  14173. };
  14174. /**
  14175. * Will return all nodes that have this node as ascendant.
  14176. * @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.
  14177. * @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.
  14178. * @return {BABYLON.Node[]} all children nodes of all types.
  14179. */
  14180. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  14181. var results = new Array();
  14182. this._getDescendants(results, directDescendantsOnly, predicate);
  14183. return results;
  14184. };
  14185. /**
  14186. * Get all child-meshes of this node.
  14187. */
  14188. Node.prototype.getChildMeshes = function (directDescendantsOnly, predicate) {
  14189. var results = [];
  14190. this._getDescendants(results, directDescendantsOnly, function (node) {
  14191. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  14192. });
  14193. return results;
  14194. };
  14195. /**
  14196. * Get all child-transformNodes of this node.
  14197. */
  14198. Node.prototype.getChildTransformNodes = function (directDescendantsOnly, predicate) {
  14199. var results = [];
  14200. this._getDescendants(results, directDescendantsOnly, function (node) {
  14201. return ((!predicate || predicate(node)) && (node instanceof BABYLON.TransformNode));
  14202. });
  14203. return results;
  14204. };
  14205. /**
  14206. * Get all direct children of this node.
  14207. */
  14208. Node.prototype.getChildren = function (predicate) {
  14209. return this.getDescendants(true, predicate);
  14210. };
  14211. Node.prototype._setReady = function (state) {
  14212. if (state === this._isReady) {
  14213. return;
  14214. }
  14215. if (!state) {
  14216. this._isReady = false;
  14217. return;
  14218. }
  14219. this._isReady = true;
  14220. if (this.onReady) {
  14221. this.onReady(this);
  14222. }
  14223. };
  14224. Node.prototype.getAnimationByName = function (name) {
  14225. for (var i = 0; i < this.animations.length; i++) {
  14226. var animation = this.animations[i];
  14227. if (animation.name === name) {
  14228. return animation;
  14229. }
  14230. }
  14231. return null;
  14232. };
  14233. Node.prototype.createAnimationRange = function (name, from, to) {
  14234. // check name not already in use
  14235. if (!this._ranges[name]) {
  14236. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  14237. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  14238. if (this.animations[i]) {
  14239. this.animations[i].createRange(name, from, to);
  14240. }
  14241. }
  14242. }
  14243. };
  14244. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  14245. if (deleteFrames === void 0) { deleteFrames = true; }
  14246. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  14247. if (this.animations[i]) {
  14248. this.animations[i].deleteRange(name, deleteFrames);
  14249. }
  14250. }
  14251. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  14252. };
  14253. Node.prototype.getAnimationRange = function (name) {
  14254. return this._ranges[name];
  14255. };
  14256. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  14257. var range = this.getAnimationRange(name);
  14258. if (!range) {
  14259. return;
  14260. }
  14261. this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  14262. };
  14263. Node.prototype.serializeAnimationRanges = function () {
  14264. var serializationRanges = [];
  14265. for (var name in this._ranges) {
  14266. var localRange = this._ranges[name];
  14267. if (!localRange) {
  14268. continue;
  14269. }
  14270. var range = {};
  14271. range.name = name;
  14272. range.from = localRange.from;
  14273. range.to = localRange.to;
  14274. serializationRanges.push(range);
  14275. }
  14276. return serializationRanges;
  14277. };
  14278. // override it in derived class
  14279. Node.prototype.computeWorldMatrix = function (force) {
  14280. return BABYLON.Matrix.Identity();
  14281. };
  14282. Node.prototype.dispose = function () {
  14283. this.parent = null;
  14284. // Callback
  14285. this.onDisposeObservable.notifyObservers(this);
  14286. this.onDisposeObservable.clear();
  14287. // Behaviors
  14288. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  14289. var behavior = _a[_i];
  14290. behavior.detach();
  14291. }
  14292. this._behaviors = [];
  14293. };
  14294. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  14295. if (parsedNode.ranges) {
  14296. for (var index = 0; index < parsedNode.ranges.length; index++) {
  14297. var data = parsedNode.ranges[index];
  14298. node.createAnimationRange(data.name, data.from, data.to);
  14299. }
  14300. }
  14301. };
  14302. __decorate([
  14303. BABYLON.serialize()
  14304. ], Node.prototype, "name", void 0);
  14305. __decorate([
  14306. BABYLON.serialize()
  14307. ], Node.prototype, "id", void 0);
  14308. __decorate([
  14309. BABYLON.serialize()
  14310. ], Node.prototype, "uniqueId", void 0);
  14311. __decorate([
  14312. BABYLON.serialize()
  14313. ], Node.prototype, "state", void 0);
  14314. __decorate([
  14315. BABYLON.serialize()
  14316. ], Node.prototype, "metadata", void 0);
  14317. return Node;
  14318. }());
  14319. BABYLON.Node = Node;
  14320. })(BABYLON || (BABYLON = {}));
  14321. //# sourceMappingURL=babylon.node.js.map
  14322. var BABYLON;
  14323. (function (BABYLON) {
  14324. var BoundingSphere = /** @class */ (function () {
  14325. function BoundingSphere(minimum, maximum) {
  14326. this.minimum = minimum;
  14327. this.maximum = maximum;
  14328. this._tempRadiusVector = BABYLON.Vector3.Zero();
  14329. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  14330. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  14331. this.radius = distance * 0.5;
  14332. this.centerWorld = BABYLON.Vector3.Zero();
  14333. this._update(BABYLON.Matrix.Identity());
  14334. }
  14335. // Methods
  14336. BoundingSphere.prototype._update = function (world) {
  14337. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  14338. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  14339. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  14340. };
  14341. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  14342. for (var i = 0; i < 6; i++) {
  14343. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  14344. return false;
  14345. }
  14346. return true;
  14347. };
  14348. BoundingSphere.prototype.intersectsPoint = function (point) {
  14349. var x = this.centerWorld.x - point.x;
  14350. var y = this.centerWorld.y - point.y;
  14351. var z = this.centerWorld.z - point.z;
  14352. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  14353. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  14354. return false;
  14355. return true;
  14356. };
  14357. // Statics
  14358. BoundingSphere.Intersects = function (sphere0, sphere1) {
  14359. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  14360. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  14361. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  14362. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  14363. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  14364. return false;
  14365. return true;
  14366. };
  14367. return BoundingSphere;
  14368. }());
  14369. BABYLON.BoundingSphere = BoundingSphere;
  14370. })(BABYLON || (BABYLON = {}));
  14371. //# sourceMappingURL=babylon.boundingSphere.js.map
  14372. var BABYLON;
  14373. (function (BABYLON) {
  14374. var BoundingBox = /** @class */ (function () {
  14375. function BoundingBox(minimum, maximum) {
  14376. this.minimum = minimum;
  14377. this.maximum = maximum;
  14378. this.vectors = new Array();
  14379. this.vectorsWorld = new Array();
  14380. // Bounding vectors
  14381. this.vectors.push(this.minimum.clone());
  14382. this.vectors.push(this.maximum.clone());
  14383. this.vectors.push(this.minimum.clone());
  14384. this.vectors[2].x = this.maximum.x;
  14385. this.vectors.push(this.minimum.clone());
  14386. this.vectors[3].y = this.maximum.y;
  14387. this.vectors.push(this.minimum.clone());
  14388. this.vectors[4].z = this.maximum.z;
  14389. this.vectors.push(this.maximum.clone());
  14390. this.vectors[5].z = this.minimum.z;
  14391. this.vectors.push(this.maximum.clone());
  14392. this.vectors[6].x = this.minimum.x;
  14393. this.vectors.push(this.maximum.clone());
  14394. this.vectors[7].y = this.minimum.y;
  14395. // OBB
  14396. this.center = this.maximum.add(this.minimum).scale(0.5);
  14397. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  14398. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  14399. // World
  14400. for (var index = 0; index < this.vectors.length; index++) {
  14401. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  14402. }
  14403. this.minimumWorld = BABYLON.Vector3.Zero();
  14404. this.maximumWorld = BABYLON.Vector3.Zero();
  14405. this.centerWorld = BABYLON.Vector3.Zero();
  14406. this.extendSizeWorld = BABYLON.Vector3.Zero();
  14407. this._update(BABYLON.Matrix.Identity());
  14408. }
  14409. // Methods
  14410. BoundingBox.prototype.getWorldMatrix = function () {
  14411. return this._worldMatrix;
  14412. };
  14413. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  14414. this._worldMatrix.copyFrom(matrix);
  14415. return this;
  14416. };
  14417. BoundingBox.prototype._update = function (world) {
  14418. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  14419. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  14420. for (var index = 0; index < this.vectors.length; index++) {
  14421. var v = this.vectorsWorld[index];
  14422. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  14423. if (v.x < this.minimumWorld.x)
  14424. this.minimumWorld.x = v.x;
  14425. if (v.y < this.minimumWorld.y)
  14426. this.minimumWorld.y = v.y;
  14427. if (v.z < this.minimumWorld.z)
  14428. this.minimumWorld.z = v.z;
  14429. if (v.x > this.maximumWorld.x)
  14430. this.maximumWorld.x = v.x;
  14431. if (v.y > this.maximumWorld.y)
  14432. this.maximumWorld.y = v.y;
  14433. if (v.z > this.maximumWorld.z)
  14434. this.maximumWorld.z = v.z;
  14435. }
  14436. // Extend
  14437. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  14438. this.extendSizeWorld.scaleInPlace(0.5);
  14439. // OBB
  14440. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  14441. this.centerWorld.scaleInPlace(0.5);
  14442. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  14443. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  14444. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  14445. this._worldMatrix = world;
  14446. };
  14447. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  14448. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  14449. };
  14450. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  14451. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  14452. };
  14453. BoundingBox.prototype.intersectsPoint = function (point) {
  14454. var delta = -BABYLON.Epsilon;
  14455. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  14456. return false;
  14457. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  14458. return false;
  14459. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  14460. return false;
  14461. return true;
  14462. };
  14463. BoundingBox.prototype.intersectsSphere = function (sphere) {
  14464. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  14465. };
  14466. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  14467. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  14468. return false;
  14469. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  14470. return false;
  14471. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  14472. return false;
  14473. return true;
  14474. };
  14475. // Statics
  14476. BoundingBox.Intersects = function (box0, box1) {
  14477. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  14478. return false;
  14479. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  14480. return false;
  14481. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  14482. return false;
  14483. return true;
  14484. };
  14485. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  14486. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  14487. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  14488. return (num <= (sphereRadius * sphereRadius));
  14489. };
  14490. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  14491. for (var p = 0; p < 6; p++) {
  14492. for (var i = 0; i < 8; i++) {
  14493. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  14494. return false;
  14495. }
  14496. }
  14497. }
  14498. return true;
  14499. };
  14500. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  14501. for (var p = 0; p < 6; p++) {
  14502. var inCount = 8;
  14503. for (var i = 0; i < 8; i++) {
  14504. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  14505. --inCount;
  14506. }
  14507. else {
  14508. break;
  14509. }
  14510. }
  14511. if (inCount === 0)
  14512. return false;
  14513. }
  14514. return true;
  14515. };
  14516. return BoundingBox;
  14517. }());
  14518. BABYLON.BoundingBox = BoundingBox;
  14519. })(BABYLON || (BABYLON = {}));
  14520. //# sourceMappingURL=babylon.boundingBox.js.map
  14521. var BABYLON;
  14522. (function (BABYLON) {
  14523. var computeBoxExtents = function (axis, box) {
  14524. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  14525. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  14526. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  14527. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  14528. var r = r0 + r1 + r2;
  14529. return {
  14530. min: p - r,
  14531. max: p + r
  14532. };
  14533. };
  14534. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  14535. var axisOverlap = function (axis, box0, box1) {
  14536. var result0 = computeBoxExtents(axis, box0);
  14537. var result1 = computeBoxExtents(axis, box1);
  14538. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  14539. };
  14540. var BoundingInfo = /** @class */ (function () {
  14541. function BoundingInfo(minimum, maximum) {
  14542. this.minimum = minimum;
  14543. this.maximum = maximum;
  14544. this._isLocked = false;
  14545. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  14546. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  14547. }
  14548. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  14549. get: function () {
  14550. return this._isLocked;
  14551. },
  14552. set: function (value) {
  14553. this._isLocked = value;
  14554. },
  14555. enumerable: true,
  14556. configurable: true
  14557. });
  14558. // Methods
  14559. BoundingInfo.prototype.update = function (world) {
  14560. if (this._isLocked) {
  14561. return;
  14562. }
  14563. this.boundingBox._update(world);
  14564. this.boundingSphere._update(world);
  14565. };
  14566. /**
  14567. * Recreate the bounding info to be centered around a specific point given a specific extend.
  14568. * @param center New center of the bounding info
  14569. * @param extend New extend of the bounding info
  14570. */
  14571. BoundingInfo.prototype.centerOn = function (center, extend) {
  14572. this.minimum = center.subtract(extend);
  14573. this.maximum = center.add(extend);
  14574. this.boundingBox = new BABYLON.BoundingBox(this.minimum, this.maximum);
  14575. this.boundingSphere = new BABYLON.BoundingSphere(this.minimum, this.maximum);
  14576. return this;
  14577. };
  14578. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  14579. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  14580. return false;
  14581. return this.boundingBox.isInFrustum(frustumPlanes);
  14582. };
  14583. Object.defineProperty(BoundingInfo.prototype, "diagonalLength", {
  14584. /**
  14585. * Gets the world distance between the min and max points of the bounding box
  14586. */
  14587. get: function () {
  14588. var boundingBox = this.boundingBox;
  14589. var size = boundingBox.maximumWorld.subtract(boundingBox.minimumWorld);
  14590. return size.length();
  14591. },
  14592. enumerable: true,
  14593. configurable: true
  14594. });
  14595. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  14596. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  14597. };
  14598. BoundingInfo.prototype._checkCollision = function (collider) {
  14599. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  14600. };
  14601. BoundingInfo.prototype.intersectsPoint = function (point) {
  14602. if (!this.boundingSphere.centerWorld) {
  14603. return false;
  14604. }
  14605. if (!this.boundingSphere.intersectsPoint(point)) {
  14606. return false;
  14607. }
  14608. if (!this.boundingBox.intersectsPoint(point)) {
  14609. return false;
  14610. }
  14611. return true;
  14612. };
  14613. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  14614. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  14615. return false;
  14616. }
  14617. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  14618. return false;
  14619. }
  14620. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  14621. return false;
  14622. }
  14623. if (!precise) {
  14624. return true;
  14625. }
  14626. var box0 = this.boundingBox;
  14627. var box1 = boundingInfo.boundingBox;
  14628. if (!axisOverlap(box0.directions[0], box0, box1))
  14629. return false;
  14630. if (!axisOverlap(box0.directions[1], box0, box1))
  14631. return false;
  14632. if (!axisOverlap(box0.directions[2], box0, box1))
  14633. return false;
  14634. if (!axisOverlap(box1.directions[0], box0, box1))
  14635. return false;
  14636. if (!axisOverlap(box1.directions[1], box0, box1))
  14637. return false;
  14638. if (!axisOverlap(box1.directions[2], box0, box1))
  14639. return false;
  14640. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  14641. return false;
  14642. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  14643. return false;
  14644. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  14645. return false;
  14646. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  14647. return false;
  14648. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  14649. return false;
  14650. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  14651. return false;
  14652. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  14653. return false;
  14654. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  14655. return false;
  14656. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  14657. return false;
  14658. return true;
  14659. };
  14660. return BoundingInfo;
  14661. }());
  14662. BABYLON.BoundingInfo = BoundingInfo;
  14663. })(BABYLON || (BABYLON = {}));
  14664. //# sourceMappingURL=babylon.boundingInfo.js.map
  14665. var BABYLON;
  14666. (function (BABYLON) {
  14667. var TransformNode = /** @class */ (function (_super) {
  14668. __extends(TransformNode, _super);
  14669. function TransformNode(name, scene, isPure) {
  14670. if (scene === void 0) { scene = null; }
  14671. if (isPure === void 0) { isPure = true; }
  14672. var _this = _super.call(this, name, scene) || this;
  14673. // Properties
  14674. _this._rotation = BABYLON.Vector3.Zero();
  14675. _this._scaling = BABYLON.Vector3.One();
  14676. _this._isDirty = false;
  14677. _this.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_NONE;
  14678. _this.scalingDeterminant = 1;
  14679. _this.infiniteDistance = false;
  14680. _this.position = BABYLON.Vector3.Zero();
  14681. _this._localWorld = BABYLON.Matrix.Zero();
  14682. _this._worldMatrix = BABYLON.Matrix.Zero();
  14683. _this._worldMatrixDeterminant = 0;
  14684. _this._absolutePosition = BABYLON.Vector3.Zero();
  14685. _this._pivotMatrix = BABYLON.Matrix.Identity();
  14686. _this._postMultiplyPivotMatrix = false;
  14687. _this._isWorldMatrixFrozen = false;
  14688. /**
  14689. * An event triggered after the world matrix is updated
  14690. * @type {BABYLON.Observable}
  14691. */
  14692. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  14693. _this._nonUniformScaling = false;
  14694. if (isPure) {
  14695. _this.getScene().addTransformNode(_this);
  14696. }
  14697. return _this;
  14698. }
  14699. Object.defineProperty(TransformNode.prototype, "rotation", {
  14700. /**
  14701. * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.
  14702. * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!
  14703. * Default : (0.0, 0.0, 0.0)
  14704. */
  14705. get: function () {
  14706. return this._rotation;
  14707. },
  14708. set: function (newRotation) {
  14709. this._rotation = newRotation;
  14710. },
  14711. enumerable: true,
  14712. configurable: true
  14713. });
  14714. Object.defineProperty(TransformNode.prototype, "scaling", {
  14715. /**
  14716. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  14717. * Default : (1.0, 1.0, 1.0)
  14718. */
  14719. get: function () {
  14720. return this._scaling;
  14721. },
  14722. /**
  14723. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  14724. * Default : (1.0, 1.0, 1.0)
  14725. */
  14726. set: function (newScaling) {
  14727. this._scaling = newScaling;
  14728. },
  14729. enumerable: true,
  14730. configurable: true
  14731. });
  14732. Object.defineProperty(TransformNode.prototype, "rotationQuaternion", {
  14733. /**
  14734. * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.
  14735. * It's null by default.
  14736. * 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)
  14737. */
  14738. get: function () {
  14739. return this._rotationQuaternion;
  14740. },
  14741. set: function (quaternion) {
  14742. this._rotationQuaternion = quaternion;
  14743. //reset the rotation vector.
  14744. if (quaternion && this.rotation.length()) {
  14745. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  14746. }
  14747. },
  14748. enumerable: true,
  14749. configurable: true
  14750. });
  14751. /**
  14752. * Returns the latest update of the World matrix
  14753. * Returns a Matrix.
  14754. */
  14755. TransformNode.prototype.getWorldMatrix = function () {
  14756. if (this._currentRenderId !== this.getScene().getRenderId()) {
  14757. this.computeWorldMatrix();
  14758. }
  14759. return this._worldMatrix;
  14760. };
  14761. /**
  14762. * Returns the latest update of the World matrix determinant.
  14763. */
  14764. TransformNode.prototype._getWorldMatrixDeterminant = function () {
  14765. return this._worldMatrixDeterminant;
  14766. };
  14767. Object.defineProperty(TransformNode.prototype, "worldMatrixFromCache", {
  14768. /**
  14769. * Returns directly the latest state of the mesh World matrix.
  14770. * A Matrix is returned.
  14771. */
  14772. get: function () {
  14773. return this._worldMatrix;
  14774. },
  14775. enumerable: true,
  14776. configurable: true
  14777. });
  14778. /**
  14779. * Copies the paramater passed Matrix into the mesh Pose matrix.
  14780. * Returns the AbstractMesh.
  14781. */
  14782. TransformNode.prototype.updatePoseMatrix = function (matrix) {
  14783. this._poseMatrix.copyFrom(matrix);
  14784. return this;
  14785. };
  14786. /**
  14787. * Returns the mesh Pose matrix.
  14788. * Returned object : Matrix
  14789. */
  14790. TransformNode.prototype.getPoseMatrix = function () {
  14791. return this._poseMatrix;
  14792. };
  14793. TransformNode.prototype._isSynchronized = function () {
  14794. if (this._isDirty) {
  14795. return false;
  14796. }
  14797. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== BABYLON.AbstractMesh.BILLBOARDMODE_NONE)
  14798. return false;
  14799. if (this._cache.pivotMatrixUpdated) {
  14800. return false;
  14801. }
  14802. if (this.infiniteDistance) {
  14803. return false;
  14804. }
  14805. if (!this._cache.position.equals(this.position))
  14806. return false;
  14807. if (this.rotationQuaternion) {
  14808. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  14809. return false;
  14810. }
  14811. if (!this._cache.rotation.equals(this.rotation))
  14812. return false;
  14813. if (!this._cache.scaling.equals(this.scaling))
  14814. return false;
  14815. return true;
  14816. };
  14817. TransformNode.prototype._initCache = function () {
  14818. _super.prototype._initCache.call(this);
  14819. this._cache.localMatrixUpdated = false;
  14820. this._cache.position = BABYLON.Vector3.Zero();
  14821. this._cache.scaling = BABYLON.Vector3.Zero();
  14822. this._cache.rotation = BABYLON.Vector3.Zero();
  14823. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  14824. this._cache.billboardMode = -1;
  14825. };
  14826. TransformNode.prototype.markAsDirty = function (property) {
  14827. if (property === "rotation") {
  14828. this.rotationQuaternion = null;
  14829. }
  14830. this._currentRenderId = Number.MAX_VALUE;
  14831. this._isDirty = true;
  14832. return this;
  14833. };
  14834. Object.defineProperty(TransformNode.prototype, "absolutePosition", {
  14835. /**
  14836. * Returns the current mesh absolute position.
  14837. * Retuns a Vector3.
  14838. */
  14839. get: function () {
  14840. return this._absolutePosition;
  14841. },
  14842. enumerable: true,
  14843. configurable: true
  14844. });
  14845. /**
  14846. * Sets a new pivot matrix to the mesh.
  14847. * Returns the AbstractMesh.
  14848. */
  14849. TransformNode.prototype.setPivotMatrix = function (matrix, postMultiplyPivotMatrix) {
  14850. if (postMultiplyPivotMatrix === void 0) { postMultiplyPivotMatrix = false; }
  14851. this._pivotMatrix = matrix.clone();
  14852. this._cache.pivotMatrixUpdated = true;
  14853. this._postMultiplyPivotMatrix = postMultiplyPivotMatrix;
  14854. if (this._postMultiplyPivotMatrix) {
  14855. this._pivotMatrixInverse = BABYLON.Matrix.Invert(matrix);
  14856. }
  14857. return this;
  14858. };
  14859. /**
  14860. * Returns the mesh pivot matrix.
  14861. * Default : Identity.
  14862. * A Matrix is returned.
  14863. */
  14864. TransformNode.prototype.getPivotMatrix = function () {
  14865. return this._pivotMatrix;
  14866. };
  14867. /**
  14868. * Prevents the World matrix to be computed any longer.
  14869. * Returns the AbstractMesh.
  14870. */
  14871. TransformNode.prototype.freezeWorldMatrix = function () {
  14872. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  14873. this.computeWorldMatrix(true);
  14874. this._isWorldMatrixFrozen = true;
  14875. return this;
  14876. };
  14877. /**
  14878. * Allows back the World matrix computation.
  14879. * Returns the AbstractMesh.
  14880. */
  14881. TransformNode.prototype.unfreezeWorldMatrix = function () {
  14882. this._isWorldMatrixFrozen = false;
  14883. this.computeWorldMatrix(true);
  14884. return this;
  14885. };
  14886. Object.defineProperty(TransformNode.prototype, "isWorldMatrixFrozen", {
  14887. /**
  14888. * True if the World matrix has been frozen.
  14889. * Returns a boolean.
  14890. */
  14891. get: function () {
  14892. return this._isWorldMatrixFrozen;
  14893. },
  14894. enumerable: true,
  14895. configurable: true
  14896. });
  14897. /**
  14898. * Retuns the mesh absolute position in the World.
  14899. * Returns a Vector3.
  14900. */
  14901. TransformNode.prototype.getAbsolutePosition = function () {
  14902. this.computeWorldMatrix();
  14903. return this._absolutePosition;
  14904. };
  14905. /**
  14906. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  14907. * Returns the AbstractMesh.
  14908. */
  14909. TransformNode.prototype.setAbsolutePosition = function (absolutePosition) {
  14910. if (!absolutePosition) {
  14911. return this;
  14912. }
  14913. var absolutePositionX;
  14914. var absolutePositionY;
  14915. var absolutePositionZ;
  14916. if (absolutePosition.x === undefined) {
  14917. if (arguments.length < 3) {
  14918. return this;
  14919. }
  14920. absolutePositionX = arguments[0];
  14921. absolutePositionY = arguments[1];
  14922. absolutePositionZ = arguments[2];
  14923. }
  14924. else {
  14925. absolutePositionX = absolutePosition.x;
  14926. absolutePositionY = absolutePosition.y;
  14927. absolutePositionZ = absolutePosition.z;
  14928. }
  14929. if (this.parent) {
  14930. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  14931. invertParentWorldMatrix.invert();
  14932. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  14933. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  14934. }
  14935. else {
  14936. this.position.x = absolutePositionX;
  14937. this.position.y = absolutePositionY;
  14938. this.position.z = absolutePositionZ;
  14939. }
  14940. return this;
  14941. };
  14942. /**
  14943. * Sets the mesh position in its local space.
  14944. * Returns the AbstractMesh.
  14945. */
  14946. TransformNode.prototype.setPositionWithLocalVector = function (vector3) {
  14947. this.computeWorldMatrix();
  14948. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  14949. return this;
  14950. };
  14951. /**
  14952. * Returns the mesh position in the local space from the current World matrix values.
  14953. * Returns a new Vector3.
  14954. */
  14955. TransformNode.prototype.getPositionExpressedInLocalSpace = function () {
  14956. this.computeWorldMatrix();
  14957. var invLocalWorldMatrix = this._localWorld.clone();
  14958. invLocalWorldMatrix.invert();
  14959. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  14960. };
  14961. /**
  14962. * Translates the mesh along the passed Vector3 in its local space.
  14963. * Returns the AbstractMesh.
  14964. */
  14965. TransformNode.prototype.locallyTranslate = function (vector3) {
  14966. this.computeWorldMatrix(true);
  14967. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  14968. return this;
  14969. };
  14970. /**
  14971. * Orients a mesh towards a target point. Mesh must be drawn facing user.
  14972. * @param targetPoint the position (must be in same space as current mesh) to look at
  14973. * @param yawCor optional yaw (y-axis) correction in radians
  14974. * @param pitchCor optional pitch (x-axis) correction in radians
  14975. * @param rollCor optional roll (z-axis) correction in radians
  14976. * @param space the choosen space of the target
  14977. * @returns the TransformNode.
  14978. */
  14979. TransformNode.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  14980. if (yawCor === void 0) { yawCor = 0; }
  14981. if (pitchCor === void 0) { pitchCor = 0; }
  14982. if (rollCor === void 0) { rollCor = 0; }
  14983. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  14984. var dv = BABYLON.AbstractMesh._lookAtVectorCache;
  14985. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  14986. targetPoint.subtractToRef(pos, dv);
  14987. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  14988. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  14989. var pitch = Math.atan2(dv.y, len);
  14990. if (this.rotationQuaternion) {
  14991. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  14992. }
  14993. else {
  14994. this.rotation.x = pitch + pitchCor;
  14995. this.rotation.y = yaw + yawCor;
  14996. this.rotation.z = rollCor;
  14997. }
  14998. return this;
  14999. };
  15000. /**
  15001. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  15002. * This Vector3 is expressed in the World space.
  15003. */
  15004. TransformNode.prototype.getDirection = function (localAxis) {
  15005. var result = BABYLON.Vector3.Zero();
  15006. this.getDirectionToRef(localAxis, result);
  15007. return result;
  15008. };
  15009. /**
  15010. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  15011. * localAxis is expressed in the mesh local space.
  15012. * result is computed in the Wordl space from the mesh World matrix.
  15013. * Returns the AbstractMesh.
  15014. */
  15015. TransformNode.prototype.getDirectionToRef = function (localAxis, result) {
  15016. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  15017. return this;
  15018. };
  15019. TransformNode.prototype.setPivotPoint = function (point, space) {
  15020. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  15021. if (this.getScene().getRenderId() == 0) {
  15022. this.computeWorldMatrix(true);
  15023. }
  15024. var wm = this.getWorldMatrix();
  15025. if (space == BABYLON.Space.WORLD) {
  15026. var tmat = BABYLON.Tmp.Matrix[0];
  15027. wm.invertToRef(tmat);
  15028. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  15029. }
  15030. BABYLON.Vector3.TransformCoordinatesToRef(point, wm, this.position);
  15031. this._pivotMatrix.m[12] = -point.x;
  15032. this._pivotMatrix.m[13] = -point.y;
  15033. this._pivotMatrix.m[14] = -point.z;
  15034. this._cache.pivotMatrixUpdated = true;
  15035. return this;
  15036. };
  15037. /**
  15038. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  15039. */
  15040. TransformNode.prototype.getPivotPoint = function () {
  15041. var point = BABYLON.Vector3.Zero();
  15042. this.getPivotPointToRef(point);
  15043. return point;
  15044. };
  15045. /**
  15046. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  15047. * Returns the AbstractMesh.
  15048. */
  15049. TransformNode.prototype.getPivotPointToRef = function (result) {
  15050. result.x = -this._pivotMatrix.m[12];
  15051. result.y = -this._pivotMatrix.m[13];
  15052. result.z = -this._pivotMatrix.m[14];
  15053. return this;
  15054. };
  15055. /**
  15056. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  15057. */
  15058. TransformNode.prototype.getAbsolutePivotPoint = function () {
  15059. var point = BABYLON.Vector3.Zero();
  15060. this.getAbsolutePivotPointToRef(point);
  15061. return point;
  15062. };
  15063. /**
  15064. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  15065. * Returns the AbstractMesh.
  15066. */
  15067. TransformNode.prototype.getAbsolutePivotPointToRef = function (result) {
  15068. result.x = this._pivotMatrix.m[12];
  15069. result.y = this._pivotMatrix.m[13];
  15070. result.z = this._pivotMatrix.m[14];
  15071. this.getPivotPointToRef(result);
  15072. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  15073. return this;
  15074. };
  15075. /**
  15076. * Defines the passed node as the parent of the current node.
  15077. * The node will remain exactly where it is and its position / rotation will be updated accordingly
  15078. * Returns the TransformNode.
  15079. */
  15080. TransformNode.prototype.setParent = function (node) {
  15081. if (node === null) {
  15082. var rotation = BABYLON.Tmp.Quaternion[0];
  15083. var position = BABYLON.Tmp.Vector3[0];
  15084. var scale = BABYLON.Tmp.Vector3[1];
  15085. if (this.parent && this.parent.computeWorldMatrix) {
  15086. this.parent.computeWorldMatrix(true);
  15087. }
  15088. this.computeWorldMatrix(true);
  15089. this.getWorldMatrix().decompose(scale, rotation, position);
  15090. if (this.rotationQuaternion) {
  15091. this.rotationQuaternion.copyFrom(rotation);
  15092. }
  15093. else {
  15094. rotation.toEulerAnglesToRef(this.rotation);
  15095. }
  15096. this.scaling.x = scale.x;
  15097. this.scaling.y = scale.y;
  15098. this.scaling.z = scale.z;
  15099. this.position.x = position.x;
  15100. this.position.y = position.y;
  15101. this.position.z = position.z;
  15102. }
  15103. else {
  15104. var rotation = BABYLON.Tmp.Quaternion[0];
  15105. var position = BABYLON.Tmp.Vector3[0];
  15106. var scale = BABYLON.Tmp.Vector3[1];
  15107. var diffMatrix = BABYLON.Tmp.Matrix[0];
  15108. var invParentMatrix = BABYLON.Tmp.Matrix[1];
  15109. this.computeWorldMatrix(true);
  15110. node.computeWorldMatrix(true);
  15111. node.getWorldMatrix().invertToRef(invParentMatrix);
  15112. this.getWorldMatrix().multiplyToRef(invParentMatrix, diffMatrix);
  15113. diffMatrix.decompose(scale, rotation, position);
  15114. if (this.rotationQuaternion) {
  15115. this.rotationQuaternion.copyFrom(rotation);
  15116. }
  15117. else {
  15118. rotation.toEulerAnglesToRef(this.rotation);
  15119. }
  15120. this.position.x = position.x;
  15121. this.position.y = position.y;
  15122. this.position.z = position.z;
  15123. this.scaling.x = scale.x;
  15124. this.scaling.y = scale.y;
  15125. this.scaling.z = scale.z;
  15126. }
  15127. this.parent = node;
  15128. return this;
  15129. };
  15130. Object.defineProperty(TransformNode.prototype, "nonUniformScaling", {
  15131. get: function () {
  15132. return this._nonUniformScaling;
  15133. },
  15134. enumerable: true,
  15135. configurable: true
  15136. });
  15137. TransformNode.prototype._updateNonUniformScalingState = function (value) {
  15138. if (this._nonUniformScaling === value) {
  15139. return false;
  15140. }
  15141. this._nonUniformScaling = true;
  15142. return true;
  15143. };
  15144. /**
  15145. * Attach the current TransformNode to another TransformNode associated with a bone
  15146. * @param bone Bone affecting the TransformNode
  15147. * @param affectedTransformNode TransformNode associated with the bone
  15148. */
  15149. TransformNode.prototype.attachToBone = function (bone, affectedTransformNode) {
  15150. this._transformToBoneReferal = affectedTransformNode;
  15151. this.parent = bone;
  15152. if (bone.getWorldMatrix().determinant() < 0) {
  15153. this.scalingDeterminant *= -1;
  15154. }
  15155. return this;
  15156. };
  15157. TransformNode.prototype.detachFromBone = function () {
  15158. if (!this.parent) {
  15159. return this;
  15160. }
  15161. if (this.parent.getWorldMatrix().determinant() < 0) {
  15162. this.scalingDeterminant *= -1;
  15163. }
  15164. this._transformToBoneReferal = null;
  15165. this.parent = null;
  15166. return this;
  15167. };
  15168. /**
  15169. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  15170. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  15171. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  15172. * The passed axis is also normalized.
  15173. * Returns the AbstractMesh.
  15174. */
  15175. TransformNode.prototype.rotate = function (axis, amount, space) {
  15176. axis.normalize();
  15177. if (!this.rotationQuaternion) {
  15178. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  15179. this.rotation = BABYLON.Vector3.Zero();
  15180. }
  15181. var rotationQuaternion;
  15182. if (!space || space === BABYLON.Space.LOCAL) {
  15183. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, BABYLON.AbstractMesh._rotationAxisCache);
  15184. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  15185. }
  15186. else {
  15187. if (this.parent) {
  15188. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  15189. invertParentWorldMatrix.invert();
  15190. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  15191. }
  15192. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, BABYLON.AbstractMesh._rotationAxisCache);
  15193. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  15194. }
  15195. return this;
  15196. };
  15197. /**
  15198. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  15199. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  15200. * The passed axis is also normalized.
  15201. * Returns the AbstractMesh.
  15202. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  15203. */
  15204. TransformNode.prototype.rotateAround = function (point, axis, amount) {
  15205. axis.normalize();
  15206. if (!this.rotationQuaternion) {
  15207. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  15208. this.rotation.copyFromFloats(0, 0, 0);
  15209. }
  15210. point.subtractToRef(this.position, BABYLON.Tmp.Vector3[0]);
  15211. BABYLON.Matrix.TranslationToRef(BABYLON.Tmp.Vector3[0].x, BABYLON.Tmp.Vector3[0].y, BABYLON.Tmp.Vector3[0].z, BABYLON.Tmp.Matrix[0]);
  15212. BABYLON.Tmp.Matrix[0].invertToRef(BABYLON.Tmp.Matrix[2]);
  15213. BABYLON.Matrix.RotationAxisToRef(axis, amount, BABYLON.Tmp.Matrix[1]);
  15214. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[2]);
  15215. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[2]);
  15216. BABYLON.Tmp.Matrix[2].decompose(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Quaternion[0], BABYLON.Tmp.Vector3[1]);
  15217. this.position.addInPlace(BABYLON.Tmp.Vector3[1]);
  15218. BABYLON.Tmp.Quaternion[0].multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  15219. return this;
  15220. };
  15221. /**
  15222. * Translates the mesh along the axis vector for the passed distance in the given space.
  15223. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  15224. * Returns the AbstractMesh.
  15225. */
  15226. TransformNode.prototype.translate = function (axis, distance, space) {
  15227. var displacementVector = axis.scale(distance);
  15228. if (!space || space === BABYLON.Space.LOCAL) {
  15229. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  15230. this.setPositionWithLocalVector(tempV3);
  15231. }
  15232. else {
  15233. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  15234. }
  15235. return this;
  15236. };
  15237. /**
  15238. * Adds a rotation step to the mesh current rotation.
  15239. * x, y, z are Euler angles expressed in radians.
  15240. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  15241. * This means this rotation is made in the mesh local space only.
  15242. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  15243. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  15244. * ```javascript
  15245. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  15246. * ```
  15247. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  15248. * 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.
  15249. * Returns the AbstractMesh.
  15250. */
  15251. TransformNode.prototype.addRotation = function (x, y, z) {
  15252. var rotationQuaternion;
  15253. if (this.rotationQuaternion) {
  15254. rotationQuaternion = this.rotationQuaternion;
  15255. }
  15256. else {
  15257. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  15258. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  15259. }
  15260. var accumulation = BABYLON.Tmp.Quaternion[0];
  15261. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  15262. rotationQuaternion.multiplyInPlace(accumulation);
  15263. if (!this.rotationQuaternion) {
  15264. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  15265. }
  15266. return this;
  15267. };
  15268. /**
  15269. * Computes the mesh World matrix and returns it.
  15270. * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
  15271. * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
  15272. * If the parameter `force`is set to `true`, the actual computation is done.
  15273. * Returns the mesh World Matrix.
  15274. */
  15275. TransformNode.prototype.computeWorldMatrix = function (force) {
  15276. if (this._isWorldMatrixFrozen) {
  15277. return this._worldMatrix;
  15278. }
  15279. if (!force && this.isSynchronized(true)) {
  15280. return this._worldMatrix;
  15281. }
  15282. this._cache.position.copyFrom(this.position);
  15283. this._cache.scaling.copyFrom(this.scaling);
  15284. this._cache.pivotMatrixUpdated = false;
  15285. this._cache.billboardMode = this.billboardMode;
  15286. this._currentRenderId = this.getScene().getRenderId();
  15287. this._isDirty = false;
  15288. // Scaling
  15289. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  15290. // Rotation
  15291. //rotate, if quaternion is set and rotation was used
  15292. if (this.rotationQuaternion) {
  15293. var len = this.rotation.length();
  15294. if (len) {
  15295. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  15296. this.rotation.copyFromFloats(0, 0, 0);
  15297. }
  15298. }
  15299. if (this.rotationQuaternion) {
  15300. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  15301. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  15302. }
  15303. else {
  15304. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  15305. this._cache.rotation.copyFrom(this.rotation);
  15306. }
  15307. // Translation
  15308. var camera = this.getScene().activeCamera;
  15309. if (this.infiniteDistance && !this.parent && camera) {
  15310. var cameraWorldMatrix = camera.getWorldMatrix();
  15311. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  15312. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  15313. }
  15314. else {
  15315. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  15316. }
  15317. // Composing transformations
  15318. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  15319. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  15320. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  15321. if (this.billboardMode !== BABYLON.AbstractMesh.BILLBOARDMODE_NONE && camera) {
  15322. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_ALL) !== BABYLON.AbstractMesh.BILLBOARDMODE_ALL) {
  15323. // Need to decompose each rotation here
  15324. var currentPosition = BABYLON.Tmp.Vector3[3];
  15325. if (this.parent && this.parent.getWorldMatrix) {
  15326. if (this._transformToBoneReferal) {
  15327. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  15328. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  15329. }
  15330. else {
  15331. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  15332. }
  15333. }
  15334. else {
  15335. currentPosition.copyFrom(this.position);
  15336. }
  15337. currentPosition.subtractInPlace(camera.globalPosition);
  15338. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  15339. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_X) === BABYLON.AbstractMesh.BILLBOARDMODE_X) {
  15340. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  15341. }
  15342. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Y) === BABYLON.AbstractMesh.BILLBOARDMODE_Y) {
  15343. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  15344. }
  15345. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Z) === BABYLON.AbstractMesh.BILLBOARDMODE_Z) {
  15346. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  15347. }
  15348. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  15349. }
  15350. else {
  15351. BABYLON.Tmp.Matrix[1].copyFrom(camera.getViewMatrix());
  15352. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  15353. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  15354. }
  15355. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  15356. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  15357. }
  15358. // Local world
  15359. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  15360. // Parent
  15361. if (this.parent && this.parent.getWorldMatrix) {
  15362. if (this.billboardMode !== BABYLON.AbstractMesh.BILLBOARDMODE_NONE) {
  15363. if (this._transformToBoneReferal) {
  15364. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  15365. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  15366. }
  15367. else {
  15368. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  15369. }
  15370. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  15371. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  15372. this._worldMatrix.copyFrom(this._localWorld);
  15373. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  15374. }
  15375. else {
  15376. if (this._transformToBoneReferal) {
  15377. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  15378. BABYLON.Tmp.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), this._worldMatrix);
  15379. }
  15380. else {
  15381. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  15382. }
  15383. }
  15384. this._markSyncedWithParent();
  15385. }
  15386. else {
  15387. this._worldMatrix.copyFrom(this._localWorld);
  15388. }
  15389. // Post multiply inverse of pivotMatrix
  15390. if (this._postMultiplyPivotMatrix) {
  15391. this._worldMatrix.multiplyToRef(this._pivotMatrixInverse, this._worldMatrix);
  15392. }
  15393. // Normal matrix
  15394. if (this.scaling.isNonUniform) {
  15395. this._updateNonUniformScalingState(true);
  15396. }
  15397. else if (this.parent && this.parent._nonUniformScaling) {
  15398. this._updateNonUniformScalingState(this.parent._nonUniformScaling);
  15399. }
  15400. else {
  15401. this._updateNonUniformScalingState(false);
  15402. }
  15403. this._afterComputeWorldMatrix();
  15404. // Absolute position
  15405. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  15406. // Callbacks
  15407. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  15408. if (!this._poseMatrix) {
  15409. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  15410. }
  15411. // Cache the determinant
  15412. this._worldMatrixDeterminant = this._worldMatrix.determinant();
  15413. return this._worldMatrix;
  15414. };
  15415. TransformNode.prototype._afterComputeWorldMatrix = function () {
  15416. };
  15417. /**
  15418. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  15419. * @param func: callback function to add
  15420. *
  15421. * Returns the TransformNode.
  15422. */
  15423. TransformNode.prototype.registerAfterWorldMatrixUpdate = function (func) {
  15424. this.onAfterWorldMatrixUpdateObservable.add(func);
  15425. return this;
  15426. };
  15427. /**
  15428. * Removes a registered callback function.
  15429. * Returns the TransformNode.
  15430. */
  15431. TransformNode.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  15432. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  15433. return this;
  15434. };
  15435. /**
  15436. * Clone the current transform node
  15437. * Returns the new transform node
  15438. * @param name Name of the new clone
  15439. * @param newParent New parent for the clone
  15440. * @param doNotCloneChildren Do not clone children hierarchy
  15441. */
  15442. TransformNode.prototype.clone = function (name, newParent, doNotCloneChildren) {
  15443. var _this = this;
  15444. var result = BABYLON.SerializationHelper.Clone(function () { return new TransformNode(name, _this.getScene()); }, this);
  15445. result.name = name;
  15446. result.id = name;
  15447. if (newParent) {
  15448. result.parent = newParent;
  15449. }
  15450. if (!doNotCloneChildren) {
  15451. // Children
  15452. var directDescendants = this.getDescendants(true);
  15453. for (var index = 0; index < directDescendants.length; index++) {
  15454. var child = directDescendants[index];
  15455. if (child.clone) {
  15456. child.clone(name + "." + child.name, result);
  15457. }
  15458. }
  15459. }
  15460. return result;
  15461. };
  15462. TransformNode.prototype.serialize = function (currentSerializationObject) {
  15463. var serializationObject = BABYLON.SerializationHelper.Serialize(this, currentSerializationObject);
  15464. serializationObject.type = this.getClassName();
  15465. // Parent
  15466. if (this.parent) {
  15467. serializationObject.parentId = this.parent.id;
  15468. }
  15469. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  15470. serializationObject.tags = BABYLON.Tags.GetTags(this);
  15471. }
  15472. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  15473. serializationObject.isEnabled = this.isEnabled();
  15474. // Parent
  15475. if (this.parent) {
  15476. serializationObject.parentId = this.parent.id;
  15477. }
  15478. return serializationObject;
  15479. };
  15480. // Statics
  15481. /**
  15482. * Returns a new TransformNode object parsed from the source provided.
  15483. * The parameter `parsedMesh` is the source.
  15484. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  15485. */
  15486. TransformNode.Parse = function (parsedTransformNode, scene, rootUrl) {
  15487. var transformNode = BABYLON.SerializationHelper.Parse(function () { return new TransformNode(parsedTransformNode.name, scene); }, parsedTransformNode, scene, rootUrl);
  15488. if (BABYLON.Tags) {
  15489. BABYLON.Tags.AddTagsTo(transformNode, parsedTransformNode.tags);
  15490. }
  15491. if (parsedTransformNode.localMatrix) {
  15492. transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.localMatrix));
  15493. }
  15494. else if (parsedTransformNode.pivotMatrix) {
  15495. transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.pivotMatrix));
  15496. }
  15497. transformNode.setEnabled(parsedTransformNode.isEnabled);
  15498. // Parent
  15499. if (parsedTransformNode.parentId) {
  15500. transformNode._waitingParentId = parsedTransformNode.parentId;
  15501. }
  15502. return transformNode;
  15503. };
  15504. /**
  15505. * Disposes the TransformNode.
  15506. * By default, all the children are also disposed unless the parameter `doNotRecurse` is set to `true`.
  15507. * Returns nothing.
  15508. */
  15509. TransformNode.prototype.dispose = function (doNotRecurse) {
  15510. // Animations
  15511. this.getScene().stopAnimation(this);
  15512. // Remove from scene
  15513. this.getScene().removeTransformNode(this);
  15514. if (!doNotRecurse) {
  15515. // Children
  15516. var objects = this.getDescendants(true);
  15517. for (var index = 0; index < objects.length; index++) {
  15518. objects[index].dispose();
  15519. }
  15520. }
  15521. else {
  15522. var childMeshes = this.getChildMeshes(true);
  15523. for (index = 0; index < childMeshes.length; index++) {
  15524. var child = childMeshes[index];
  15525. child.parent = null;
  15526. child.computeWorldMatrix(true);
  15527. }
  15528. }
  15529. this.onAfterWorldMatrixUpdateObservable.clear();
  15530. _super.prototype.dispose.call(this);
  15531. };
  15532. // Statics
  15533. TransformNode.BILLBOARDMODE_NONE = 0;
  15534. TransformNode.BILLBOARDMODE_X = 1;
  15535. TransformNode.BILLBOARDMODE_Y = 2;
  15536. TransformNode.BILLBOARDMODE_Z = 4;
  15537. TransformNode.BILLBOARDMODE_ALL = 7;
  15538. TransformNode._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  15539. TransformNode._rotationAxisCache = new BABYLON.Quaternion();
  15540. __decorate([
  15541. BABYLON.serializeAsVector3()
  15542. ], TransformNode.prototype, "_rotation", void 0);
  15543. __decorate([
  15544. BABYLON.serializeAsQuaternion()
  15545. ], TransformNode.prototype, "_rotationQuaternion", void 0);
  15546. __decorate([
  15547. BABYLON.serializeAsVector3()
  15548. ], TransformNode.prototype, "_scaling", void 0);
  15549. __decorate([
  15550. BABYLON.serialize()
  15551. ], TransformNode.prototype, "billboardMode", void 0);
  15552. __decorate([
  15553. BABYLON.serialize()
  15554. ], TransformNode.prototype, "scalingDeterminant", void 0);
  15555. __decorate([
  15556. BABYLON.serialize()
  15557. ], TransformNode.prototype, "infiniteDistance", void 0);
  15558. __decorate([
  15559. BABYLON.serializeAsVector3()
  15560. ], TransformNode.prototype, "position", void 0);
  15561. return TransformNode;
  15562. }(BABYLON.Node));
  15563. BABYLON.TransformNode = TransformNode;
  15564. })(BABYLON || (BABYLON = {}));
  15565. //# sourceMappingURL=babylon.transformNode.js.map
  15566. var BABYLON;
  15567. (function (BABYLON) {
  15568. var AbstractMesh = /** @class */ (function (_super) {
  15569. __extends(AbstractMesh, _super);
  15570. // Constructor
  15571. function AbstractMesh(name, scene) {
  15572. if (scene === void 0) { scene = null; }
  15573. var _this = _super.call(this, name, scene, false) || this;
  15574. _this._facetNb = 0; // facet number
  15575. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  15576. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  15577. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  15578. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  15579. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  15580. _this._subDiv = {
  15581. max: 1,
  15582. X: 1,
  15583. Y: 1,
  15584. Z: 1
  15585. };
  15586. _this._facetDepthSort = false; // is the facet depth sort to be computed
  15587. _this._facetDepthSortEnabled = false; // is the facet depth sort initialized
  15588. // Events
  15589. /**
  15590. * An event triggered when this mesh collides with another one
  15591. * @type {BABYLON.Observable}
  15592. */
  15593. _this.onCollideObservable = new BABYLON.Observable();
  15594. /**
  15595. * An event triggered when the collision's position changes
  15596. * @type {BABYLON.Observable}
  15597. */
  15598. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  15599. /**
  15600. * An event triggered when material is changed
  15601. * @type {BABYLON.Observable}
  15602. */
  15603. _this.onMaterialChangedObservable = new BABYLON.Observable();
  15604. // Properties
  15605. _this.definedFacingForward = true; // orientation for POV movement & rotation
  15606. /**
  15607. * This property determines the type of occlusion query algorithm to run in WebGl, you can use:
  15608. * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE which is mapped to GL_ANY_SAMPLES_PASSED.
  15609. * or
  15610. * 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.
  15611. * for more info check WebGl documentations
  15612. */
  15613. _this.occlusionQueryAlgorithmType = AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;
  15614. /**
  15615. * 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:
  15616. * OCCLUSION_TYPE_NONE (Default Value): this option means no occlusion query whith the Mesh.
  15617. * OCCLUSION_TYPE_OPTIMISTIC: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken show the mesh.
  15618. * 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.
  15619. */
  15620. _this.occlusionType = AbstractMesh.OCCLUSION_TYPE_NONE;
  15621. /**
  15622. * 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.
  15623. * The default value is -1 which means don't break the query and wait till the result.
  15624. */
  15625. _this.occlusionRetryCount = -1;
  15626. _this._occlusionInternalRetryCounter = 0;
  15627. _this._isOccluded = false;
  15628. _this._isOcclusionQueryInProgress = false;
  15629. _this._visibility = 1.0;
  15630. _this.alphaIndex = Number.MAX_VALUE;
  15631. _this.isVisible = true;
  15632. _this.isPickable = true;
  15633. _this.showBoundingBox = false;
  15634. _this.showSubMeshesBoundingBox = false;
  15635. _this.isBlocker = false;
  15636. _this.enablePointerMoveEvents = false;
  15637. _this.renderingGroupId = 0;
  15638. _this._receiveShadows = false;
  15639. _this.renderOutline = false;
  15640. _this.outlineColor = BABYLON.Color3.Red();
  15641. _this.outlineWidth = 0.02;
  15642. _this.renderOverlay = false;
  15643. _this.overlayColor = BABYLON.Color3.Red();
  15644. _this.overlayAlpha = 0.5;
  15645. _this._hasVertexAlpha = false;
  15646. _this._useVertexColors = true;
  15647. _this._computeBonesUsingShaders = true;
  15648. _this._numBoneInfluencers = 4;
  15649. _this._applyFog = true;
  15650. _this.useOctreeForRenderingSelection = true;
  15651. _this.useOctreeForPicking = true;
  15652. _this.useOctreeForCollisions = true;
  15653. _this._layerMask = 0x0FFFFFFF;
  15654. /**
  15655. * True if the mesh must be rendered in any case.
  15656. */
  15657. _this.alwaysSelectAsActiveMesh = false;
  15658. /**
  15659. * This scene's action manager
  15660. * @type {BABYLON.ActionManager}
  15661. */
  15662. _this.actionManager = null;
  15663. // Physics
  15664. _this.physicsImpostor = null;
  15665. // Collisions
  15666. _this._checkCollisions = false;
  15667. _this._collisionMask = -1;
  15668. _this._collisionGroup = -1;
  15669. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  15670. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  15671. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  15672. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  15673. // Edges
  15674. _this.edgesWidth = 1;
  15675. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  15676. // Cache
  15677. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  15678. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  15679. _this._isDisposed = false;
  15680. _this._renderId = 0;
  15681. _this._intersectionsInProgress = new Array();
  15682. _this._unIndexed = false;
  15683. _this._lightSources = new Array();
  15684. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  15685. if (collidedMesh === void 0) { collidedMesh = null; }
  15686. //TODO move this to the collision coordinator!
  15687. if (_this.getScene().workerCollisions)
  15688. newPosition.multiplyInPlace(_this._collider._radius);
  15689. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  15690. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  15691. _this.position.addInPlace(_this._diffPositionForCollisions);
  15692. }
  15693. if (collidedMesh) {
  15694. _this.onCollideObservable.notifyObservers(collidedMesh);
  15695. }
  15696. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  15697. };
  15698. _this.getScene().addMesh(_this);
  15699. _this._resyncLightSources();
  15700. return _this;
  15701. }
  15702. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  15703. get: function () {
  15704. return BABYLON.TransformNode.BILLBOARDMODE_NONE;
  15705. },
  15706. enumerable: true,
  15707. configurable: true
  15708. });
  15709. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  15710. get: function () {
  15711. return BABYLON.TransformNode.BILLBOARDMODE_X;
  15712. },
  15713. enumerable: true,
  15714. configurable: true
  15715. });
  15716. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  15717. get: function () {
  15718. return BABYLON.TransformNode.BILLBOARDMODE_Y;
  15719. },
  15720. enumerable: true,
  15721. configurable: true
  15722. });
  15723. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  15724. get: function () {
  15725. return BABYLON.TransformNode.BILLBOARDMODE_Z;
  15726. },
  15727. enumerable: true,
  15728. configurable: true
  15729. });
  15730. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  15731. get: function () {
  15732. return BABYLON.TransformNode.BILLBOARDMODE_ALL;
  15733. },
  15734. enumerable: true,
  15735. configurable: true
  15736. });
  15737. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  15738. /**
  15739. * Read-only : the number of facets in the mesh
  15740. */
  15741. get: function () {
  15742. return this._facetNb;
  15743. },
  15744. enumerable: true,
  15745. configurable: true
  15746. });
  15747. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  15748. /**
  15749. * The number (integer) of subdivisions per axis in the partioning space
  15750. */
  15751. get: function () {
  15752. return this._partitioningSubdivisions;
  15753. },
  15754. set: function (nb) {
  15755. this._partitioningSubdivisions = nb;
  15756. },
  15757. enumerable: true,
  15758. configurable: true
  15759. });
  15760. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  15761. /**
  15762. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  15763. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box.
  15764. */
  15765. get: function () {
  15766. return this._partitioningBBoxRatio;
  15767. },
  15768. set: function (ratio) {
  15769. this._partitioningBBoxRatio = ratio;
  15770. },
  15771. enumerable: true,
  15772. configurable: true
  15773. });
  15774. Object.defineProperty(AbstractMesh.prototype, "mustDepthSortFacets", {
  15775. /**
  15776. * Boolean : must the facet be depth sorted on next call to `updateFacetData()` ?
  15777. * Works only for updatable meshes.
  15778. * Doesn't work with multi-materials.
  15779. */
  15780. get: function () {
  15781. return this._facetDepthSort;
  15782. },
  15783. set: function (sort) {
  15784. this._facetDepthSort = sort;
  15785. },
  15786. enumerable: true,
  15787. configurable: true
  15788. });
  15789. Object.defineProperty(AbstractMesh.prototype, "facetDepthSortFrom", {
  15790. /**
  15791. * The location (Vector3) where the facet depth sort must be computed from.
  15792. * By default, the active camera position.
  15793. * Used only when facet depth sort is enabled.
  15794. */
  15795. get: function () {
  15796. return this._facetDepthSortFrom;
  15797. },
  15798. set: function (location) {
  15799. this._facetDepthSortFrom = location;
  15800. },
  15801. enumerable: true,
  15802. configurable: true
  15803. });
  15804. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  15805. /**
  15806. * Read-only boolean : is the feature facetData enabled ?
  15807. */
  15808. get: function () {
  15809. return this._facetDataEnabled;
  15810. },
  15811. enumerable: true,
  15812. configurable: true
  15813. });
  15814. AbstractMesh.prototype._updateNonUniformScalingState = function (value) {
  15815. if (!_super.prototype._updateNonUniformScalingState.call(this, value)) {
  15816. return false;
  15817. }
  15818. this._markSubMeshesAsMiscDirty();
  15819. return true;
  15820. };
  15821. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  15822. set: function (callback) {
  15823. if (this._onCollideObserver) {
  15824. this.onCollideObservable.remove(this._onCollideObserver);
  15825. }
  15826. this._onCollideObserver = this.onCollideObservable.add(callback);
  15827. },
  15828. enumerable: true,
  15829. configurable: true
  15830. });
  15831. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  15832. set: function (callback) {
  15833. if (this._onCollisionPositionChangeObserver) {
  15834. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  15835. }
  15836. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  15837. },
  15838. enumerable: true,
  15839. configurable: true
  15840. });
  15841. Object.defineProperty(AbstractMesh.prototype, "isOccluded", {
  15842. /**
  15843. * 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.
  15844. */
  15845. get: function () {
  15846. return this._isOccluded;
  15847. },
  15848. set: function (value) {
  15849. this._isOccluded = value;
  15850. },
  15851. enumerable: true,
  15852. configurable: true
  15853. });
  15854. Object.defineProperty(AbstractMesh.prototype, "isOcclusionQueryInProgress", {
  15855. /**
  15856. * Flag to check the progress status of the query
  15857. */
  15858. get: function () {
  15859. return this._isOcclusionQueryInProgress;
  15860. },
  15861. enumerable: true,
  15862. configurable: true
  15863. });
  15864. Object.defineProperty(AbstractMesh.prototype, "visibility", {
  15865. /**
  15866. * Gets or sets mesh visibility between 0 and 1 (defult is 1)
  15867. */
  15868. get: function () {
  15869. return this._visibility;
  15870. },
  15871. /**
  15872. * Gets or sets mesh visibility between 0 and 1 (defult is 1)
  15873. */
  15874. set: function (value) {
  15875. if (this._visibility === value) {
  15876. return;
  15877. }
  15878. this._visibility = value;
  15879. this._markSubMeshesAsMiscDirty();
  15880. },
  15881. enumerable: true,
  15882. configurable: true
  15883. });
  15884. Object.defineProperty(AbstractMesh.prototype, "material", {
  15885. get: function () {
  15886. return this._material;
  15887. },
  15888. set: function (value) {
  15889. if (this._material === value) {
  15890. return;
  15891. }
  15892. this._material = value;
  15893. if (this.onMaterialChangedObservable.hasObservers) {
  15894. this.onMaterialChangedObservable.notifyObservers(this);
  15895. }
  15896. if (!this.subMeshes) {
  15897. return;
  15898. }
  15899. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  15900. var subMesh = _a[_i];
  15901. subMesh.setEffect(null);
  15902. }
  15903. },
  15904. enumerable: true,
  15905. configurable: true
  15906. });
  15907. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  15908. get: function () {
  15909. return this._receiveShadows;
  15910. },
  15911. set: function (value) {
  15912. if (this._receiveShadows === value) {
  15913. return;
  15914. }
  15915. this._receiveShadows = value;
  15916. this._markSubMeshesAsLightDirty();
  15917. },
  15918. enumerable: true,
  15919. configurable: true
  15920. });
  15921. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  15922. get: function () {
  15923. return this._hasVertexAlpha;
  15924. },
  15925. set: function (value) {
  15926. if (this._hasVertexAlpha === value) {
  15927. return;
  15928. }
  15929. this._hasVertexAlpha = value;
  15930. this._markSubMeshesAsAttributesDirty();
  15931. this._markSubMeshesAsMiscDirty();
  15932. },
  15933. enumerable: true,
  15934. configurable: true
  15935. });
  15936. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  15937. get: function () {
  15938. return this._useVertexColors;
  15939. },
  15940. set: function (value) {
  15941. if (this._useVertexColors === value) {
  15942. return;
  15943. }
  15944. this._useVertexColors = value;
  15945. this._markSubMeshesAsAttributesDirty();
  15946. },
  15947. enumerable: true,
  15948. configurable: true
  15949. });
  15950. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  15951. get: function () {
  15952. return this._computeBonesUsingShaders;
  15953. },
  15954. set: function (value) {
  15955. if (this._computeBonesUsingShaders === value) {
  15956. return;
  15957. }
  15958. this._computeBonesUsingShaders = value;
  15959. this._markSubMeshesAsAttributesDirty();
  15960. },
  15961. enumerable: true,
  15962. configurable: true
  15963. });
  15964. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  15965. get: function () {
  15966. return this._numBoneInfluencers;
  15967. },
  15968. set: function (value) {
  15969. if (this._numBoneInfluencers === value) {
  15970. return;
  15971. }
  15972. this._numBoneInfluencers = value;
  15973. this._markSubMeshesAsAttributesDirty();
  15974. },
  15975. enumerable: true,
  15976. configurable: true
  15977. });
  15978. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  15979. get: function () {
  15980. return this._applyFog;
  15981. },
  15982. set: function (value) {
  15983. if (this._applyFog === value) {
  15984. return;
  15985. }
  15986. this._applyFog = value;
  15987. this._markSubMeshesAsMiscDirty();
  15988. },
  15989. enumerable: true,
  15990. configurable: true
  15991. });
  15992. Object.defineProperty(AbstractMesh.prototype, "layerMask", {
  15993. get: function () {
  15994. return this._layerMask;
  15995. },
  15996. set: function (value) {
  15997. if (value === this._layerMask) {
  15998. return;
  15999. }
  16000. this._layerMask = value;
  16001. this._resyncLightSources();
  16002. },
  16003. enumerable: true,
  16004. configurable: true
  16005. });
  16006. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  16007. get: function () {
  16008. return this._collisionMask;
  16009. },
  16010. set: function (mask) {
  16011. this._collisionMask = !isNaN(mask) ? mask : -1;
  16012. },
  16013. enumerable: true,
  16014. configurable: true
  16015. });
  16016. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  16017. get: function () {
  16018. return this._collisionGroup;
  16019. },
  16020. set: function (mask) {
  16021. this._collisionGroup = !isNaN(mask) ? mask : -1;
  16022. },
  16023. enumerable: true,
  16024. configurable: true
  16025. });
  16026. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  16027. get: function () {
  16028. return null;
  16029. },
  16030. enumerable: true,
  16031. configurable: true
  16032. });
  16033. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  16034. get: function () {
  16035. return this._skeleton;
  16036. },
  16037. set: function (value) {
  16038. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  16039. this._skeleton._unregisterMeshWithPoseMatrix(this);
  16040. }
  16041. if (value && value.needInitialSkinMatrix) {
  16042. value._registerMeshWithPoseMatrix(this);
  16043. }
  16044. this._skeleton = value;
  16045. if (!this._skeleton) {
  16046. this._bonesTransformMatrices = null;
  16047. }
  16048. this._markSubMeshesAsAttributesDirty();
  16049. },
  16050. enumerable: true,
  16051. configurable: true
  16052. });
  16053. /**
  16054. * Boolean : true if the mesh has been disposed.
  16055. */
  16056. AbstractMesh.prototype.isDisposed = function () {
  16057. return this._isDisposed;
  16058. };
  16059. /**
  16060. * Returns the string "AbstractMesh"
  16061. */
  16062. AbstractMesh.prototype.getClassName = function () {
  16063. return "AbstractMesh";
  16064. };
  16065. /**
  16066. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  16067. */
  16068. AbstractMesh.prototype.toString = function (fullDetails) {
  16069. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  16070. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  16071. if (this._skeleton) {
  16072. ret += ", skeleton: " + this._skeleton.name;
  16073. }
  16074. if (fullDetails) {
  16075. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  16076. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  16077. }
  16078. return ret;
  16079. };
  16080. AbstractMesh.prototype._rebuild = function () {
  16081. if (this._occlusionQuery) {
  16082. this._occlusionQuery = null;
  16083. }
  16084. if (this._edgesRenderer) {
  16085. this._edgesRenderer._rebuild();
  16086. }
  16087. if (!this.subMeshes) {
  16088. return;
  16089. }
  16090. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  16091. var subMesh = _a[_i];
  16092. subMesh._rebuild();
  16093. }
  16094. };
  16095. AbstractMesh.prototype._resyncLightSources = function () {
  16096. this._lightSources.length = 0;
  16097. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  16098. var light = _a[_i];
  16099. if (!light.isEnabled()) {
  16100. continue;
  16101. }
  16102. if (light.canAffectMesh(this)) {
  16103. this._lightSources.push(light);
  16104. }
  16105. }
  16106. this._markSubMeshesAsLightDirty();
  16107. };
  16108. AbstractMesh.prototype._resyncLighSource = function (light) {
  16109. var isIn = light.isEnabled() && light.canAffectMesh(this);
  16110. var index = this._lightSources.indexOf(light);
  16111. if (index === -1) {
  16112. if (!isIn) {
  16113. return;
  16114. }
  16115. this._lightSources.push(light);
  16116. }
  16117. else {
  16118. if (isIn) {
  16119. return;
  16120. }
  16121. this._lightSources.splice(index, 1);
  16122. }
  16123. this._markSubMeshesAsLightDirty();
  16124. };
  16125. AbstractMesh.prototype._removeLightSource = function (light) {
  16126. var index = this._lightSources.indexOf(light);
  16127. if (index === -1) {
  16128. return;
  16129. }
  16130. this._lightSources.splice(index, 1);
  16131. this._markSubMeshesAsLightDirty();
  16132. };
  16133. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  16134. if (!this.subMeshes) {
  16135. return;
  16136. }
  16137. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  16138. var subMesh = _a[_i];
  16139. if (subMesh._materialDefines) {
  16140. func(subMesh._materialDefines);
  16141. }
  16142. }
  16143. };
  16144. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  16145. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  16146. };
  16147. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  16148. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  16149. };
  16150. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  16151. if (!this.subMeshes) {
  16152. return;
  16153. }
  16154. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  16155. var subMesh = _a[_i];
  16156. var material = subMesh.getMaterial();
  16157. if (material) {
  16158. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  16159. }
  16160. }
  16161. };
  16162. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  16163. /**
  16164. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  16165. * Default : (1.0, 1.0, 1.0)
  16166. */
  16167. get: function () {
  16168. return this._scaling;
  16169. },
  16170. /**
  16171. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  16172. * Default : (1.0, 1.0, 1.0)
  16173. */
  16174. set: function (newScaling) {
  16175. this._scaling = newScaling;
  16176. if (this.physicsImpostor) {
  16177. this.physicsImpostor.forceUpdate();
  16178. }
  16179. },
  16180. enumerable: true,
  16181. configurable: true
  16182. });
  16183. // Methods
  16184. /**
  16185. * Disables the mesh edger rendering mode.
  16186. * Returns the AbstractMesh.
  16187. */
  16188. AbstractMesh.prototype.disableEdgesRendering = function () {
  16189. if (this._edgesRenderer) {
  16190. this._edgesRenderer.dispose();
  16191. this._edgesRenderer = null;
  16192. }
  16193. return this;
  16194. };
  16195. /**
  16196. * Enables the edge rendering mode on the mesh.
  16197. * This mode makes the mesh edges visible.
  16198. * Returns the AbstractMesh.
  16199. */
  16200. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  16201. if (epsilon === void 0) { epsilon = 0.95; }
  16202. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  16203. this.disableEdgesRendering();
  16204. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  16205. return this;
  16206. };
  16207. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  16208. /**
  16209. * Returns true if the mesh is blocked. Used by the class Mesh.
  16210. * Returns the boolean `false` by default.
  16211. */
  16212. get: function () {
  16213. return false;
  16214. },
  16215. enumerable: true,
  16216. configurable: true
  16217. });
  16218. /**
  16219. * Returns the mesh itself by default, used by the class Mesh.
  16220. * Returned type : AbstractMesh
  16221. */
  16222. AbstractMesh.prototype.getLOD = function (camera) {
  16223. return this;
  16224. };
  16225. /**
  16226. * Returns 0 by default, used by the class Mesh.
  16227. * Returns an integer.
  16228. */
  16229. AbstractMesh.prototype.getTotalVertices = function () {
  16230. return 0;
  16231. };
  16232. /**
  16233. * Returns null by default, used by the class Mesh.
  16234. * Returned type : integer array
  16235. */
  16236. AbstractMesh.prototype.getIndices = function () {
  16237. return null;
  16238. };
  16239. /**
  16240. * Returns the array of the requested vertex data kind. Used by the class Mesh. Returns null here.
  16241. * Returned type : float array or Float32Array
  16242. */
  16243. AbstractMesh.prototype.getVerticesData = function (kind) {
  16244. return null;
  16245. };
  16246. /**
  16247. * Sets the vertex data of the mesh geometry for the requested `kind`.
  16248. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  16249. * The `data` are either a numeric array either a Float32Array.
  16250. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  16251. * 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).
  16252. * Note that a new underlying VertexBuffer object is created each call.
  16253. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  16254. *
  16255. * Possible `kind` values :
  16256. * - BABYLON.VertexBuffer.PositionKind
  16257. * - BABYLON.VertexBuffer.UVKind
  16258. * - BABYLON.VertexBuffer.UV2Kind
  16259. * - BABYLON.VertexBuffer.UV3Kind
  16260. * - BABYLON.VertexBuffer.UV4Kind
  16261. * - BABYLON.VertexBuffer.UV5Kind
  16262. * - BABYLON.VertexBuffer.UV6Kind
  16263. * - BABYLON.VertexBuffer.ColorKind
  16264. * - BABYLON.VertexBuffer.MatricesIndicesKind
  16265. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  16266. * - BABYLON.VertexBuffer.MatricesWeightsKind
  16267. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  16268. *
  16269. * Returns the Mesh.
  16270. */
  16271. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  16272. return this;
  16273. };
  16274. /**
  16275. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  16276. * If the mesh has no geometry, it is simply returned as it is.
  16277. * The `data` are either a numeric array either a Float32Array.
  16278. * No new underlying VertexBuffer object is created.
  16279. * 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.
  16280. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  16281. *
  16282. * Possible `kind` values :
  16283. * - BABYLON.VertexBuffer.PositionKind
  16284. * - BABYLON.VertexBuffer.UVKind
  16285. * - BABYLON.VertexBuffer.UV2Kind
  16286. * - BABYLON.VertexBuffer.UV3Kind
  16287. * - BABYLON.VertexBuffer.UV4Kind
  16288. * - BABYLON.VertexBuffer.UV5Kind
  16289. * - BABYLON.VertexBuffer.UV6Kind
  16290. * - BABYLON.VertexBuffer.ColorKind
  16291. * - BABYLON.VertexBuffer.MatricesIndicesKind
  16292. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  16293. * - BABYLON.VertexBuffer.MatricesWeightsKind
  16294. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  16295. *
  16296. * Returns the Mesh.
  16297. */
  16298. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  16299. return this;
  16300. };
  16301. /**
  16302. * Sets the mesh indices.
  16303. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  16304. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  16305. * This method creates a new index buffer each call.
  16306. * Returns the Mesh.
  16307. */
  16308. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  16309. return this;
  16310. };
  16311. /** Returns false by default, used by the class Mesh.
  16312. * Returns a boolean
  16313. */
  16314. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  16315. return false;
  16316. };
  16317. /**
  16318. * Returns the mesh BoundingInfo object or creates a new one and returns it if undefined.
  16319. * Returns a BoundingInfo
  16320. */
  16321. AbstractMesh.prototype.getBoundingInfo = function () {
  16322. if (this._masterMesh) {
  16323. return this._masterMesh.getBoundingInfo();
  16324. }
  16325. if (!this._boundingInfo) {
  16326. // this._boundingInfo is being created here
  16327. this._updateBoundingInfo();
  16328. }
  16329. // cannot be null.
  16330. return this._boundingInfo;
  16331. };
  16332. /**
  16333. * Uniformly scales the mesh to fit inside of a unit cube (1 X 1 X 1 units).
  16334. * @param includeDescendants Take the hierarchy's bounding box instead of the mesh's bounding box.
  16335. */
  16336. AbstractMesh.prototype.normalizeToUnitCube = function (includeDescendants) {
  16337. if (includeDescendants === void 0) { includeDescendants = true; }
  16338. var boundingVectors = this.getHierarchyBoundingVectors(includeDescendants);
  16339. var sizeVec = boundingVectors.max.subtract(boundingVectors.min);
  16340. var maxDimension = Math.max(sizeVec.x, sizeVec.y, sizeVec.z);
  16341. if (maxDimension === 0) {
  16342. return this;
  16343. }
  16344. var scale = 1 / maxDimension;
  16345. this.scaling.scaleInPlace(scale);
  16346. return this;
  16347. };
  16348. /**
  16349. * Sets a mesh new object BoundingInfo.
  16350. * Returns the AbstractMesh.
  16351. */
  16352. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  16353. this._boundingInfo = boundingInfo;
  16354. return this;
  16355. };
  16356. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  16357. get: function () {
  16358. return (this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind));
  16359. },
  16360. enumerable: true,
  16361. configurable: true
  16362. });
  16363. AbstractMesh.prototype._preActivate = function () {
  16364. };
  16365. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  16366. };
  16367. AbstractMesh.prototype._activate = function (renderId) {
  16368. this._renderId = renderId;
  16369. };
  16370. /**
  16371. * Returns the latest update of the World matrix
  16372. * Returns a Matrix.
  16373. */
  16374. AbstractMesh.prototype.getWorldMatrix = function () {
  16375. if (this._masterMesh) {
  16376. return this._masterMesh.getWorldMatrix();
  16377. }
  16378. return _super.prototype.getWorldMatrix.call(this);
  16379. };
  16380. /**
  16381. * Returns the latest update of the World matrix determinant.
  16382. */
  16383. AbstractMesh.prototype._getWorldMatrixDeterminant = function () {
  16384. if (this._masterMesh) {
  16385. return this._masterMesh._getWorldMatrixDeterminant();
  16386. }
  16387. return _super.prototype._getWorldMatrixDeterminant.call(this);
  16388. };
  16389. // ================================== Point of View Movement =================================
  16390. /**
  16391. * Perform relative position change from the point of view of behind the front of the mesh.
  16392. * This is performed taking into account the meshes current rotation, so you do not have to care.
  16393. * Supports definition of mesh facing forward or backward.
  16394. * @param {number} amountRight
  16395. * @param {number} amountUp
  16396. * @param {number} amountForward
  16397. *
  16398. * Returns the AbstractMesh.
  16399. */
  16400. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  16401. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  16402. return this;
  16403. };
  16404. /**
  16405. * Calculate relative position change from the point of view of behind the front of the mesh.
  16406. * This is performed taking into account the meshes current rotation, so you do not have to care.
  16407. * Supports definition of mesh facing forward or backward.
  16408. * @param {number} amountRight
  16409. * @param {number} amountUp
  16410. * @param {number} amountForward
  16411. *
  16412. * Returns a new Vector3.
  16413. */
  16414. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  16415. var rotMatrix = new BABYLON.Matrix();
  16416. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  16417. rotQuaternion.toRotationMatrix(rotMatrix);
  16418. var translationDelta = BABYLON.Vector3.Zero();
  16419. var defForwardMult = this.definedFacingForward ? -1 : 1;
  16420. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  16421. return translationDelta;
  16422. };
  16423. // ================================== Point of View Rotation =================================
  16424. /**
  16425. * Perform relative rotation change from the point of view of behind the front of the mesh.
  16426. * Supports definition of mesh facing forward or backward.
  16427. * @param {number} flipBack
  16428. * @param {number} twirlClockwise
  16429. * @param {number} tiltRight
  16430. *
  16431. * Returns the AbstractMesh.
  16432. */
  16433. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  16434. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  16435. return this;
  16436. };
  16437. /**
  16438. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  16439. * Supports definition of mesh facing forward or backward.
  16440. * @param {number} flipBack
  16441. * @param {number} twirlClockwise
  16442. * @param {number} tiltRight
  16443. *
  16444. * Returns a new Vector3.
  16445. */
  16446. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  16447. var defForwardMult = this.definedFacingForward ? 1 : -1;
  16448. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  16449. };
  16450. /**
  16451. * Return the minimum and maximum world vectors of the entire hierarchy under current mesh
  16452. * @param includeDescendants Include bounding info from descendants as well (true by default).
  16453. */
  16454. AbstractMesh.prototype.getHierarchyBoundingVectors = function (includeDescendants) {
  16455. if (includeDescendants === void 0) { includeDescendants = true; }
  16456. this.computeWorldMatrix(true);
  16457. var min;
  16458. var max;
  16459. var boundingInfo = this.getBoundingInfo();
  16460. if (!this.subMeshes) {
  16461. min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  16462. max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  16463. }
  16464. else {
  16465. min = boundingInfo.boundingBox.minimumWorld;
  16466. max = boundingInfo.boundingBox.maximumWorld;
  16467. }
  16468. if (includeDescendants) {
  16469. var descendants = this.getDescendants(false);
  16470. for (var _i = 0, descendants_1 = descendants; _i < descendants_1.length; _i++) {
  16471. var descendant = descendants_1[_i];
  16472. var childMesh = descendant;
  16473. childMesh.computeWorldMatrix(true);
  16474. //make sure we have the needed params to get mix and max
  16475. if (!childMesh.getBoundingInfo || childMesh.getTotalVertices() === 0) {
  16476. continue;
  16477. }
  16478. var childBoundingInfo = childMesh.getBoundingInfo();
  16479. var boundingBox = childBoundingInfo.boundingBox;
  16480. var minBox = boundingBox.minimumWorld;
  16481. var maxBox = boundingBox.maximumWorld;
  16482. BABYLON.Tools.CheckExtends(minBox, min, max);
  16483. BABYLON.Tools.CheckExtends(maxBox, min, max);
  16484. }
  16485. }
  16486. return {
  16487. min: min,
  16488. max: max
  16489. };
  16490. };
  16491. /**
  16492. * Updates the mesh BoundingInfo object and all its children BoundingInfo objects also.
  16493. * Returns the AbstractMesh.
  16494. */
  16495. AbstractMesh.prototype._updateBoundingInfo = function () {
  16496. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  16497. this._boundingInfo.update(this.worldMatrixFromCache);
  16498. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  16499. return this;
  16500. };
  16501. /**
  16502. * Update a mesh's children BoundingInfo objects only.
  16503. * Returns the AbstractMesh.
  16504. */
  16505. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  16506. if (!this.subMeshes) {
  16507. return this;
  16508. }
  16509. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  16510. var subMesh = this.subMeshes[subIndex];
  16511. if (!subMesh.IsGlobal) {
  16512. subMesh.updateBoundingInfo(matrix);
  16513. }
  16514. }
  16515. return this;
  16516. };
  16517. AbstractMesh.prototype._afterComputeWorldMatrix = function () {
  16518. // Bounding info
  16519. this._updateBoundingInfo();
  16520. };
  16521. /**
  16522. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  16523. * A mesh is in the frustum if its bounding box intersects the frustum.
  16524. * Boolean returned.
  16525. */
  16526. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  16527. return this._boundingInfo !== null && this._boundingInfo.isInFrustum(frustumPlanes);
  16528. };
  16529. /**
  16530. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  16531. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  16532. * Boolean returned.
  16533. */
  16534. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  16535. return this._boundingInfo !== null && this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  16536. ;
  16537. };
  16538. /**
  16539. * True if the mesh intersects another mesh or a SolidParticle object.
  16540. * 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)
  16541. * includeDescendants can be set to true to test if the mesh defined in parameters intersects with the current mesh or any child meshes
  16542. * Returns a boolean.
  16543. */
  16544. AbstractMesh.prototype.intersectsMesh = function (mesh, precise, includeDescendants) {
  16545. if (precise === void 0) { precise = false; }
  16546. if (!this._boundingInfo || !mesh._boundingInfo) {
  16547. return false;
  16548. }
  16549. if (this._boundingInfo.intersects(mesh._boundingInfo, precise)) {
  16550. return true;
  16551. }
  16552. if (includeDescendants) {
  16553. for (var _i = 0, _a = this.getChildMeshes(); _i < _a.length; _i++) {
  16554. var child = _a[_i];
  16555. if (child.intersectsMesh(mesh, precise, true)) {
  16556. return true;
  16557. }
  16558. }
  16559. }
  16560. return false;
  16561. };
  16562. /**
  16563. * Returns true if the passed point (Vector3) is inside the mesh bounding box.
  16564. * Returns a boolean.
  16565. */
  16566. AbstractMesh.prototype.intersectsPoint = function (point) {
  16567. if (!this._boundingInfo) {
  16568. return false;
  16569. }
  16570. return this._boundingInfo.intersectsPoint(point);
  16571. };
  16572. AbstractMesh.prototype.getPhysicsImpostor = function () {
  16573. return this.physicsImpostor;
  16574. };
  16575. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  16576. if (camera === void 0) { camera = null; }
  16577. if (!camera) {
  16578. camera = this.getScene().activeCamera;
  16579. }
  16580. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  16581. };
  16582. /**
  16583. * Returns the distance from the mesh to the active camera.
  16584. * Returns a float.
  16585. */
  16586. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  16587. if (camera === void 0) { camera = null; }
  16588. if (!camera) {
  16589. camera = this.getScene().activeCamera;
  16590. }
  16591. return this.absolutePosition.subtract(camera.position).length();
  16592. };
  16593. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  16594. if (!this.physicsImpostor) {
  16595. return this;
  16596. }
  16597. this.physicsImpostor.applyImpulse(force, contactPoint);
  16598. return this;
  16599. };
  16600. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  16601. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  16602. return this;
  16603. }
  16604. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  16605. mainPivot: pivot1,
  16606. connectedPivot: pivot2,
  16607. nativeParams: options
  16608. });
  16609. return this;
  16610. };
  16611. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  16612. // Collisions
  16613. /**
  16614. * Property checkCollisions : Boolean, whether the camera should check the collisions against the mesh.
  16615. * Default `false`.
  16616. */
  16617. get: function () {
  16618. return this._checkCollisions;
  16619. },
  16620. set: function (collisionEnabled) {
  16621. this._checkCollisions = collisionEnabled;
  16622. if (this.getScene().workerCollisions) {
  16623. this.getScene().collisionCoordinator.onMeshUpdated(this);
  16624. }
  16625. },
  16626. enumerable: true,
  16627. configurable: true
  16628. });
  16629. Object.defineProperty(AbstractMesh.prototype, "collider", {
  16630. /**
  16631. * Gets Collider object used to compute collisions (not physics)
  16632. */
  16633. get: function () {
  16634. return this._collider;
  16635. },
  16636. enumerable: true,
  16637. configurable: true
  16638. });
  16639. AbstractMesh.prototype.moveWithCollisions = function (displacement) {
  16640. var globalPosition = this.getAbsolutePosition();
  16641. globalPosition.addToRef(this.ellipsoidOffset, this._oldPositionForCollisions);
  16642. if (!this._collider) {
  16643. this._collider = new BABYLON.Collider();
  16644. }
  16645. this._collider._radius = this.ellipsoid;
  16646. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, displacement, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  16647. return this;
  16648. };
  16649. // Submeshes octree
  16650. /**
  16651. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  16652. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree.
  16653. * Returns an Octree of submeshes.
  16654. */
  16655. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  16656. if (maxCapacity === void 0) { maxCapacity = 64; }
  16657. if (maxDepth === void 0) { maxDepth = 2; }
  16658. if (!this._submeshesOctree) {
  16659. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  16660. }
  16661. this.computeWorldMatrix(true);
  16662. var boundingInfo = this.getBoundingInfo();
  16663. // Update octree
  16664. var bbox = boundingInfo.boundingBox;
  16665. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  16666. return this._submeshesOctree;
  16667. };
  16668. // Collisions
  16669. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  16670. this._generatePointsArray();
  16671. if (!this._positions) {
  16672. return this;
  16673. }
  16674. // Transformation
  16675. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  16676. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  16677. subMesh._lastColliderWorldVertices = [];
  16678. subMesh._trianglePlanes = [];
  16679. var start = subMesh.verticesStart;
  16680. var end = (subMesh.verticesStart + subMesh.verticesCount);
  16681. for (var i = start; i < end; i++) {
  16682. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  16683. }
  16684. }
  16685. // Collide
  16686. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  16687. if (collider.collisionFound) {
  16688. collider.collidedMesh = this;
  16689. }
  16690. return this;
  16691. };
  16692. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  16693. var subMeshes;
  16694. var len;
  16695. // Octrees
  16696. if (this._submeshesOctree && this.useOctreeForCollisions) {
  16697. var radius = collider._velocityWorldLength + Math.max(collider._radius.x, collider._radius.y, collider._radius.z);
  16698. var intersections = this._submeshesOctree.intersects(collider._basePointWorld, radius);
  16699. len = intersections.length;
  16700. subMeshes = intersections.data;
  16701. }
  16702. else {
  16703. subMeshes = this.subMeshes;
  16704. len = subMeshes.length;
  16705. }
  16706. for (var index = 0; index < len; index++) {
  16707. var subMesh = subMeshes[index];
  16708. // Bounding test
  16709. if (len > 1 && !subMesh._checkCollision(collider))
  16710. continue;
  16711. this._collideForSubMesh(subMesh, transformMatrix, collider);
  16712. }
  16713. return this;
  16714. };
  16715. AbstractMesh.prototype._checkCollision = function (collider) {
  16716. // Bounding box test
  16717. if (!this._boundingInfo || !this._boundingInfo._checkCollision(collider))
  16718. return this;
  16719. // Transformation matrix
  16720. BABYLON.Matrix.ScalingToRef(1.0 / collider._radius.x, 1.0 / collider._radius.y, 1.0 / collider._radius.z, this._collisionsScalingMatrix);
  16721. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  16722. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  16723. return this;
  16724. };
  16725. // Picking
  16726. AbstractMesh.prototype._generatePointsArray = function () {
  16727. return false;
  16728. };
  16729. /**
  16730. * Checks if the passed Ray intersects with the mesh.
  16731. * Returns an object PickingInfo.
  16732. */
  16733. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  16734. var pickingInfo = new BABYLON.PickingInfo();
  16735. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  16736. return pickingInfo;
  16737. }
  16738. if (!this._generatePointsArray()) {
  16739. return pickingInfo;
  16740. }
  16741. var intersectInfo = null;
  16742. // Octrees
  16743. var subMeshes;
  16744. var len;
  16745. if (this._submeshesOctree && this.useOctreeForPicking) {
  16746. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  16747. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  16748. len = intersections.length;
  16749. subMeshes = intersections.data;
  16750. }
  16751. else {
  16752. subMeshes = this.subMeshes;
  16753. len = subMeshes.length;
  16754. }
  16755. for (var index = 0; index < len; index++) {
  16756. var subMesh = subMeshes[index];
  16757. // Bounding test
  16758. if (len > 1 && !subMesh.canIntersects(ray))
  16759. continue;
  16760. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  16761. if (currentIntersectInfo) {
  16762. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  16763. intersectInfo = currentIntersectInfo;
  16764. intersectInfo.subMeshId = index;
  16765. if (fastCheck) {
  16766. break;
  16767. }
  16768. }
  16769. }
  16770. }
  16771. if (intersectInfo) {
  16772. // Get picked point
  16773. var world = this.getWorldMatrix();
  16774. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  16775. var direction = ray.direction.clone();
  16776. direction = direction.scale(intersectInfo.distance);
  16777. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  16778. var pickedPoint = worldOrigin.add(worldDirection);
  16779. // Return result
  16780. pickingInfo.hit = true;
  16781. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  16782. pickingInfo.pickedPoint = pickedPoint;
  16783. pickingInfo.pickedMesh = this;
  16784. pickingInfo.bu = intersectInfo.bu || 0;
  16785. pickingInfo.bv = intersectInfo.bv || 0;
  16786. pickingInfo.faceId = intersectInfo.faceId;
  16787. pickingInfo.subMeshId = intersectInfo.subMeshId;
  16788. return pickingInfo;
  16789. }
  16790. return pickingInfo;
  16791. };
  16792. /**
  16793. * Clones the mesh, used by the class Mesh.
  16794. * Just returns `null` for an AbstractMesh.
  16795. */
  16796. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  16797. return null;
  16798. };
  16799. /**
  16800. * Disposes all the mesh submeshes.
  16801. * Returns the AbstractMesh.
  16802. */
  16803. AbstractMesh.prototype.releaseSubMeshes = function () {
  16804. if (this.subMeshes) {
  16805. while (this.subMeshes.length) {
  16806. this.subMeshes[0].dispose();
  16807. }
  16808. }
  16809. else {
  16810. this.subMeshes = new Array();
  16811. }
  16812. return this;
  16813. };
  16814. /**
  16815. * Disposes the AbstractMesh.
  16816. * By default, all the mesh children are also disposed unless the parameter `doNotRecurse` is set to `true`.
  16817. * Returns nothing.
  16818. */
  16819. AbstractMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  16820. var _this = this;
  16821. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  16822. var index;
  16823. // Action manager
  16824. if (this.actionManager !== undefined && this.actionManager !== null) {
  16825. this.actionManager.dispose();
  16826. this.actionManager = null;
  16827. }
  16828. // Skeleton
  16829. this.skeleton = null;
  16830. // Physics
  16831. if (this.physicsImpostor) {
  16832. this.physicsImpostor.dispose();
  16833. }
  16834. // Intersections in progress
  16835. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  16836. var other = this._intersectionsInProgress[index];
  16837. var pos = other._intersectionsInProgress.indexOf(this);
  16838. other._intersectionsInProgress.splice(pos, 1);
  16839. }
  16840. this._intersectionsInProgress = [];
  16841. // Lights
  16842. var lights = this.getScene().lights;
  16843. lights.forEach(function (light) {
  16844. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  16845. if (meshIndex !== -1) {
  16846. light.includedOnlyMeshes.splice(meshIndex, 1);
  16847. }
  16848. meshIndex = light.excludedMeshes.indexOf(_this);
  16849. if (meshIndex !== -1) {
  16850. light.excludedMeshes.splice(meshIndex, 1);
  16851. }
  16852. // Shadow generators
  16853. var generator = light.getShadowGenerator();
  16854. if (generator) {
  16855. var shadowMap = generator.getShadowMap();
  16856. if (shadowMap && shadowMap.renderList) {
  16857. meshIndex = shadowMap.renderList.indexOf(_this);
  16858. if (meshIndex !== -1) {
  16859. shadowMap.renderList.splice(meshIndex, 1);
  16860. }
  16861. }
  16862. }
  16863. });
  16864. // Edges
  16865. if (this._edgesRenderer) {
  16866. this._edgesRenderer.dispose();
  16867. this._edgesRenderer = null;
  16868. }
  16869. // SubMeshes
  16870. if (this.getClassName() !== "InstancedMesh") {
  16871. this.releaseSubMeshes();
  16872. }
  16873. // Octree
  16874. var sceneOctree = this.getScene().selectionOctree;
  16875. if (sceneOctree !== undefined && sceneOctree !== null) {
  16876. var index = sceneOctree.dynamicContent.indexOf(this);
  16877. if (index !== -1) {
  16878. sceneOctree.dynamicContent.splice(index, 1);
  16879. }
  16880. }
  16881. // Query
  16882. var engine = this.getScene().getEngine();
  16883. if (this._occlusionQuery) {
  16884. this._isOcclusionQueryInProgress = false;
  16885. engine.deleteQuery(this._occlusionQuery);
  16886. this._occlusionQuery = null;
  16887. }
  16888. // Engine
  16889. engine.wipeCaches();
  16890. // Remove from scene
  16891. this.getScene().removeMesh(this);
  16892. if (disposeMaterialAndTextures) {
  16893. if (this.material) {
  16894. this.material.dispose(false, true);
  16895. }
  16896. }
  16897. if (!doNotRecurse) {
  16898. // Particles
  16899. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  16900. if (this.getScene().particleSystems[index].emitter === this) {
  16901. this.getScene().particleSystems[index].dispose();
  16902. index--;
  16903. }
  16904. }
  16905. }
  16906. // facet data
  16907. if (this._facetDataEnabled) {
  16908. this.disableFacetData();
  16909. }
  16910. this.onAfterWorldMatrixUpdateObservable.clear();
  16911. this.onCollideObservable.clear();
  16912. this.onCollisionPositionChangeObservable.clear();
  16913. this._isDisposed = true;
  16914. _super.prototype.dispose.call(this, doNotRecurse);
  16915. };
  16916. /**
  16917. * Adds the passed mesh as a child to the current mesh.
  16918. * Returns the AbstractMesh.
  16919. */
  16920. AbstractMesh.prototype.addChild = function (mesh) {
  16921. mesh.setParent(this);
  16922. return this;
  16923. };
  16924. /**
  16925. * Removes the passed mesh from the current mesh children list.
  16926. * Returns the AbstractMesh.
  16927. */
  16928. AbstractMesh.prototype.removeChild = function (mesh) {
  16929. mesh.setParent(null);
  16930. return this;
  16931. };
  16932. // Facet data
  16933. /**
  16934. * Initialize the facet data arrays : facetNormals, facetPositions and facetPartitioning.
  16935. * Returns the AbstractMesh.
  16936. */
  16937. AbstractMesh.prototype._initFacetData = function () {
  16938. if (!this._facetNormals) {
  16939. this._facetNormals = new Array();
  16940. }
  16941. if (!this._facetPositions) {
  16942. this._facetPositions = new Array();
  16943. }
  16944. if (!this._facetPartitioning) {
  16945. this._facetPartitioning = new Array();
  16946. }
  16947. this._facetNb = (this.getIndices().length / 3) | 0;
  16948. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  16949. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  16950. for (var f = 0; f < this._facetNb; f++) {
  16951. this._facetNormals[f] = BABYLON.Vector3.Zero();
  16952. this._facetPositions[f] = BABYLON.Vector3.Zero();
  16953. }
  16954. this._facetDataEnabled = true;
  16955. return this;
  16956. };
  16957. /**
  16958. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  16959. * This method can be called within the render loop.
  16960. * 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.
  16961. * Returns the AbstractMesh.
  16962. */
  16963. AbstractMesh.prototype.updateFacetData = function () {
  16964. if (!this._facetDataEnabled) {
  16965. this._initFacetData();
  16966. }
  16967. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  16968. var indices = this.getIndices();
  16969. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  16970. var bInfo = this.getBoundingInfo();
  16971. if (this._facetDepthSort && !this._facetDepthSortEnabled) {
  16972. // init arrays, matrix and sort function on first call
  16973. this._facetDepthSortEnabled = true;
  16974. if (indices instanceof Uint16Array) {
  16975. this._depthSortedIndices = new Uint16Array(indices);
  16976. }
  16977. else if (indices instanceof Uint32Array) {
  16978. this._depthSortedIndices = new Uint32Array(indices);
  16979. }
  16980. else {
  16981. var needs32bits = false;
  16982. for (var i = 0; i < indices.length; i++) {
  16983. if (indices[i] > 65535) {
  16984. needs32bits = true;
  16985. break;
  16986. }
  16987. }
  16988. if (needs32bits) {
  16989. this._depthSortedIndices = new Uint32Array(indices);
  16990. }
  16991. else {
  16992. this._depthSortedIndices = new Uint16Array(indices);
  16993. }
  16994. }
  16995. this._facetDepthSortFunction = function (f1, f2) {
  16996. return (f2.sqDistance - f1.sqDistance);
  16997. };
  16998. if (!this._facetDepthSortFrom) {
  16999. var camera = this.getScene().activeCamera;
  17000. this._facetDepthSortFrom = (camera) ? camera.position : BABYLON.Vector3.Zero();
  17001. }
  17002. this._depthSortedFacets = [];
  17003. for (var f = 0; f < this._facetNb; f++) {
  17004. var depthSortedFacet = { ind: f * 3, sqDistance: 0.0 };
  17005. this._depthSortedFacets.push(depthSortedFacet);
  17006. }
  17007. this._invertedMatrix = BABYLON.Matrix.Identity();
  17008. this._facetDepthSortOrigin = BABYLON.Vector3.Zero();
  17009. }
  17010. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  17011. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  17012. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  17013. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  17014. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  17015. this._subDiv.max = this._partitioningSubdivisions;
  17016. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  17017. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  17018. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  17019. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  17020. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  17021. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  17022. // set the parameters for ComputeNormals()
  17023. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  17024. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  17025. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  17026. this._facetParameters.bInfo = bInfo;
  17027. this._facetParameters.bbSize = this._bbSize;
  17028. this._facetParameters.subDiv = this._subDiv;
  17029. this._facetParameters.ratio = this.partitioningBBoxRatio;
  17030. this._facetParameters.depthSort = this._facetDepthSort;
  17031. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  17032. this.computeWorldMatrix(true);
  17033. this._worldMatrix.invertToRef(this._invertedMatrix);
  17034. BABYLON.Vector3.TransformCoordinatesToRef(this._facetDepthSortFrom, this._invertedMatrix, this._facetDepthSortOrigin);
  17035. this._facetParameters.distanceTo = this._facetDepthSortOrigin;
  17036. }
  17037. this._facetParameters.depthSortedFacets = this._depthSortedFacets;
  17038. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  17039. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  17040. this._depthSortedFacets.sort(this._facetDepthSortFunction);
  17041. var l = (this._depthSortedIndices.length / 3) | 0;
  17042. for (var f = 0; f < l; f++) {
  17043. var sind = this._depthSortedFacets[f].ind;
  17044. this._depthSortedIndices[f * 3] = indices[sind];
  17045. this._depthSortedIndices[f * 3 + 1] = indices[sind + 1];
  17046. this._depthSortedIndices[f * 3 + 2] = indices[sind + 2];
  17047. }
  17048. this.updateIndices(this._depthSortedIndices);
  17049. }
  17050. return this;
  17051. };
  17052. /**
  17053. * Returns the facetLocalNormals array.
  17054. * The normals are expressed in the mesh local space.
  17055. */
  17056. AbstractMesh.prototype.getFacetLocalNormals = function () {
  17057. if (!this._facetNormals) {
  17058. this.updateFacetData();
  17059. }
  17060. return this._facetNormals;
  17061. };
  17062. /**
  17063. * Returns the facetLocalPositions array.
  17064. * The facet positions are expressed in the mesh local space.
  17065. */
  17066. AbstractMesh.prototype.getFacetLocalPositions = function () {
  17067. if (!this._facetPositions) {
  17068. this.updateFacetData();
  17069. }
  17070. return this._facetPositions;
  17071. };
  17072. /**
  17073. * Returns the facetLocalPartioning array.
  17074. */
  17075. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  17076. if (!this._facetPartitioning) {
  17077. this.updateFacetData();
  17078. }
  17079. return this._facetPartitioning;
  17080. };
  17081. /**
  17082. * Returns the i-th facet position in the world system.
  17083. * This method allocates a new Vector3 per call.
  17084. */
  17085. AbstractMesh.prototype.getFacetPosition = function (i) {
  17086. var pos = BABYLON.Vector3.Zero();
  17087. this.getFacetPositionToRef(i, pos);
  17088. return pos;
  17089. };
  17090. /**
  17091. * Sets the reference Vector3 with the i-th facet position in the world system.
  17092. * Returns the AbstractMesh.
  17093. */
  17094. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  17095. var localPos = (this.getFacetLocalPositions())[i];
  17096. var world = this.getWorldMatrix();
  17097. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  17098. return this;
  17099. };
  17100. /**
  17101. * Returns the i-th facet normal in the world system.
  17102. * This method allocates a new Vector3 per call.
  17103. */
  17104. AbstractMesh.prototype.getFacetNormal = function (i) {
  17105. var norm = BABYLON.Vector3.Zero();
  17106. this.getFacetNormalToRef(i, norm);
  17107. return norm;
  17108. };
  17109. /**
  17110. * Sets the reference Vector3 with the i-th facet normal in the world system.
  17111. * Returns the AbstractMesh.
  17112. */
  17113. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  17114. var localNorm = (this.getFacetLocalNormals())[i];
  17115. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  17116. return this;
  17117. };
  17118. /**
  17119. * 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).
  17120. */
  17121. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  17122. var bInfo = this.getBoundingInfo();
  17123. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  17124. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  17125. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  17126. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  17127. return null;
  17128. }
  17129. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  17130. };
  17131. /**
  17132. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found.
  17133. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) World projection on the facet.
  17134. * 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.
  17135. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  17136. * 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.
  17137. */
  17138. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  17139. if (checkFace === void 0) { checkFace = false; }
  17140. if (facing === void 0) { facing = true; }
  17141. var world = this.getWorldMatrix();
  17142. var invMat = BABYLON.Tmp.Matrix[5];
  17143. world.invertToRef(invMat);
  17144. var invVect = BABYLON.Tmp.Vector3[8];
  17145. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  17146. var closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  17147. if (projected) {
  17148. // tranform the local computed projected vector to world coordinates
  17149. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  17150. }
  17151. return closest;
  17152. };
  17153. /**
  17154. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found.
  17155. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) local projection on the facet.
  17156. * 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.
  17157. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  17158. * 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.
  17159. */
  17160. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  17161. if (checkFace === void 0) { checkFace = false; }
  17162. if (facing === void 0) { facing = true; }
  17163. var closest = null;
  17164. var tmpx = 0.0;
  17165. var tmpy = 0.0;
  17166. var tmpz = 0.0;
  17167. var d = 0.0; // tmp dot facet normal * facet position
  17168. var t0 = 0.0;
  17169. var projx = 0.0;
  17170. var projy = 0.0;
  17171. var projz = 0.0;
  17172. // Get all the facets in the same partitioning block than (x, y, z)
  17173. var facetPositions = this.getFacetLocalPositions();
  17174. var facetNormals = this.getFacetLocalNormals();
  17175. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  17176. if (!facetsInBlock) {
  17177. return null;
  17178. }
  17179. // Get the closest facet to (x, y, z)
  17180. var shortest = Number.MAX_VALUE; // init distance vars
  17181. var tmpDistance = shortest;
  17182. var fib; // current facet in the block
  17183. var norm; // current facet normal
  17184. var p0; // current facet barycenter position
  17185. // loop on all the facets in the current partitioning block
  17186. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  17187. fib = facetsInBlock[idx];
  17188. norm = facetNormals[fib];
  17189. p0 = facetPositions[fib];
  17190. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  17191. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  17192. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  17193. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  17194. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  17195. projx = x + norm.x * t0;
  17196. projy = y + norm.y * t0;
  17197. projz = z + norm.z * t0;
  17198. tmpx = projx - x;
  17199. tmpy = projy - y;
  17200. tmpz = projz - z;
  17201. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  17202. if (tmpDistance < shortest) {
  17203. shortest = tmpDistance;
  17204. closest = fib;
  17205. if (projected) {
  17206. projected.x = projx;
  17207. projected.y = projy;
  17208. projected.z = projz;
  17209. }
  17210. }
  17211. }
  17212. }
  17213. return closest;
  17214. };
  17215. /**
  17216. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  17217. */
  17218. AbstractMesh.prototype.getFacetDataParameters = function () {
  17219. return this._facetParameters;
  17220. };
  17221. /**
  17222. * Disables the feature FacetData and frees the related memory.
  17223. * Returns the AbstractMesh.
  17224. */
  17225. AbstractMesh.prototype.disableFacetData = function () {
  17226. if (this._facetDataEnabled) {
  17227. this._facetDataEnabled = false;
  17228. this._facetPositions = new Array();
  17229. this._facetNormals = new Array();
  17230. this._facetPartitioning = new Array();
  17231. this._facetParameters = null;
  17232. this._depthSortedIndices = new Uint32Array(0);
  17233. }
  17234. return this;
  17235. };
  17236. /**
  17237. * Updates the AbstractMesh indices array. Actually, used by the Mesh object.
  17238. * Returns the mesh.
  17239. */
  17240. AbstractMesh.prototype.updateIndices = function (indices) {
  17241. return this;
  17242. };
  17243. /**
  17244. * The mesh Geometry. Actually used by the Mesh object.
  17245. * Returns a blank geometry object.
  17246. */
  17247. /**
  17248. * Creates new normals data for the mesh.
  17249. * @param updatable.
  17250. */
  17251. AbstractMesh.prototype.createNormals = function (updatable) {
  17252. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  17253. var indices = this.getIndices();
  17254. var normals;
  17255. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  17256. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  17257. }
  17258. else {
  17259. normals = [];
  17260. }
  17261. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  17262. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  17263. };
  17264. /**
  17265. * Align the mesh with a normal.
  17266. * Returns the mesh.
  17267. */
  17268. AbstractMesh.prototype.alignWithNormal = function (normal, upDirection) {
  17269. if (!upDirection) {
  17270. upDirection = BABYLON.Axis.Y;
  17271. }
  17272. var axisX = BABYLON.Tmp.Vector3[0];
  17273. var axisZ = BABYLON.Tmp.Vector3[1];
  17274. BABYLON.Vector3.CrossToRef(upDirection, normal, axisZ);
  17275. BABYLON.Vector3.CrossToRef(normal, axisZ, axisX);
  17276. if (this.rotationQuaternion) {
  17277. BABYLON.Quaternion.RotationQuaternionFromAxisToRef(axisX, normal, axisZ, this.rotationQuaternion);
  17278. }
  17279. else {
  17280. BABYLON.Vector3.RotationFromAxisToRef(axisX, normal, axisZ, this.rotation);
  17281. }
  17282. return this;
  17283. };
  17284. AbstractMesh.prototype.checkOcclusionQuery = function () {
  17285. var engine = this.getEngine();
  17286. if (engine.webGLVersion < 2 || this.occlusionType === AbstractMesh.OCCLUSION_TYPE_NONE) {
  17287. this._isOccluded = false;
  17288. return;
  17289. }
  17290. if (this.isOcclusionQueryInProgress && this._occlusionQuery) {
  17291. var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);
  17292. if (isOcclusionQueryAvailable) {
  17293. var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);
  17294. this._isOcclusionQueryInProgress = false;
  17295. this._occlusionInternalRetryCounter = 0;
  17296. this._isOccluded = occlusionQueryResult === 1 ? false : true;
  17297. }
  17298. else {
  17299. this._occlusionInternalRetryCounter++;
  17300. if (this.occlusionRetryCount !== -1 && this._occlusionInternalRetryCounter > this.occlusionRetryCount) {
  17301. this._isOcclusionQueryInProgress = false;
  17302. this._occlusionInternalRetryCounter = 0;
  17303. // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop)
  17304. // if strict continue the last state of the object.
  17305. this._isOccluded = this.occlusionType === AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : this._isOccluded;
  17306. }
  17307. else {
  17308. return;
  17309. }
  17310. }
  17311. }
  17312. var scene = this.getScene();
  17313. var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();
  17314. if (!this._occlusionQuery) {
  17315. this._occlusionQuery = engine.createQuery();
  17316. }
  17317. engine.beginOcclusionQuery(this.occlusionQueryAlgorithmType, this._occlusionQuery);
  17318. occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);
  17319. engine.endOcclusionQuery(this.occlusionQueryAlgorithmType);
  17320. this._isOcclusionQueryInProgress = true;
  17321. };
  17322. AbstractMesh.OCCLUSION_TYPE_NONE = 0;
  17323. AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1;
  17324. AbstractMesh.OCCLUSION_TYPE_STRICT = 2;
  17325. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;
  17326. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;
  17327. return AbstractMesh;
  17328. }(BABYLON.TransformNode));
  17329. BABYLON.AbstractMesh = AbstractMesh;
  17330. })(BABYLON || (BABYLON = {}));
  17331. //# sourceMappingURL=babylon.abstractMesh.js.map
  17332. var BABYLON;
  17333. (function (BABYLON) {
  17334. var Light = /** @class */ (function (_super) {
  17335. __extends(Light, _super);
  17336. /**
  17337. * Creates a Light object in the scene.
  17338. * Documentation : http://doc.babylonjs.com/tutorials/lights
  17339. */
  17340. function Light(name, scene) {
  17341. var _this = _super.call(this, name, scene) || this;
  17342. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  17343. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  17344. _this.intensity = 1.0;
  17345. _this.range = Number.MAX_VALUE;
  17346. /**
  17347. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  17348. * of light.
  17349. */
  17350. _this._photometricScale = 1.0;
  17351. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  17352. _this._radius = 0.00001;
  17353. _this.renderPriority = 0;
  17354. /**
  17355. * Defines wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  17356. * the current shadow generator.
  17357. */
  17358. _this.shadowEnabled = true;
  17359. _this._excludeWithLayerMask = 0;
  17360. _this._includeOnlyWithLayerMask = 0;
  17361. _this._lightmapMode = 0;
  17362. _this._excludedMeshesIds = new Array();
  17363. _this._includedOnlyMeshesIds = new Array();
  17364. _this.getScene().addLight(_this);
  17365. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  17366. _this._buildUniformLayout();
  17367. _this.includedOnlyMeshes = new Array();
  17368. _this.excludedMeshes = new Array();
  17369. _this._resyncMeshes();
  17370. return _this;
  17371. }
  17372. Object.defineProperty(Light, "LIGHTMAP_DEFAULT", {
  17373. /**
  17374. * If every light affecting the material is in this lightmapMode,
  17375. * material.lightmapTexture adds or multiplies
  17376. * (depends on material.useLightmapAsShadowmap)
  17377. * after every other light calculations.
  17378. */
  17379. get: function () {
  17380. return Light._LIGHTMAP_DEFAULT;
  17381. },
  17382. enumerable: true,
  17383. configurable: true
  17384. });
  17385. Object.defineProperty(Light, "LIGHTMAP_SPECULAR", {
  17386. /**
  17387. * material.lightmapTexture as only diffuse lighting from this light
  17388. * adds only specular lighting from this light
  17389. * adds dynamic shadows
  17390. */
  17391. get: function () {
  17392. return Light._LIGHTMAP_SPECULAR;
  17393. },
  17394. enumerable: true,
  17395. configurable: true
  17396. });
  17397. Object.defineProperty(Light, "LIGHTMAP_SHADOWSONLY", {
  17398. /**
  17399. * material.lightmapTexture as only lighting
  17400. * no light calculation from this light
  17401. * only adds dynamic shadows from this light
  17402. */
  17403. get: function () {
  17404. return Light._LIGHTMAP_SHADOWSONLY;
  17405. },
  17406. enumerable: true,
  17407. configurable: true
  17408. });
  17409. Object.defineProperty(Light, "INTENSITYMODE_AUTOMATIC", {
  17410. /**
  17411. * Each light type uses the default quantity according to its type:
  17412. * point/spot lights use luminous intensity
  17413. * directional lights use illuminance
  17414. */
  17415. get: function () {
  17416. return Light._INTENSITYMODE_AUTOMATIC;
  17417. },
  17418. enumerable: true,
  17419. configurable: true
  17420. });
  17421. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSPOWER", {
  17422. /**
  17423. * lumen (lm)
  17424. */
  17425. get: function () {
  17426. return Light._INTENSITYMODE_LUMINOUSPOWER;
  17427. },
  17428. enumerable: true,
  17429. configurable: true
  17430. });
  17431. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSINTENSITY", {
  17432. /**
  17433. * candela (lm/sr)
  17434. */
  17435. get: function () {
  17436. return Light._INTENSITYMODE_LUMINOUSINTENSITY;
  17437. },
  17438. enumerable: true,
  17439. configurable: true
  17440. });
  17441. Object.defineProperty(Light, "INTENSITYMODE_ILLUMINANCE", {
  17442. /**
  17443. * lux (lm/m^2)
  17444. */
  17445. get: function () {
  17446. return Light._INTENSITYMODE_ILLUMINANCE;
  17447. },
  17448. enumerable: true,
  17449. configurable: true
  17450. });
  17451. Object.defineProperty(Light, "INTENSITYMODE_LUMINANCE", {
  17452. /**
  17453. * nit (cd/m^2)
  17454. */
  17455. get: function () {
  17456. return Light._INTENSITYMODE_LUMINANCE;
  17457. },
  17458. enumerable: true,
  17459. configurable: true
  17460. });
  17461. Object.defineProperty(Light, "LIGHTTYPEID_POINTLIGHT", {
  17462. /**
  17463. * Light type const id of the point light.
  17464. */
  17465. get: function () {
  17466. return Light._LIGHTTYPEID_POINTLIGHT;
  17467. },
  17468. enumerable: true,
  17469. configurable: true
  17470. });
  17471. Object.defineProperty(Light, "LIGHTTYPEID_DIRECTIONALLIGHT", {
  17472. /**
  17473. * Light type const id of the directional light.
  17474. */
  17475. get: function () {
  17476. return Light._LIGHTTYPEID_DIRECTIONALLIGHT;
  17477. },
  17478. enumerable: true,
  17479. configurable: true
  17480. });
  17481. Object.defineProperty(Light, "LIGHTTYPEID_SPOTLIGHT", {
  17482. /**
  17483. * Light type const id of the spot light.
  17484. */
  17485. get: function () {
  17486. return Light._LIGHTTYPEID_SPOTLIGHT;
  17487. },
  17488. enumerable: true,
  17489. configurable: true
  17490. });
  17491. Object.defineProperty(Light, "LIGHTTYPEID_HEMISPHERICLIGHT", {
  17492. /**
  17493. * Light type const id of the hemispheric light.
  17494. */
  17495. get: function () {
  17496. return Light._LIGHTTYPEID_HEMISPHERICLIGHT;
  17497. },
  17498. enumerable: true,
  17499. configurable: true
  17500. });
  17501. Object.defineProperty(Light.prototype, "intensityMode", {
  17502. /**
  17503. * Gets the photometric scale used to interpret the intensity.
  17504. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  17505. */
  17506. get: function () {
  17507. return this._intensityMode;
  17508. },
  17509. /**
  17510. * Sets the photometric scale used to interpret the intensity.
  17511. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  17512. */
  17513. set: function (value) {
  17514. this._intensityMode = value;
  17515. this._computePhotometricScale();
  17516. },
  17517. enumerable: true,
  17518. configurable: true
  17519. });
  17520. ;
  17521. ;
  17522. Object.defineProperty(Light.prototype, "radius", {
  17523. /**
  17524. * Gets the light radius used by PBR Materials to simulate soft area lights.
  17525. */
  17526. get: function () {
  17527. return this._radius;
  17528. },
  17529. /**
  17530. * sets the light radius used by PBR Materials to simulate soft area lights.
  17531. */
  17532. set: function (value) {
  17533. this._radius = value;
  17534. this._computePhotometricScale();
  17535. },
  17536. enumerable: true,
  17537. configurable: true
  17538. });
  17539. ;
  17540. ;
  17541. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  17542. get: function () {
  17543. return this._includedOnlyMeshes;
  17544. },
  17545. set: function (value) {
  17546. this._includedOnlyMeshes = value;
  17547. this._hookArrayForIncludedOnly(value);
  17548. },
  17549. enumerable: true,
  17550. configurable: true
  17551. });
  17552. Object.defineProperty(Light.prototype, "excludedMeshes", {
  17553. get: function () {
  17554. return this._excludedMeshes;
  17555. },
  17556. set: function (value) {
  17557. this._excludedMeshes = value;
  17558. this._hookArrayForExcluded(value);
  17559. },
  17560. enumerable: true,
  17561. configurable: true
  17562. });
  17563. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  17564. get: function () {
  17565. return this._excludeWithLayerMask;
  17566. },
  17567. set: function (value) {
  17568. this._excludeWithLayerMask = value;
  17569. this._resyncMeshes();
  17570. },
  17571. enumerable: true,
  17572. configurable: true
  17573. });
  17574. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  17575. get: function () {
  17576. return this._includeOnlyWithLayerMask;
  17577. },
  17578. set: function (value) {
  17579. this._includeOnlyWithLayerMask = value;
  17580. this._resyncMeshes();
  17581. },
  17582. enumerable: true,
  17583. configurable: true
  17584. });
  17585. Object.defineProperty(Light.prototype, "lightmapMode", {
  17586. get: function () {
  17587. return this._lightmapMode;
  17588. },
  17589. set: function (value) {
  17590. if (this._lightmapMode === value) {
  17591. return;
  17592. }
  17593. this._lightmapMode = value;
  17594. this._markMeshesAsLightDirty();
  17595. },
  17596. enumerable: true,
  17597. configurable: true
  17598. });
  17599. Light.prototype._buildUniformLayout = function () {
  17600. // Overridden
  17601. };
  17602. /**
  17603. * Returns the string "Light".
  17604. */
  17605. Light.prototype.getClassName = function () {
  17606. return "Light";
  17607. };
  17608. /**
  17609. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  17610. */
  17611. Light.prototype.toString = function (fullDetails) {
  17612. var ret = "Name: " + this.name;
  17613. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  17614. if (this.animations) {
  17615. for (var i = 0; i < this.animations.length; i++) {
  17616. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  17617. }
  17618. }
  17619. if (fullDetails) {
  17620. }
  17621. return ret;
  17622. };
  17623. /**
  17624. * Set the enabled state of this node.
  17625. * @param {boolean} value - the new enabled state
  17626. * @see isEnabled
  17627. */
  17628. Light.prototype.setEnabled = function (value) {
  17629. _super.prototype.setEnabled.call(this, value);
  17630. this._resyncMeshes();
  17631. };
  17632. /**
  17633. * Returns the Light associated shadow generator.
  17634. */
  17635. Light.prototype.getShadowGenerator = function () {
  17636. return this._shadowGenerator;
  17637. };
  17638. /**
  17639. * Returns a Vector3, the absolute light position in the World.
  17640. */
  17641. Light.prototype.getAbsolutePosition = function () {
  17642. return BABYLON.Vector3.Zero();
  17643. };
  17644. Light.prototype.transferToEffect = function (effect, lightIndex) {
  17645. };
  17646. Light.prototype._getWorldMatrix = function () {
  17647. return BABYLON.Matrix.Identity();
  17648. };
  17649. /**
  17650. * Boolean : True if the light will affect the passed mesh.
  17651. */
  17652. Light.prototype.canAffectMesh = function (mesh) {
  17653. if (!mesh) {
  17654. return true;
  17655. }
  17656. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  17657. return false;
  17658. }
  17659. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  17660. return false;
  17661. }
  17662. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  17663. return false;
  17664. }
  17665. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  17666. return false;
  17667. }
  17668. return true;
  17669. };
  17670. /**
  17671. * Returns the light World matrix.
  17672. */
  17673. Light.prototype.getWorldMatrix = function () {
  17674. this._currentRenderId = this.getScene().getRenderId();
  17675. var worldMatrix = this._getWorldMatrix();
  17676. if (this.parent && this.parent.getWorldMatrix) {
  17677. if (!this._parentedWorldMatrix) {
  17678. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  17679. }
  17680. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  17681. this._markSyncedWithParent();
  17682. return this._parentedWorldMatrix;
  17683. }
  17684. return worldMatrix;
  17685. };
  17686. /**
  17687. * Sort function to order lights for rendering.
  17688. * @param a First Light object to compare to second.
  17689. * @param b Second Light object to compare first.
  17690. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  17691. */
  17692. Light.compareLightsPriority = function (a, b) {
  17693. //shadow-casting lights have priority over non-shadow-casting lights
  17694. //the renderPrioirty is a secondary sort criterion
  17695. if (a.shadowEnabled !== b.shadowEnabled) {
  17696. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  17697. }
  17698. return b.renderPriority - a.renderPriority;
  17699. };
  17700. /**
  17701. * Disposes the light.
  17702. */
  17703. Light.prototype.dispose = function () {
  17704. if (this._shadowGenerator) {
  17705. this._shadowGenerator.dispose();
  17706. this._shadowGenerator = null;
  17707. }
  17708. // Animations
  17709. this.getScene().stopAnimation(this);
  17710. this._uniformBuffer.dispose();
  17711. // Remove from scene
  17712. this.getScene().removeLight(this);
  17713. _super.prototype.dispose.call(this);
  17714. };
  17715. /**
  17716. * Returns the light type ID (integer).
  17717. */
  17718. Light.prototype.getTypeID = function () {
  17719. return 0;
  17720. };
  17721. /**
  17722. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  17723. */
  17724. Light.prototype.getScaledIntensity = function () {
  17725. return this._photometricScale * this.intensity;
  17726. };
  17727. /**
  17728. * Returns a new Light object, named "name", from the current one.
  17729. */
  17730. Light.prototype.clone = function (name) {
  17731. var constructor = Light.GetConstructorFromName(this.getTypeID(), name, this.getScene());
  17732. if (!constructor) {
  17733. return null;
  17734. }
  17735. return BABYLON.SerializationHelper.Clone(constructor, this);
  17736. };
  17737. /**
  17738. * Serializes the current light into a Serialization object.
  17739. * Returns the serialized object.
  17740. */
  17741. Light.prototype.serialize = function () {
  17742. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  17743. // Type
  17744. serializationObject.type = this.getTypeID();
  17745. // Parent
  17746. if (this.parent) {
  17747. serializationObject.parentId = this.parent.id;
  17748. }
  17749. // Inclusion / exclusions
  17750. if (this.excludedMeshes.length > 0) {
  17751. serializationObject.excludedMeshesIds = [];
  17752. this.excludedMeshes.forEach(function (mesh) {
  17753. serializationObject.excludedMeshesIds.push(mesh.id);
  17754. });
  17755. }
  17756. if (this.includedOnlyMeshes.length > 0) {
  17757. serializationObject.includedOnlyMeshesIds = [];
  17758. this.includedOnlyMeshes.forEach(function (mesh) {
  17759. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  17760. });
  17761. }
  17762. // Animations
  17763. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  17764. serializationObject.ranges = this.serializeAnimationRanges();
  17765. return serializationObject;
  17766. };
  17767. /**
  17768. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  17769. * This new light is named "name" and added to the passed scene.
  17770. */
  17771. Light.GetConstructorFromName = function (type, name, scene) {
  17772. switch (type) {
  17773. case 0:
  17774. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  17775. case 1:
  17776. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  17777. case 2:
  17778. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  17779. case 3:
  17780. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  17781. }
  17782. return null;
  17783. };
  17784. /**
  17785. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  17786. */
  17787. Light.Parse = function (parsedLight, scene) {
  17788. var constructor = Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene);
  17789. if (!constructor) {
  17790. return null;
  17791. }
  17792. var light = BABYLON.SerializationHelper.Parse(constructor, parsedLight, scene);
  17793. // Inclusion / exclusions
  17794. if (parsedLight.excludedMeshesIds) {
  17795. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  17796. }
  17797. if (parsedLight.includedOnlyMeshesIds) {
  17798. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  17799. }
  17800. // Parent
  17801. if (parsedLight.parentId) {
  17802. light._waitingParentId = parsedLight.parentId;
  17803. }
  17804. // Animations
  17805. if (parsedLight.animations) {
  17806. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  17807. var parsedAnimation = parsedLight.animations[animationIndex];
  17808. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  17809. }
  17810. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  17811. }
  17812. if (parsedLight.autoAnimate) {
  17813. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  17814. }
  17815. return light;
  17816. };
  17817. Light.prototype._hookArrayForExcluded = function (array) {
  17818. var _this = this;
  17819. var oldPush = array.push;
  17820. array.push = function () {
  17821. var items = [];
  17822. for (var _i = 0; _i < arguments.length; _i++) {
  17823. items[_i] = arguments[_i];
  17824. }
  17825. var result = oldPush.apply(array, items);
  17826. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  17827. var item = items_1[_a];
  17828. item._resyncLighSource(_this);
  17829. }
  17830. return result;
  17831. };
  17832. var oldSplice = array.splice;
  17833. array.splice = function (index, deleteCount) {
  17834. var deleted = oldSplice.apply(array, [index, deleteCount]);
  17835. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  17836. var item = deleted_1[_i];
  17837. item._resyncLighSource(_this);
  17838. }
  17839. return deleted;
  17840. };
  17841. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  17842. var item = array_1[_i];
  17843. item._resyncLighSource(this);
  17844. }
  17845. };
  17846. Light.prototype._hookArrayForIncludedOnly = function (array) {
  17847. var _this = this;
  17848. var oldPush = array.push;
  17849. array.push = function () {
  17850. var items = [];
  17851. for (var _i = 0; _i < arguments.length; _i++) {
  17852. items[_i] = arguments[_i];
  17853. }
  17854. var result = oldPush.apply(array, items);
  17855. _this._resyncMeshes();
  17856. return result;
  17857. };
  17858. var oldSplice = array.splice;
  17859. array.splice = function (index, deleteCount) {
  17860. var deleted = oldSplice.apply(array, [index, deleteCount]);
  17861. _this._resyncMeshes();
  17862. return deleted;
  17863. };
  17864. this._resyncMeshes();
  17865. };
  17866. Light.prototype._resyncMeshes = function () {
  17867. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  17868. var mesh = _a[_i];
  17869. mesh._resyncLighSource(this);
  17870. }
  17871. };
  17872. Light.prototype._markMeshesAsLightDirty = function () {
  17873. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  17874. var mesh = _a[_i];
  17875. if (mesh._lightSources.indexOf(this) !== -1) {
  17876. mesh._markSubMeshesAsLightDirty();
  17877. }
  17878. }
  17879. };
  17880. /**
  17881. * Recomputes the cached photometric scale if needed.
  17882. */
  17883. Light.prototype._computePhotometricScale = function () {
  17884. this._photometricScale = this._getPhotometricScale();
  17885. this.getScene().resetCachedMaterial();
  17886. };
  17887. /**
  17888. * Returns the Photometric Scale according to the light type and intensity mode.
  17889. */
  17890. Light.prototype._getPhotometricScale = function () {
  17891. var photometricScale = 0.0;
  17892. var lightTypeID = this.getTypeID();
  17893. //get photometric mode
  17894. var photometricMode = this.intensityMode;
  17895. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  17896. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  17897. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  17898. }
  17899. else {
  17900. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  17901. }
  17902. }
  17903. //compute photometric scale
  17904. switch (lightTypeID) {
  17905. case Light.LIGHTTYPEID_POINTLIGHT:
  17906. case Light.LIGHTTYPEID_SPOTLIGHT:
  17907. switch (photometricMode) {
  17908. case Light.INTENSITYMODE_LUMINOUSPOWER:
  17909. photometricScale = 1.0 / (4.0 * Math.PI);
  17910. break;
  17911. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  17912. photometricScale = 1.0;
  17913. break;
  17914. case Light.INTENSITYMODE_LUMINANCE:
  17915. photometricScale = this.radius * this.radius;
  17916. break;
  17917. }
  17918. break;
  17919. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  17920. switch (photometricMode) {
  17921. case Light.INTENSITYMODE_ILLUMINANCE:
  17922. photometricScale = 1.0;
  17923. break;
  17924. case Light.INTENSITYMODE_LUMINANCE:
  17925. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  17926. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  17927. var apexAngleRadians = this.radius;
  17928. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  17929. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  17930. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  17931. photometricScale = solidAngle;
  17932. break;
  17933. }
  17934. break;
  17935. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  17936. // No fall off in hemisperic light.
  17937. photometricScale = 1.0;
  17938. break;
  17939. }
  17940. return photometricScale;
  17941. };
  17942. Light.prototype._reorderLightsInScene = function () {
  17943. var scene = this.getScene();
  17944. if (this._renderPriority != 0) {
  17945. scene.requireLightSorting = true;
  17946. }
  17947. this.getScene().sortLightsByPriority();
  17948. };
  17949. //lightmapMode Consts
  17950. Light._LIGHTMAP_DEFAULT = 0;
  17951. Light._LIGHTMAP_SPECULAR = 1;
  17952. Light._LIGHTMAP_SHADOWSONLY = 2;
  17953. // Intensity Mode Consts
  17954. Light._INTENSITYMODE_AUTOMATIC = 0;
  17955. Light._INTENSITYMODE_LUMINOUSPOWER = 1;
  17956. Light._INTENSITYMODE_LUMINOUSINTENSITY = 2;
  17957. Light._INTENSITYMODE_ILLUMINANCE = 3;
  17958. Light._INTENSITYMODE_LUMINANCE = 4;
  17959. // Light types ids const.
  17960. Light._LIGHTTYPEID_POINTLIGHT = 0;
  17961. Light._LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  17962. Light._LIGHTTYPEID_SPOTLIGHT = 2;
  17963. Light._LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  17964. __decorate([
  17965. BABYLON.serializeAsColor3()
  17966. ], Light.prototype, "diffuse", void 0);
  17967. __decorate([
  17968. BABYLON.serializeAsColor3()
  17969. ], Light.prototype, "specular", void 0);
  17970. __decorate([
  17971. BABYLON.serialize()
  17972. ], Light.prototype, "intensity", void 0);
  17973. __decorate([
  17974. BABYLON.serialize()
  17975. ], Light.prototype, "range", void 0);
  17976. __decorate([
  17977. BABYLON.serialize()
  17978. ], Light.prototype, "intensityMode", null);
  17979. __decorate([
  17980. BABYLON.serialize()
  17981. ], Light.prototype, "radius", null);
  17982. __decorate([
  17983. BABYLON.serialize()
  17984. ], Light.prototype, "_renderPriority", void 0);
  17985. __decorate([
  17986. BABYLON.expandToProperty("_reorderLightsInScene")
  17987. ], Light.prototype, "renderPriority", void 0);
  17988. __decorate([
  17989. BABYLON.serialize()
  17990. ], Light.prototype, "shadowEnabled", void 0);
  17991. __decorate([
  17992. BABYLON.serialize("excludeWithLayerMask")
  17993. ], Light.prototype, "_excludeWithLayerMask", void 0);
  17994. __decorate([
  17995. BABYLON.serialize("includeOnlyWithLayerMask")
  17996. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  17997. __decorate([
  17998. BABYLON.serialize("lightmapMode")
  17999. ], Light.prototype, "_lightmapMode", void 0);
  18000. return Light;
  18001. }(BABYLON.Node));
  18002. BABYLON.Light = Light;
  18003. })(BABYLON || (BABYLON = {}));
  18004. //# sourceMappingURL=babylon.light.js.map
  18005. var BABYLON;
  18006. (function (BABYLON) {
  18007. var Camera = /** @class */ (function (_super) {
  18008. __extends(Camera, _super);
  18009. function Camera(name, position, scene) {
  18010. var _this = _super.call(this, name, scene) || this;
  18011. /**
  18012. * The vector the camera should consider as up.
  18013. * (default is Vector3(0, 1, 0) aka Vector3.Up())
  18014. */
  18015. _this.upVector = BABYLON.Vector3.Up();
  18016. _this.orthoLeft = null;
  18017. _this.orthoRight = null;
  18018. _this.orthoBottom = null;
  18019. _this.orthoTop = null;
  18020. /**
  18021. * FOV is set in Radians. (default is 0.8)
  18022. */
  18023. _this.fov = 0.8;
  18024. _this.minZ = 1;
  18025. _this.maxZ = 10000.0;
  18026. _this.inertia = 0.9;
  18027. _this.mode = Camera.PERSPECTIVE_CAMERA;
  18028. _this.isIntermediate = false;
  18029. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  18030. /**
  18031. * Restricts the camera to viewing objects with the same layerMask.
  18032. * A camera with a layerMask of 1 will render mesh.layerMask & camera.layerMask!== 0
  18033. */
  18034. _this.layerMask = 0x0FFFFFFF;
  18035. /**
  18036. * fovMode sets the camera frustum bounds to the viewport bounds. (default is FOVMODE_VERTICAL_FIXED)
  18037. */
  18038. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  18039. // Camera rig members
  18040. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  18041. _this._rigCameras = new Array();
  18042. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  18043. _this._skipRendering = false;
  18044. _this.customRenderTargets = new Array();
  18045. // Observables
  18046. _this.onViewMatrixChangedObservable = new BABYLON.Observable();
  18047. _this.onProjectionMatrixChangedObservable = new BABYLON.Observable();
  18048. _this.onAfterCheckInputsObservable = new BABYLON.Observable();
  18049. _this.onRestoreStateObservable = new BABYLON.Observable();
  18050. // Cache
  18051. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  18052. _this._projectionMatrix = new BABYLON.Matrix();
  18053. _this._doNotComputeProjectionMatrix = false;
  18054. _this._postProcesses = new Array();
  18055. _this._transformMatrix = BABYLON.Matrix.Zero();
  18056. _this._activeMeshes = new BABYLON.SmartArray(256);
  18057. _this._globalPosition = BABYLON.Vector3.Zero();
  18058. _this._refreshFrustumPlanes = true;
  18059. _this.getScene().addCamera(_this);
  18060. if (!_this.getScene().activeCamera) {
  18061. _this.getScene().activeCamera = _this;
  18062. }
  18063. _this.position = position;
  18064. return _this;
  18065. }
  18066. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  18067. get: function () {
  18068. return Camera._PERSPECTIVE_CAMERA;
  18069. },
  18070. enumerable: true,
  18071. configurable: true
  18072. });
  18073. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  18074. get: function () {
  18075. return Camera._ORTHOGRAPHIC_CAMERA;
  18076. },
  18077. enumerable: true,
  18078. configurable: true
  18079. });
  18080. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  18081. /**
  18082. * This is the default FOV mode for perspective cameras.
  18083. * This setting aligns the upper and lower bounds of the viewport to the upper and lower bounds of the camera frustum.
  18084. *
  18085. */
  18086. get: function () {
  18087. return Camera._FOVMODE_VERTICAL_FIXED;
  18088. },
  18089. enumerable: true,
  18090. configurable: true
  18091. });
  18092. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  18093. /**
  18094. * This setting aligns the left and right bounds of the viewport to the left and right bounds of the camera frustum.
  18095. *
  18096. */
  18097. get: function () {
  18098. return Camera._FOVMODE_HORIZONTAL_FIXED;
  18099. },
  18100. enumerable: true,
  18101. configurable: true
  18102. });
  18103. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  18104. get: function () {
  18105. return Camera._RIG_MODE_NONE;
  18106. },
  18107. enumerable: true,
  18108. configurable: true
  18109. });
  18110. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  18111. get: function () {
  18112. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  18113. },
  18114. enumerable: true,
  18115. configurable: true
  18116. });
  18117. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  18118. get: function () {
  18119. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  18120. },
  18121. enumerable: true,
  18122. configurable: true
  18123. });
  18124. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  18125. get: function () {
  18126. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  18127. },
  18128. enumerable: true,
  18129. configurable: true
  18130. });
  18131. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  18132. get: function () {
  18133. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  18134. },
  18135. enumerable: true,
  18136. configurable: true
  18137. });
  18138. Object.defineProperty(Camera, "RIG_MODE_VR", {
  18139. get: function () {
  18140. return Camera._RIG_MODE_VR;
  18141. },
  18142. enumerable: true,
  18143. configurable: true
  18144. });
  18145. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  18146. get: function () {
  18147. return Camera._RIG_MODE_WEBVR;
  18148. },
  18149. enumerable: true,
  18150. configurable: true
  18151. });
  18152. /**
  18153. * Store current camera state (fov, position, etc..)
  18154. */
  18155. Camera.prototype.storeState = function () {
  18156. this._stateStored = true;
  18157. this._storedFov = this.fov;
  18158. return this;
  18159. };
  18160. /**
  18161. * Restores the camera state values if it has been stored. You must call storeState() first
  18162. */
  18163. Camera.prototype._restoreStateValues = function () {
  18164. if (!this._stateStored) {
  18165. return false;
  18166. }
  18167. this.fov = this._storedFov;
  18168. return true;
  18169. };
  18170. /**
  18171. * Restored camera state. You must call storeState() first
  18172. */
  18173. Camera.prototype.restoreState = function () {
  18174. if (this._restoreStateValues()) {
  18175. this.onRestoreStateObservable.notifyObservers(this);
  18176. return true;
  18177. }
  18178. return false;
  18179. };
  18180. Camera.prototype.getClassName = function () {
  18181. return "Camera";
  18182. };
  18183. /**
  18184. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  18185. */
  18186. Camera.prototype.toString = function (fullDetails) {
  18187. var ret = "Name: " + this.name;
  18188. ret += ", type: " + this.getClassName();
  18189. if (this.animations) {
  18190. for (var i = 0; i < this.animations.length; i++) {
  18191. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  18192. }
  18193. }
  18194. if (fullDetails) {
  18195. }
  18196. return ret;
  18197. };
  18198. Object.defineProperty(Camera.prototype, "globalPosition", {
  18199. get: function () {
  18200. return this._globalPosition;
  18201. },
  18202. enumerable: true,
  18203. configurable: true
  18204. });
  18205. Camera.prototype.getActiveMeshes = function () {
  18206. return this._activeMeshes;
  18207. };
  18208. Camera.prototype.isActiveMesh = function (mesh) {
  18209. return (this._activeMeshes.indexOf(mesh) !== -1);
  18210. };
  18211. //Cache
  18212. Camera.prototype._initCache = function () {
  18213. _super.prototype._initCache.call(this);
  18214. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  18215. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  18216. this._cache.mode = undefined;
  18217. this._cache.minZ = undefined;
  18218. this._cache.maxZ = undefined;
  18219. this._cache.fov = undefined;
  18220. this._cache.fovMode = undefined;
  18221. this._cache.aspectRatio = undefined;
  18222. this._cache.orthoLeft = undefined;
  18223. this._cache.orthoRight = undefined;
  18224. this._cache.orthoBottom = undefined;
  18225. this._cache.orthoTop = undefined;
  18226. this._cache.renderWidth = undefined;
  18227. this._cache.renderHeight = undefined;
  18228. };
  18229. Camera.prototype._updateCache = function (ignoreParentClass) {
  18230. if (!ignoreParentClass) {
  18231. _super.prototype._updateCache.call(this);
  18232. }
  18233. this._cache.position.copyFrom(this.position);
  18234. this._cache.upVector.copyFrom(this.upVector);
  18235. };
  18236. // Synchronized
  18237. Camera.prototype._isSynchronized = function () {
  18238. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  18239. };
  18240. Camera.prototype._isSynchronizedViewMatrix = function () {
  18241. if (!_super.prototype._isSynchronized.call(this))
  18242. return false;
  18243. return this._cache.position.equals(this.position)
  18244. && this._cache.upVector.equals(this.upVector)
  18245. && this.isSynchronizedWithParent();
  18246. };
  18247. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  18248. var check = this._cache.mode === this.mode
  18249. && this._cache.minZ === this.minZ
  18250. && this._cache.maxZ === this.maxZ;
  18251. if (!check) {
  18252. return false;
  18253. }
  18254. var engine = this.getEngine();
  18255. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  18256. check = this._cache.fov === this.fov
  18257. && this._cache.fovMode === this.fovMode
  18258. && this._cache.aspectRatio === engine.getAspectRatio(this);
  18259. }
  18260. else {
  18261. check = this._cache.orthoLeft === this.orthoLeft
  18262. && this._cache.orthoRight === this.orthoRight
  18263. && this._cache.orthoBottom === this.orthoBottom
  18264. && this._cache.orthoTop === this.orthoTop
  18265. && this._cache.renderWidth === engine.getRenderWidth()
  18266. && this._cache.renderHeight === engine.getRenderHeight();
  18267. }
  18268. return check;
  18269. };
  18270. // Controls
  18271. Camera.prototype.attachControl = function (element, noPreventDefault) {
  18272. };
  18273. Camera.prototype.detachControl = function (element) {
  18274. };
  18275. Camera.prototype.update = function () {
  18276. this._checkInputs();
  18277. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  18278. this._updateRigCameras();
  18279. }
  18280. };
  18281. Camera.prototype._checkInputs = function () {
  18282. this.onAfterCheckInputsObservable.notifyObservers(this);
  18283. };
  18284. Object.defineProperty(Camera.prototype, "rigCameras", {
  18285. get: function () {
  18286. return this._rigCameras;
  18287. },
  18288. enumerable: true,
  18289. configurable: true
  18290. });
  18291. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  18292. get: function () {
  18293. return this._rigPostProcess;
  18294. },
  18295. enumerable: true,
  18296. configurable: true
  18297. });
  18298. Camera.prototype._cascadePostProcessesToRigCams = function () {
  18299. // invalidate framebuffer
  18300. if (this._postProcesses.length > 0) {
  18301. this._postProcesses[0].markTextureDirty();
  18302. }
  18303. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  18304. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  18305. var cam = this._rigCameras[i];
  18306. var rigPostProcess = cam._rigPostProcess;
  18307. // for VR rig, there does not have to be a post process
  18308. if (rigPostProcess) {
  18309. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  18310. if (isPass) {
  18311. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  18312. cam.isIntermediate = this._postProcesses.length === 0;
  18313. }
  18314. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  18315. rigPostProcess.markTextureDirty();
  18316. }
  18317. else {
  18318. cam._postProcesses = this._postProcesses.slice(0);
  18319. }
  18320. }
  18321. };
  18322. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  18323. if (insertAt === void 0) { insertAt = null; }
  18324. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  18325. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  18326. return 0;
  18327. }
  18328. if (insertAt == null || insertAt < 0) {
  18329. this._postProcesses.push(postProcess);
  18330. }
  18331. else {
  18332. this._postProcesses.splice(insertAt, 0, postProcess);
  18333. }
  18334. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  18335. return this._postProcesses.indexOf(postProcess);
  18336. };
  18337. Camera.prototype.detachPostProcess = function (postProcess) {
  18338. var idx = this._postProcesses.indexOf(postProcess);
  18339. if (idx !== -1) {
  18340. this._postProcesses.splice(idx, 1);
  18341. }
  18342. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  18343. };
  18344. Camera.prototype.getWorldMatrix = function () {
  18345. if (!this._worldMatrix) {
  18346. this._worldMatrix = BABYLON.Matrix.Identity();
  18347. }
  18348. var viewMatrix = this.getViewMatrix();
  18349. viewMatrix.invertToRef(this._worldMatrix);
  18350. return this._worldMatrix;
  18351. };
  18352. Camera.prototype._getViewMatrix = function () {
  18353. return BABYLON.Matrix.Identity();
  18354. };
  18355. Camera.prototype.getViewMatrix = function (force) {
  18356. if (!force && this._isSynchronizedViewMatrix()) {
  18357. return this._computedViewMatrix;
  18358. }
  18359. this.updateCache();
  18360. this._computedViewMatrix = this._getViewMatrix();
  18361. this._currentRenderId = this.getScene().getRenderId();
  18362. this._refreshFrustumPlanes = true;
  18363. if (!this.parent || !this.parent.getWorldMatrix) {
  18364. this._globalPosition.copyFrom(this.position);
  18365. }
  18366. else {
  18367. if (!this._worldMatrix) {
  18368. this._worldMatrix = BABYLON.Matrix.Identity();
  18369. }
  18370. this._computedViewMatrix.invertToRef(this._worldMatrix);
  18371. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  18372. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  18373. this._computedViewMatrix.invert();
  18374. this._markSyncedWithParent();
  18375. }
  18376. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  18377. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  18378. }
  18379. this.onViewMatrixChangedObservable.notifyObservers(this);
  18380. return this._computedViewMatrix;
  18381. };
  18382. Camera.prototype.freezeProjectionMatrix = function (projection) {
  18383. this._doNotComputeProjectionMatrix = true;
  18384. if (projection !== undefined) {
  18385. this._projectionMatrix = projection;
  18386. }
  18387. };
  18388. ;
  18389. Camera.prototype.unfreezeProjectionMatrix = function () {
  18390. this._doNotComputeProjectionMatrix = false;
  18391. };
  18392. ;
  18393. Camera.prototype.getProjectionMatrix = function (force) {
  18394. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  18395. return this._projectionMatrix;
  18396. }
  18397. // Cache
  18398. this._cache.mode = this.mode;
  18399. this._cache.minZ = this.minZ;
  18400. this._cache.maxZ = this.maxZ;
  18401. // Matrix
  18402. this._refreshFrustumPlanes = true;
  18403. var engine = this.getEngine();
  18404. var scene = this.getScene();
  18405. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  18406. this._cache.fov = this.fov;
  18407. this._cache.fovMode = this.fovMode;
  18408. this._cache.aspectRatio = engine.getAspectRatio(this);
  18409. if (this.minZ <= 0) {
  18410. this.minZ = 0.1;
  18411. }
  18412. if (scene.useRightHandedSystem) {
  18413. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  18414. }
  18415. else {
  18416. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  18417. }
  18418. }
  18419. else {
  18420. var halfWidth = engine.getRenderWidth() / 2.0;
  18421. var halfHeight = engine.getRenderHeight() / 2.0;
  18422. if (scene.useRightHandedSystem) {
  18423. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  18424. }
  18425. else {
  18426. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  18427. }
  18428. this._cache.orthoLeft = this.orthoLeft;
  18429. this._cache.orthoRight = this.orthoRight;
  18430. this._cache.orthoBottom = this.orthoBottom;
  18431. this._cache.orthoTop = this.orthoTop;
  18432. this._cache.renderWidth = engine.getRenderWidth();
  18433. this._cache.renderHeight = engine.getRenderHeight();
  18434. }
  18435. this.onProjectionMatrixChangedObservable.notifyObservers(this);
  18436. return this._projectionMatrix;
  18437. };
  18438. Camera.prototype.getTranformationMatrix = function () {
  18439. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  18440. return this._transformMatrix;
  18441. };
  18442. Camera.prototype.updateFrustumPlanes = function () {
  18443. if (!this._refreshFrustumPlanes) {
  18444. return;
  18445. }
  18446. this.getTranformationMatrix();
  18447. if (!this._frustumPlanes) {
  18448. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  18449. }
  18450. else {
  18451. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  18452. }
  18453. this._refreshFrustumPlanes = false;
  18454. };
  18455. Camera.prototype.isInFrustum = function (target) {
  18456. this.updateFrustumPlanes();
  18457. return target.isInFrustum(this._frustumPlanes);
  18458. };
  18459. Camera.prototype.isCompletelyInFrustum = function (target) {
  18460. this.updateFrustumPlanes();
  18461. return target.isCompletelyInFrustum(this._frustumPlanes);
  18462. };
  18463. Camera.prototype.getForwardRay = function (length, transform, origin) {
  18464. if (length === void 0) { length = 100; }
  18465. if (!transform) {
  18466. transform = this.getWorldMatrix();
  18467. }
  18468. if (!origin) {
  18469. origin = this.position;
  18470. }
  18471. var forward = new BABYLON.Vector3(0, 0, 1);
  18472. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  18473. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  18474. return new BABYLON.Ray(origin, direction, length);
  18475. };
  18476. Camera.prototype.dispose = function () {
  18477. // Observables
  18478. this.onViewMatrixChangedObservable.clear();
  18479. this.onProjectionMatrixChangedObservable.clear();
  18480. this.onAfterCheckInputsObservable.clear();
  18481. this.onRestoreStateObservable.clear();
  18482. // Inputs
  18483. if (this.inputs) {
  18484. this.inputs.clear();
  18485. }
  18486. // Animations
  18487. this.getScene().stopAnimation(this);
  18488. // Remove from scene
  18489. this.getScene().removeCamera(this);
  18490. while (this._rigCameras.length > 0) {
  18491. var camera = this._rigCameras.pop();
  18492. if (camera) {
  18493. camera.dispose();
  18494. }
  18495. }
  18496. // Postprocesses
  18497. if (this._rigPostProcess) {
  18498. this._rigPostProcess.dispose(this);
  18499. this._rigPostProcess = null;
  18500. this._postProcesses = [];
  18501. }
  18502. else if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  18503. this._rigPostProcess = null;
  18504. this._postProcesses = [];
  18505. }
  18506. else {
  18507. var i = this._postProcesses.length;
  18508. while (--i >= 0) {
  18509. this._postProcesses[i].dispose(this);
  18510. }
  18511. }
  18512. // Render targets
  18513. var i = this.customRenderTargets.length;
  18514. while (--i >= 0) {
  18515. this.customRenderTargets[i].dispose();
  18516. }
  18517. this.customRenderTargets = [];
  18518. // Active Meshes
  18519. this._activeMeshes.dispose();
  18520. _super.prototype.dispose.call(this);
  18521. };
  18522. Object.defineProperty(Camera.prototype, "leftCamera", {
  18523. // ---- Camera rigs section ----
  18524. get: function () {
  18525. if (this._rigCameras.length < 1) {
  18526. return null;
  18527. }
  18528. return this._rigCameras[0];
  18529. },
  18530. enumerable: true,
  18531. configurable: true
  18532. });
  18533. Object.defineProperty(Camera.prototype, "rightCamera", {
  18534. get: function () {
  18535. if (this._rigCameras.length < 2) {
  18536. return null;
  18537. }
  18538. return this._rigCameras[1];
  18539. },
  18540. enumerable: true,
  18541. configurable: true
  18542. });
  18543. Camera.prototype.getLeftTarget = function () {
  18544. if (this._rigCameras.length < 1) {
  18545. return null;
  18546. }
  18547. return this._rigCameras[0].getTarget();
  18548. };
  18549. Camera.prototype.getRightTarget = function () {
  18550. if (this._rigCameras.length < 2) {
  18551. return null;
  18552. }
  18553. return this._rigCameras[1].getTarget();
  18554. };
  18555. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  18556. if (this.cameraRigMode === mode) {
  18557. return;
  18558. }
  18559. while (this._rigCameras.length > 0) {
  18560. var camera = this._rigCameras.pop();
  18561. if (camera) {
  18562. camera.dispose();
  18563. }
  18564. }
  18565. this.cameraRigMode = mode;
  18566. this._cameraRigParams = {};
  18567. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  18568. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  18569. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  18570. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  18571. // create the rig cameras, unless none
  18572. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  18573. var leftCamera = this.createRigCamera(this.name + "_L", 0);
  18574. var rightCamera = this.createRigCamera(this.name + "_R", 1);
  18575. if (leftCamera && rightCamera) {
  18576. this._rigCameras.push(leftCamera);
  18577. this._rigCameras.push(rightCamera);
  18578. }
  18579. }
  18580. switch (this.cameraRigMode) {
  18581. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  18582. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  18583. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  18584. break;
  18585. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  18586. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  18587. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  18588. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  18589. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  18590. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  18591. break;
  18592. case Camera.RIG_MODE_VR:
  18593. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  18594. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  18595. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  18596. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  18597. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  18598. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  18599. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  18600. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  18601. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  18602. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  18603. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  18604. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  18605. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  18606. if (metrics.compensateDistortion) {
  18607. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  18608. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  18609. }
  18610. break;
  18611. case Camera.RIG_MODE_WEBVR:
  18612. if (rigParams.vrDisplay) {
  18613. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  18614. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  18615. //Left eye
  18616. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  18617. this._rigCameras[0].setCameraRigParameter("left", true);
  18618. //leaving this for future reference
  18619. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  18620. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  18621. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  18622. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  18623. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  18624. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  18625. this._rigCameras[0].parent = this;
  18626. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  18627. //Right eye
  18628. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  18629. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  18630. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  18631. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  18632. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  18633. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  18634. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  18635. this._rigCameras[1].parent = this;
  18636. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  18637. if (Camera.UseAlternateWebVRRendering) {
  18638. this._rigCameras[1]._skipRendering = true;
  18639. this._rigCameras[0]._alternateCamera = this._rigCameras[1];
  18640. }
  18641. }
  18642. break;
  18643. }
  18644. this._cascadePostProcessesToRigCams();
  18645. this.update();
  18646. };
  18647. Camera.prototype._getVRProjectionMatrix = function () {
  18648. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  18649. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  18650. return this._projectionMatrix;
  18651. };
  18652. Camera.prototype._updateCameraRotationMatrix = function () {
  18653. //Here for WebVR
  18654. };
  18655. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  18656. //Here for WebVR
  18657. };
  18658. /**
  18659. * This function MUST be overwritten by the different WebVR cameras available.
  18660. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  18661. */
  18662. Camera.prototype._getWebVRProjectionMatrix = function () {
  18663. return BABYLON.Matrix.Identity();
  18664. };
  18665. /**
  18666. * This function MUST be overwritten by the different WebVR cameras available.
  18667. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  18668. */
  18669. Camera.prototype._getWebVRViewMatrix = function () {
  18670. return BABYLON.Matrix.Identity();
  18671. };
  18672. Camera.prototype.setCameraRigParameter = function (name, value) {
  18673. if (!this._cameraRigParams) {
  18674. this._cameraRigParams = {};
  18675. }
  18676. this._cameraRigParams[name] = value;
  18677. //provisionnally:
  18678. if (name === "interaxialDistance") {
  18679. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  18680. }
  18681. };
  18682. /**
  18683. * needs to be overridden by children so sub has required properties to be copied
  18684. */
  18685. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  18686. return null;
  18687. };
  18688. /**
  18689. * May need to be overridden by children
  18690. */
  18691. Camera.prototype._updateRigCameras = function () {
  18692. for (var i = 0; i < this._rigCameras.length; i++) {
  18693. this._rigCameras[i].minZ = this.minZ;
  18694. this._rigCameras[i].maxZ = this.maxZ;
  18695. this._rigCameras[i].fov = this.fov;
  18696. }
  18697. // only update viewport when ANAGLYPH
  18698. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  18699. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  18700. }
  18701. };
  18702. Camera.prototype._setupInputs = function () {
  18703. };
  18704. Camera.prototype.serialize = function () {
  18705. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  18706. // Type
  18707. serializationObject.type = this.getClassName();
  18708. // Parent
  18709. if (this.parent) {
  18710. serializationObject.parentId = this.parent.id;
  18711. }
  18712. if (this.inputs) {
  18713. this.inputs.serialize(serializationObject);
  18714. }
  18715. // Animations
  18716. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  18717. serializationObject.ranges = this.serializeAnimationRanges();
  18718. return serializationObject;
  18719. };
  18720. Camera.prototype.clone = function (name) {
  18721. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  18722. };
  18723. Camera.prototype.getDirection = function (localAxis) {
  18724. var result = BABYLON.Vector3.Zero();
  18725. this.getDirectionToRef(localAxis, result);
  18726. return result;
  18727. };
  18728. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  18729. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  18730. };
  18731. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  18732. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  18733. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  18734. switch (type) {
  18735. case "ArcRotateCamera":
  18736. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  18737. case "DeviceOrientationCamera":
  18738. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  18739. case "FollowCamera":
  18740. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  18741. case "ArcFollowCamera":
  18742. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  18743. case "GamepadCamera":
  18744. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  18745. case "TouchCamera":
  18746. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  18747. case "VirtualJoysticksCamera":
  18748. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  18749. case "WebVRFreeCamera":
  18750. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  18751. case "WebVRGamepadCamera":
  18752. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  18753. case "VRDeviceOrientationFreeCamera":
  18754. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  18755. case "VRDeviceOrientationGamepadCamera":
  18756. return function () { return new BABYLON.VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  18757. case "AnaglyphArcRotateCamera":
  18758. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  18759. case "AnaglyphFreeCamera":
  18760. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  18761. case "AnaglyphGamepadCamera":
  18762. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  18763. case "AnaglyphUniversalCamera":
  18764. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  18765. case "StereoscopicArcRotateCamera":
  18766. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  18767. case "StereoscopicFreeCamera":
  18768. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  18769. case "StereoscopicGamepadCamera":
  18770. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  18771. case "StereoscopicUniversalCamera":
  18772. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  18773. case "FreeCamera":// Forcing Universal here
  18774. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  18775. default:// Universal Camera is the default value
  18776. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  18777. }
  18778. };
  18779. Camera.prototype.computeWorldMatrix = function () {
  18780. return this.getWorldMatrix();
  18781. };
  18782. Camera.Parse = function (parsedCamera, scene) {
  18783. var type = parsedCamera.type;
  18784. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  18785. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  18786. // Parent
  18787. if (parsedCamera.parentId) {
  18788. camera._waitingParentId = parsedCamera.parentId;
  18789. }
  18790. //If camera has an input manager, let it parse inputs settings
  18791. if (camera.inputs) {
  18792. camera.inputs.parse(parsedCamera);
  18793. camera._setupInputs();
  18794. }
  18795. if (camera.setPosition) {
  18796. camera.position.copyFromFloats(0, 0, 0);
  18797. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  18798. }
  18799. // Target
  18800. if (parsedCamera.target) {
  18801. if (camera.setTarget) {
  18802. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  18803. }
  18804. }
  18805. // Apply 3d rig, when found
  18806. if (parsedCamera.cameraRigMode) {
  18807. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  18808. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  18809. }
  18810. // Animations
  18811. if (parsedCamera.animations) {
  18812. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  18813. var parsedAnimation = parsedCamera.animations[animationIndex];
  18814. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  18815. }
  18816. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  18817. }
  18818. if (parsedCamera.autoAnimate) {
  18819. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  18820. }
  18821. return camera;
  18822. };
  18823. // Statics
  18824. Camera._PERSPECTIVE_CAMERA = 0;
  18825. Camera._ORTHOGRAPHIC_CAMERA = 1;
  18826. Camera._FOVMODE_VERTICAL_FIXED = 0;
  18827. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  18828. Camera._RIG_MODE_NONE = 0;
  18829. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  18830. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  18831. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  18832. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  18833. Camera._RIG_MODE_VR = 20;
  18834. Camera._RIG_MODE_WEBVR = 21;
  18835. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  18836. Camera.UseAlternateWebVRRendering = false;
  18837. __decorate([
  18838. BABYLON.serializeAsVector3()
  18839. ], Camera.prototype, "position", void 0);
  18840. __decorate([
  18841. BABYLON.serializeAsVector3()
  18842. ], Camera.prototype, "upVector", void 0);
  18843. __decorate([
  18844. BABYLON.serialize()
  18845. ], Camera.prototype, "orthoLeft", void 0);
  18846. __decorate([
  18847. BABYLON.serialize()
  18848. ], Camera.prototype, "orthoRight", void 0);
  18849. __decorate([
  18850. BABYLON.serialize()
  18851. ], Camera.prototype, "orthoBottom", void 0);
  18852. __decorate([
  18853. BABYLON.serialize()
  18854. ], Camera.prototype, "orthoTop", void 0);
  18855. __decorate([
  18856. BABYLON.serialize()
  18857. ], Camera.prototype, "fov", void 0);
  18858. __decorate([
  18859. BABYLON.serialize()
  18860. ], Camera.prototype, "minZ", void 0);
  18861. __decorate([
  18862. BABYLON.serialize()
  18863. ], Camera.prototype, "maxZ", void 0);
  18864. __decorate([
  18865. BABYLON.serialize()
  18866. ], Camera.prototype, "inertia", void 0);
  18867. __decorate([
  18868. BABYLON.serialize()
  18869. ], Camera.prototype, "mode", void 0);
  18870. __decorate([
  18871. BABYLON.serialize()
  18872. ], Camera.prototype, "layerMask", void 0);
  18873. __decorate([
  18874. BABYLON.serialize()
  18875. ], Camera.prototype, "fovMode", void 0);
  18876. __decorate([
  18877. BABYLON.serialize()
  18878. ], Camera.prototype, "cameraRigMode", void 0);
  18879. __decorate([
  18880. BABYLON.serialize()
  18881. ], Camera.prototype, "interaxialDistance", void 0);
  18882. __decorate([
  18883. BABYLON.serialize()
  18884. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  18885. return Camera;
  18886. }(BABYLON.Node));
  18887. BABYLON.Camera = Camera;
  18888. })(BABYLON || (BABYLON = {}));
  18889. //# sourceMappingURL=babylon.camera.js.map
  18890. var BABYLON;
  18891. (function (BABYLON) {
  18892. var RenderingManager = /** @class */ (function () {
  18893. function RenderingManager(scene) {
  18894. this._renderingGroups = new Array();
  18895. this._autoClearDepthStencil = {};
  18896. this._customOpaqueSortCompareFn = {};
  18897. this._customAlphaTestSortCompareFn = {};
  18898. this._customTransparentSortCompareFn = {};
  18899. this._renderinGroupInfo = null;
  18900. this._scene = scene;
  18901. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  18902. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  18903. }
  18904. }
  18905. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  18906. if (depth === void 0) { depth = true; }
  18907. if (stencil === void 0) { stencil = true; }
  18908. if (this._depthStencilBufferAlreadyCleaned) {
  18909. return;
  18910. }
  18911. this._scene.getEngine().clear(null, false, depth, stencil);
  18912. this._depthStencilBufferAlreadyCleaned = true;
  18913. };
  18914. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  18915. // Check if there's at least on observer on the onRenderingGroupObservable and initialize things to fire it
  18916. var observable = this._scene.onRenderingGroupObservable.hasObservers() ? this._scene.onRenderingGroupObservable : null;
  18917. var info = null;
  18918. if (observable) {
  18919. if (!this._renderinGroupInfo) {
  18920. this._renderinGroupInfo = new BABYLON.RenderingGroupInfo();
  18921. }
  18922. info = this._renderinGroupInfo;
  18923. info.scene = this._scene;
  18924. info.camera = this._scene.activeCamera;
  18925. }
  18926. // Dispatch sprites
  18927. if (renderSprites) {
  18928. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  18929. var manager = this._scene.spriteManagers[index];
  18930. this.dispatchSprites(manager);
  18931. }
  18932. }
  18933. // Render
  18934. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  18935. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  18936. var renderingGroup = this._renderingGroups[index];
  18937. if (!renderingGroup && !observable)
  18938. continue;
  18939. var renderingGroupMask = 0;
  18940. // Fire PRECLEAR stage
  18941. if (observable && info) {
  18942. renderingGroupMask = Math.pow(2, index);
  18943. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
  18944. info.renderingGroupId = index;
  18945. observable.notifyObservers(info, renderingGroupMask);
  18946. }
  18947. // Clear depth/stencil if needed
  18948. if (RenderingManager.AUTOCLEAR) {
  18949. var autoClear = this._autoClearDepthStencil[index];
  18950. if (autoClear && autoClear.autoClear) {
  18951. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  18952. }
  18953. }
  18954. if (observable && info) {
  18955. // Fire PREOPAQUE stage
  18956. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PREOPAQUE;
  18957. observable.notifyObservers(info, renderingGroupMask);
  18958. // Fire PRETRANSPARENT stage
  18959. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRETRANSPARENT;
  18960. observable.notifyObservers(info, renderingGroupMask);
  18961. }
  18962. if (renderingGroup)
  18963. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  18964. // Fire POSTTRANSPARENT stage
  18965. if (observable && info) {
  18966. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
  18967. observable.notifyObservers(info, renderingGroupMask);
  18968. }
  18969. }
  18970. };
  18971. RenderingManager.prototype.reset = function () {
  18972. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  18973. var renderingGroup = this._renderingGroups[index];
  18974. if (renderingGroup) {
  18975. renderingGroup.prepare();
  18976. }
  18977. }
  18978. };
  18979. RenderingManager.prototype.dispose = function () {
  18980. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  18981. var renderingGroup = this._renderingGroups[index];
  18982. if (renderingGroup) {
  18983. renderingGroup.dispose();
  18984. }
  18985. }
  18986. this._renderingGroups.length = 0;
  18987. };
  18988. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  18989. if (this._renderingGroups[renderingGroupId] === undefined) {
  18990. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  18991. }
  18992. };
  18993. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  18994. var renderingGroupId = spriteManager.renderingGroupId || 0;
  18995. this._prepareRenderingGroup(renderingGroupId);
  18996. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  18997. };
  18998. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  18999. var renderingGroupId = particleSystem.renderingGroupId || 0;
  19000. this._prepareRenderingGroup(renderingGroupId);
  19001. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  19002. };
  19003. /**
  19004. * @param subMesh The submesh to dispatch
  19005. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  19006. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  19007. */
  19008. RenderingManager.prototype.dispatch = function (subMesh, mesh, material) {
  19009. if (mesh === undefined) {
  19010. mesh = subMesh.getMesh();
  19011. }
  19012. var renderingGroupId = mesh.renderingGroupId || 0;
  19013. this._prepareRenderingGroup(renderingGroupId);
  19014. this._renderingGroups[renderingGroupId].dispatch(subMesh, mesh, material);
  19015. };
  19016. /**
  19017. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  19018. * This allowed control for front to back rendering or reversly depending of the special needs.
  19019. *
  19020. * @param renderingGroupId The rendering group id corresponding to its index
  19021. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  19022. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  19023. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  19024. */
  19025. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  19026. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  19027. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  19028. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  19029. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  19030. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  19031. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  19032. if (this._renderingGroups[renderingGroupId]) {
  19033. var group = this._renderingGroups[renderingGroupId];
  19034. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  19035. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  19036. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  19037. }
  19038. };
  19039. /**
  19040. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  19041. *
  19042. * @param renderingGroupId The rendering group id corresponding to its index
  19043. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  19044. * @param depth Automatically clears depth between groups if true and autoClear is true.
  19045. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  19046. */
  19047. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  19048. if (depth === void 0) { depth = true; }
  19049. if (stencil === void 0) { stencil = true; }
  19050. this._autoClearDepthStencil[renderingGroupId] = {
  19051. autoClear: autoClearDepthStencil,
  19052. depth: depth,
  19053. stencil: stencil
  19054. };
  19055. };
  19056. /**
  19057. * The max id used for rendering groups (not included)
  19058. */
  19059. RenderingManager.MAX_RENDERINGGROUPS = 4;
  19060. /**
  19061. * The min id used for rendering groups (included)
  19062. */
  19063. RenderingManager.MIN_RENDERINGGROUPS = 0;
  19064. /**
  19065. * Used to globally prevent autoclearing scenes.
  19066. */
  19067. RenderingManager.AUTOCLEAR = true;
  19068. return RenderingManager;
  19069. }());
  19070. BABYLON.RenderingManager = RenderingManager;
  19071. })(BABYLON || (BABYLON = {}));
  19072. //# sourceMappingURL=babylon.renderingManager.js.map
  19073. var BABYLON;
  19074. (function (BABYLON) {
  19075. var RenderingGroup = /** @class */ (function () {
  19076. /**
  19077. * Creates a new rendering group.
  19078. * @param index The rendering group index
  19079. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  19080. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  19081. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  19082. */
  19083. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  19084. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  19085. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  19086. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  19087. this.index = index;
  19088. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  19089. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  19090. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  19091. this._depthOnlySubMeshes = new BABYLON.SmartArray(256);
  19092. this._particleSystems = new BABYLON.SmartArray(256);
  19093. this._spriteManagers = new BABYLON.SmartArray(256);
  19094. this._edgesRenderers = new BABYLON.SmartArray(16);
  19095. this._scene = scene;
  19096. this.opaqueSortCompareFn = opaqueSortCompareFn;
  19097. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  19098. this.transparentSortCompareFn = transparentSortCompareFn;
  19099. }
  19100. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  19101. /**
  19102. * Set the opaque sort comparison function.
  19103. * If null the sub meshes will be render in the order they were created
  19104. */
  19105. set: function (value) {
  19106. this._opaqueSortCompareFn = value;
  19107. if (value) {
  19108. this._renderOpaque = this.renderOpaqueSorted;
  19109. }
  19110. else {
  19111. this._renderOpaque = RenderingGroup.renderUnsorted;
  19112. }
  19113. },
  19114. enumerable: true,
  19115. configurable: true
  19116. });
  19117. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  19118. /**
  19119. * Set the alpha test sort comparison function.
  19120. * If null the sub meshes will be render in the order they were created
  19121. */
  19122. set: function (value) {
  19123. this._alphaTestSortCompareFn = value;
  19124. if (value) {
  19125. this._renderAlphaTest = this.renderAlphaTestSorted;
  19126. }
  19127. else {
  19128. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  19129. }
  19130. },
  19131. enumerable: true,
  19132. configurable: true
  19133. });
  19134. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  19135. /**
  19136. * Set the transparent sort comparison function.
  19137. * If null the sub meshes will be render in the order they were created
  19138. */
  19139. set: function (value) {
  19140. if (value) {
  19141. this._transparentSortCompareFn = value;
  19142. }
  19143. else {
  19144. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  19145. }
  19146. this._renderTransparent = this.renderTransparentSorted;
  19147. },
  19148. enumerable: true,
  19149. configurable: true
  19150. });
  19151. /**
  19152. * Render all the sub meshes contained in the group.
  19153. * @param customRenderFunction Used to override the default render behaviour of the group.
  19154. * @returns true if rendered some submeshes.
  19155. */
  19156. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  19157. if (customRenderFunction) {
  19158. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, this._depthOnlySubMeshes);
  19159. return;
  19160. }
  19161. var engine = this._scene.getEngine();
  19162. // Depth only
  19163. if (this._depthOnlySubMeshes.length !== 0) {
  19164. engine.setColorWrite(false);
  19165. this._renderAlphaTest(this._depthOnlySubMeshes);
  19166. engine.setColorWrite(true);
  19167. }
  19168. // Opaque
  19169. if (this._opaqueSubMeshes.length !== 0) {
  19170. this._renderOpaque(this._opaqueSubMeshes);
  19171. }
  19172. // Alpha test
  19173. if (this._alphaTestSubMeshes.length !== 0) {
  19174. this._renderAlphaTest(this._alphaTestSubMeshes);
  19175. }
  19176. var stencilState = engine.getStencilBuffer();
  19177. engine.setStencilBuffer(false);
  19178. // Sprites
  19179. if (renderSprites) {
  19180. this._renderSprites();
  19181. }
  19182. // Particles
  19183. if (renderParticles) {
  19184. this._renderParticles(activeMeshes);
  19185. }
  19186. if (this.onBeforeTransparentRendering) {
  19187. this.onBeforeTransparentRendering();
  19188. }
  19189. // Transparent
  19190. if (this._transparentSubMeshes.length !== 0) {
  19191. this._renderTransparent(this._transparentSubMeshes);
  19192. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  19193. }
  19194. // Set back stencil to false in case it changes before the edge renderer.
  19195. engine.setStencilBuffer(false);
  19196. // Edges
  19197. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  19198. this._edgesRenderers.data[edgesRendererIndex].render();
  19199. }
  19200. // Restore Stencil state.
  19201. engine.setStencilBuffer(stencilState);
  19202. };
  19203. /**
  19204. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  19205. * @param subMeshes The submeshes to render
  19206. */
  19207. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  19208. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera, false);
  19209. };
  19210. /**
  19211. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  19212. * @param subMeshes The submeshes to render
  19213. */
  19214. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  19215. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera, false);
  19216. };
  19217. /**
  19218. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  19219. * @param subMeshes The submeshes to render
  19220. */
  19221. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  19222. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera, true);
  19223. };
  19224. /**
  19225. * Renders the submeshes in a specified order.
  19226. * @param subMeshes The submeshes to sort before render
  19227. * @param sortCompareFn The comparison function use to sort
  19228. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  19229. * @param transparent Specifies to activate blending if true
  19230. */
  19231. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, camera, transparent) {
  19232. var subIndex = 0;
  19233. var subMesh;
  19234. var cameraPosition = camera ? camera.globalPosition : BABYLON.Vector3.Zero();
  19235. for (; subIndex < subMeshes.length; subIndex++) {
  19236. subMesh = subMeshes.data[subIndex];
  19237. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  19238. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  19239. }
  19240. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  19241. if (sortCompareFn) {
  19242. sortedArray.sort(sortCompareFn);
  19243. }
  19244. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  19245. subMesh = sortedArray[subIndex];
  19246. if (transparent) {
  19247. var material = subMesh.getMaterial();
  19248. if (material && material.needDepthPrePass) {
  19249. var engine = material.getScene().getEngine();
  19250. engine.setColorWrite(false);
  19251. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  19252. subMesh.render(false);
  19253. engine.setColorWrite(true);
  19254. }
  19255. }
  19256. subMesh.render(transparent);
  19257. }
  19258. };
  19259. /**
  19260. * Renders the submeshes in the order they were dispatched (no sort applied).
  19261. * @param subMeshes The submeshes to render
  19262. */
  19263. RenderingGroup.renderUnsorted = function (subMeshes) {
  19264. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  19265. var submesh = subMeshes.data[subIndex];
  19266. submesh.render(false);
  19267. }
  19268. };
  19269. /**
  19270. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  19271. * are rendered back to front if in the same alpha index.
  19272. *
  19273. * @param a The first submesh
  19274. * @param b The second submesh
  19275. * @returns The result of the comparison
  19276. */
  19277. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  19278. // Alpha index first
  19279. if (a._alphaIndex > b._alphaIndex) {
  19280. return 1;
  19281. }
  19282. if (a._alphaIndex < b._alphaIndex) {
  19283. return -1;
  19284. }
  19285. // Then distance to camera
  19286. return RenderingGroup.backToFrontSortCompare(a, b);
  19287. };
  19288. /**
  19289. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  19290. * are rendered back to front.
  19291. *
  19292. * @param a The first submesh
  19293. * @param b The second submesh
  19294. * @returns The result of the comparison
  19295. */
  19296. RenderingGroup.backToFrontSortCompare = function (a, b) {
  19297. // Then distance to camera
  19298. if (a._distanceToCamera < b._distanceToCamera) {
  19299. return 1;
  19300. }
  19301. if (a._distanceToCamera > b._distanceToCamera) {
  19302. return -1;
  19303. }
  19304. return 0;
  19305. };
  19306. /**
  19307. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  19308. * are rendered front to back (prevent overdraw).
  19309. *
  19310. * @param a The first submesh
  19311. * @param b The second submesh
  19312. * @returns The result of the comparison
  19313. */
  19314. RenderingGroup.frontToBackSortCompare = function (a, b) {
  19315. // Then distance to camera
  19316. if (a._distanceToCamera < b._distanceToCamera) {
  19317. return -1;
  19318. }
  19319. if (a._distanceToCamera > b._distanceToCamera) {
  19320. return 1;
  19321. }
  19322. return 0;
  19323. };
  19324. /**
  19325. * Resets the different lists of submeshes to prepare a new frame.
  19326. */
  19327. RenderingGroup.prototype.prepare = function () {
  19328. this._opaqueSubMeshes.reset();
  19329. this._transparentSubMeshes.reset();
  19330. this._alphaTestSubMeshes.reset();
  19331. this._depthOnlySubMeshes.reset();
  19332. this._particleSystems.reset();
  19333. this._spriteManagers.reset();
  19334. this._edgesRenderers.reset();
  19335. };
  19336. RenderingGroup.prototype.dispose = function () {
  19337. this._opaqueSubMeshes.dispose();
  19338. this._transparentSubMeshes.dispose();
  19339. this._alphaTestSubMeshes.dispose();
  19340. this._depthOnlySubMeshes.dispose();
  19341. this._particleSystems.dispose();
  19342. this._spriteManagers.dispose();
  19343. this._edgesRenderers.dispose();
  19344. };
  19345. /**
  19346. * Inserts the submesh in its correct queue depending on its material.
  19347. * @param subMesh The submesh to dispatch
  19348. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  19349. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  19350. */
  19351. RenderingGroup.prototype.dispatch = function (subMesh, mesh, material) {
  19352. // Get mesh and materials if not provided
  19353. if (mesh === undefined) {
  19354. mesh = subMesh.getMesh();
  19355. }
  19356. if (material === undefined) {
  19357. material = subMesh.getMaterial();
  19358. }
  19359. if (material === null || material === undefined) {
  19360. return;
  19361. }
  19362. if (material.needAlphaBlendingForMesh(mesh)) {
  19363. this._transparentSubMeshes.push(subMesh);
  19364. }
  19365. else if (material.needAlphaTesting()) {
  19366. if (material.needDepthPrePass) {
  19367. this._depthOnlySubMeshes.push(subMesh);
  19368. }
  19369. this._alphaTestSubMeshes.push(subMesh);
  19370. }
  19371. else {
  19372. if (material.needDepthPrePass) {
  19373. this._depthOnlySubMeshes.push(subMesh);
  19374. }
  19375. this._opaqueSubMeshes.push(subMesh); // Opaque
  19376. }
  19377. if (mesh._edgesRenderer !== null && mesh._edgesRenderer !== undefined) {
  19378. this._edgesRenderers.push(mesh._edgesRenderer);
  19379. }
  19380. };
  19381. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  19382. this._spriteManagers.push(spriteManager);
  19383. };
  19384. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  19385. this._particleSystems.push(particleSystem);
  19386. };
  19387. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  19388. if (this._particleSystems.length === 0) {
  19389. return;
  19390. }
  19391. // Particles
  19392. var activeCamera = this._scene.activeCamera;
  19393. this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);
  19394. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  19395. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  19396. if ((activeCamera && activeCamera.layerMask & particleSystem.layerMask) === 0) {
  19397. continue;
  19398. }
  19399. var emitter = particleSystem.emitter;
  19400. if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {
  19401. this._scene._activeParticles.addCount(particleSystem.render(), false);
  19402. }
  19403. }
  19404. this._scene.onAfterParticlesRenderingObservable.notifyObservers(this._scene);
  19405. };
  19406. RenderingGroup.prototype._renderSprites = function () {
  19407. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  19408. return;
  19409. }
  19410. // Sprites
  19411. var activeCamera = this._scene.activeCamera;
  19412. this._scene.onBeforeSpritesRenderingObservable.notifyObservers(this._scene);
  19413. for (var id = 0; id < this._spriteManagers.length; id++) {
  19414. var spriteManager = this._spriteManagers.data[id];
  19415. if (((activeCamera && activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  19416. spriteManager.render();
  19417. }
  19418. }
  19419. this._scene.onAfterSpritesRenderingObservable.notifyObservers(this._scene);
  19420. };
  19421. return RenderingGroup;
  19422. }());
  19423. BABYLON.RenderingGroup = RenderingGroup;
  19424. })(BABYLON || (BABYLON = {}));
  19425. //# sourceMappingURL=babylon.renderingGroup.js.map
  19426. var BABYLON;
  19427. (function (BABYLON) {
  19428. var ClickInfo = /** @class */ (function () {
  19429. function ClickInfo() {
  19430. this._singleClick = false;
  19431. this._doubleClick = false;
  19432. this._hasSwiped = false;
  19433. this._ignore = false;
  19434. }
  19435. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  19436. get: function () {
  19437. return this._singleClick;
  19438. },
  19439. set: function (b) {
  19440. this._singleClick = b;
  19441. },
  19442. enumerable: true,
  19443. configurable: true
  19444. });
  19445. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  19446. get: function () {
  19447. return this._doubleClick;
  19448. },
  19449. set: function (b) {
  19450. this._doubleClick = b;
  19451. },
  19452. enumerable: true,
  19453. configurable: true
  19454. });
  19455. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  19456. get: function () {
  19457. return this._hasSwiped;
  19458. },
  19459. set: function (b) {
  19460. this._hasSwiped = b;
  19461. },
  19462. enumerable: true,
  19463. configurable: true
  19464. });
  19465. Object.defineProperty(ClickInfo.prototype, "ignore", {
  19466. get: function () {
  19467. return this._ignore;
  19468. },
  19469. set: function (b) {
  19470. this._ignore = b;
  19471. },
  19472. enumerable: true,
  19473. configurable: true
  19474. });
  19475. return ClickInfo;
  19476. }());
  19477. /**
  19478. * This class is used by the onRenderingGroupObservable
  19479. */
  19480. var RenderingGroupInfo = /** @class */ (function () {
  19481. function RenderingGroupInfo() {
  19482. }
  19483. /**
  19484. * Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared
  19485. * This stage will be fired no matter what
  19486. */
  19487. RenderingGroupInfo.STAGE_PRECLEAR = 1;
  19488. /**
  19489. * Called before opaque object are rendered.
  19490. * This stage will be fired only if there's 3D Opaque content to render
  19491. */
  19492. RenderingGroupInfo.STAGE_PREOPAQUE = 2;
  19493. /**
  19494. * Called after the opaque objects are rendered and before the transparent ones
  19495. * This stage will be fired only if there's 3D transparent content to render
  19496. */
  19497. RenderingGroupInfo.STAGE_PRETRANSPARENT = 3;
  19498. /**
  19499. * Called after the transparent object are rendered, last hook of the renderingGroup phase
  19500. * This stage will be fired no matter what
  19501. */
  19502. RenderingGroupInfo.STAGE_POSTTRANSPARENT = 4;
  19503. return RenderingGroupInfo;
  19504. }());
  19505. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  19506. /**
  19507. * Represents a scene to be rendered by the engine.
  19508. * @see http://doc.babylonjs.com/page.php?p=21911
  19509. */
  19510. var Scene = /** @class */ (function () {
  19511. /**
  19512. * @constructor
  19513. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  19514. */
  19515. function Scene(engine) {
  19516. // Members
  19517. this.autoClear = true;
  19518. this.autoClearDepthAndStencil = true;
  19519. this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  19520. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  19521. this.forceWireframe = false;
  19522. this._forcePointsCloud = false;
  19523. this.forceShowBoundingBoxes = false;
  19524. this.animationsEnabled = true;
  19525. this.useConstantAnimationDeltaTime = false;
  19526. this.constantlyUpdateMeshUnderPointer = false;
  19527. this.hoverCursor = "pointer";
  19528. this.defaultCursor = "";
  19529. /**
  19530. * This is used to call preventDefault() on pointer down
  19531. * in order to block unwanted artifacts like system double clicks
  19532. */
  19533. this.preventDefaultOnPointerDown = true;
  19534. // Metadata
  19535. this.metadata = null;
  19536. /**
  19537. * An event triggered when the scene is disposed.
  19538. * @type {BABYLON.Observable}
  19539. */
  19540. this.onDisposeObservable = new BABYLON.Observable();
  19541. /**
  19542. * An event triggered before rendering the scene (right after animations and physics)
  19543. * @type {BABYLON.Observable}
  19544. */
  19545. this.onBeforeRenderObservable = new BABYLON.Observable();
  19546. /**
  19547. * An event triggered after rendering the scene
  19548. * @type {BABYLON.Observable}
  19549. */
  19550. this.onAfterRenderObservable = new BABYLON.Observable();
  19551. /**
  19552. * An event triggered before animating the scene
  19553. * @type {BABYLON.Observable}
  19554. */
  19555. this.onBeforeAnimationsObservable = new BABYLON.Observable();
  19556. /**
  19557. * An event triggered after animations processing
  19558. * @type {BABYLON.Observable}
  19559. */
  19560. this.onAfterAnimationsObservable = new BABYLON.Observable();
  19561. /**
  19562. * An event triggered before draw calls are ready to be sent
  19563. * @type {BABYLON.Observable}
  19564. */
  19565. this.onBeforeDrawPhaseObservable = new BABYLON.Observable();
  19566. /**
  19567. * An event triggered after draw calls have been sent
  19568. * @type {BABYLON.Observable}
  19569. */
  19570. this.onAfterDrawPhaseObservable = new BABYLON.Observable();
  19571. /**
  19572. * An event triggered when physic simulation is about to be run
  19573. * @type {BABYLON.Observable}
  19574. */
  19575. this.onBeforePhysicsObservable = new BABYLON.Observable();
  19576. /**
  19577. * An event triggered when physic simulation has been done
  19578. * @type {BABYLON.Observable}
  19579. */
  19580. this.onAfterPhysicsObservable = new BABYLON.Observable();
  19581. /**
  19582. * An event triggered when the scene is ready
  19583. * @type {BABYLON.Observable}
  19584. */
  19585. this.onReadyObservable = new BABYLON.Observable();
  19586. /**
  19587. * An event triggered before rendering a camera
  19588. * @type {BABYLON.Observable}
  19589. */
  19590. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  19591. /**
  19592. * An event triggered after rendering a camera
  19593. * @type {BABYLON.Observable}
  19594. */
  19595. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  19596. /**
  19597. * An event triggered when active meshes evaluation is about to start
  19598. * @type {BABYLON.Observable}
  19599. */
  19600. this.onBeforeActiveMeshesEvaluationObservable = new BABYLON.Observable();
  19601. /**
  19602. * An event triggered when active meshes evaluation is done
  19603. * @type {BABYLON.Observable}
  19604. */
  19605. this.onAfterActiveMeshesEvaluationObservable = new BABYLON.Observable();
  19606. /**
  19607. * An event triggered when particles rendering is about to start
  19608. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  19609. * @type {BABYLON.Observable}
  19610. */
  19611. this.onBeforeParticlesRenderingObservable = new BABYLON.Observable();
  19612. /**
  19613. * An event triggered when particles rendering is done
  19614. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  19615. * @type {BABYLON.Observable}
  19616. */
  19617. this.onAfterParticlesRenderingObservable = new BABYLON.Observable();
  19618. /**
  19619. * An event triggered when sprites rendering is about to start
  19620. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  19621. * @type {BABYLON.Observable}
  19622. */
  19623. this.onBeforeSpritesRenderingObservable = new BABYLON.Observable();
  19624. /**
  19625. * An event triggered when sprites rendering is done
  19626. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  19627. * @type {BABYLON.Observable}
  19628. */
  19629. this.onAfterSpritesRenderingObservable = new BABYLON.Observable();
  19630. /**
  19631. * An event triggered when SceneLoader.Append or SceneLoader.Load or SceneLoader.ImportMesh were successfully executed
  19632. * @type {BABYLON.Observable}
  19633. */
  19634. this.onDataLoadedObservable = new BABYLON.Observable();
  19635. /**
  19636. * An event triggered when a camera is created
  19637. * @type {BABYLON.Observable}
  19638. */
  19639. this.onNewCameraAddedObservable = new BABYLON.Observable();
  19640. /**
  19641. * An event triggered when a camera is removed
  19642. * @type {BABYLON.Observable}
  19643. */
  19644. this.onCameraRemovedObservable = new BABYLON.Observable();
  19645. /**
  19646. * An event triggered when a light is created
  19647. * @type {BABYLON.Observable}
  19648. */
  19649. this.onNewLightAddedObservable = new BABYLON.Observable();
  19650. /**
  19651. * An event triggered when a light is removed
  19652. * @type {BABYLON.Observable}
  19653. */
  19654. this.onLightRemovedObservable = new BABYLON.Observable();
  19655. /**
  19656. * An event triggered when a geometry is created
  19657. * @type {BABYLON.Observable}
  19658. */
  19659. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  19660. /**
  19661. * An event triggered when a geometry is removed
  19662. * @type {BABYLON.Observable}
  19663. */
  19664. this.onGeometryRemovedObservable = new BABYLON.Observable();
  19665. /**
  19666. * An event triggered when a transform node is created
  19667. * @type {BABYLON.Observable}
  19668. */
  19669. this.onNewTransformNodeAddedObservable = new BABYLON.Observable();
  19670. /**
  19671. * An event triggered when a transform node is removed
  19672. * @type {BABYLON.Observable}
  19673. */
  19674. this.onTransformNodeRemovedObservable = new BABYLON.Observable();
  19675. /**
  19676. * An event triggered when a mesh is created
  19677. * @type {BABYLON.Observable}
  19678. */
  19679. this.onNewMeshAddedObservable = new BABYLON.Observable();
  19680. /**
  19681. * An event triggered when a mesh is removed
  19682. * @type {BABYLON.Observable}
  19683. */
  19684. this.onMeshRemovedObservable = new BABYLON.Observable();
  19685. /**
  19686. * An event triggered when render targets are about to be rendered
  19687. * Can happen multiple times per frame.
  19688. * @type {BABYLON.Observable}
  19689. */
  19690. this.OnBeforeRenderTargetsRenderObservable = new BABYLON.Observable();
  19691. /**
  19692. * An event triggered when render targets were rendered.
  19693. * Can happen multiple times per frame.
  19694. * @type {BABYLON.Observable}
  19695. */
  19696. this.OnAfterRenderTargetsRenderObservable = new BABYLON.Observable();
  19697. /**
  19698. * An event triggered before calculating deterministic simulation step
  19699. * @type {BABYLON.Observable}
  19700. */
  19701. this.onBeforeStepObservable = new BABYLON.Observable();
  19702. /**
  19703. * An event triggered after calculating deterministic simulation step
  19704. * @type {BABYLON.Observable}
  19705. */
  19706. this.onAfterStepObservable = new BABYLON.Observable();
  19707. /**
  19708. * This Observable will be triggered for each stage of each renderingGroup of each rendered camera.
  19709. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  19710. * 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)
  19711. */
  19712. this.onRenderingGroupObservable = new BABYLON.Observable();
  19713. // Animations
  19714. this.animations = [];
  19715. /**
  19716. * 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).
  19717. * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true
  19718. */
  19719. this.onPrePointerObservable = new BABYLON.Observable();
  19720. /**
  19721. * Observable event triggered each time an input event is received from the rendering canvas
  19722. */
  19723. this.onPointerObservable = new BABYLON.Observable();
  19724. this._meshPickProceed = false;
  19725. this._currentPickResult = null;
  19726. this._previousPickResult = null;
  19727. this._totalPointersPressed = 0;
  19728. this._doubleClickOccured = false;
  19729. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  19730. this.cameraToUseForPointers = null;
  19731. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  19732. this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  19733. this._startingPointerTime = 0;
  19734. this._previousStartingPointerTime = 0;
  19735. // Deterministic lockstep
  19736. this._timeAccumulator = 0;
  19737. this._currentStepId = 0;
  19738. this._currentInternalStep = 0;
  19739. // Keyboard
  19740. /**
  19741. * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl()
  19742. * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true
  19743. */
  19744. this.onPreKeyboardObservable = new BABYLON.Observable();
  19745. /**
  19746. * Observable event triggered each time an keyboard event is received from the hosting window
  19747. */
  19748. this.onKeyboardObservable = new BABYLON.Observable();
  19749. // Coordinate system
  19750. /**
  19751. * use right-handed coordinate system on this scene.
  19752. * @type {boolean}
  19753. */
  19754. this._useRightHandedSystem = false;
  19755. // Fog
  19756. this._fogEnabled = true;
  19757. this._fogMode = Scene.FOGMODE_NONE;
  19758. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  19759. this.fogDensity = 0.1;
  19760. this.fogStart = 0;
  19761. this.fogEnd = 1000.0;
  19762. // Lights
  19763. /**
  19764. * is shadow enabled on this scene.
  19765. * @type {boolean}
  19766. */
  19767. this._shadowsEnabled = true;
  19768. /**
  19769. * is light enabled on this scene.
  19770. * @type {boolean}
  19771. */
  19772. this._lightsEnabled = true;
  19773. /**
  19774. * All of the lights added to this scene.
  19775. * @see BABYLON.Light
  19776. * @type {BABYLON.Light[]}
  19777. */
  19778. this.lights = new Array();
  19779. // Cameras
  19780. /** All of the cameras added to this scene. */
  19781. this.cameras = new Array();
  19782. /** All of the active cameras added to this scene. */
  19783. this.activeCameras = new Array();
  19784. // Meshes
  19785. /**
  19786. * All of the tranform nodes added to this scene.
  19787. * @see BABYLON.TransformNode
  19788. * @type {BABYLON.TransformNode[]}
  19789. */
  19790. this.transformNodes = new Array();
  19791. /**
  19792. * All of the (abstract) meshes added to this scene.
  19793. * @see BABYLON.AbstractMesh
  19794. * @type {BABYLON.AbstractMesh[]}
  19795. */
  19796. this.meshes = new Array();
  19797. /**
  19798. * All of the animation groups added to this scene.
  19799. * @see BABYLON.AnimationGroup
  19800. * @type {BABYLON.AnimationGroup[]}
  19801. */
  19802. this.animationGroups = new Array();
  19803. // Geometries
  19804. this._geometries = new Array();
  19805. this.materials = new Array();
  19806. this.multiMaterials = new Array();
  19807. // Textures
  19808. this._texturesEnabled = true;
  19809. this.textures = new Array();
  19810. // Particles
  19811. this.particlesEnabled = true;
  19812. this.particleSystems = new Array();
  19813. // Sprites
  19814. this.spritesEnabled = true;
  19815. this.spriteManagers = new Array();
  19816. // Layers
  19817. this.layers = new Array();
  19818. this.highlightLayers = new Array();
  19819. // Skeletons
  19820. this._skeletonsEnabled = true;
  19821. this.skeletons = new Array();
  19822. // Morph targets
  19823. this.morphTargetManagers = new Array();
  19824. // Lens flares
  19825. this.lensFlaresEnabled = true;
  19826. this.lensFlareSystems = new Array();
  19827. // Collisions
  19828. this.collisionsEnabled = true;
  19829. /** Defines the gravity applied to this scene */
  19830. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  19831. // Postprocesses
  19832. this.postProcesses = new Array();
  19833. this.postProcessesEnabled = true;
  19834. // Customs render targets
  19835. this.renderTargetsEnabled = true;
  19836. this.dumpNextRenderTargets = false;
  19837. this.customRenderTargets = new Array();
  19838. // Imported meshes
  19839. this.importedMeshesFiles = new Array();
  19840. // Probes
  19841. this.probesEnabled = true;
  19842. this.reflectionProbes = new Array();
  19843. this._actionManagers = new Array();
  19844. this._meshesForIntersections = new BABYLON.SmartArrayNoDuplicate(256);
  19845. // Procedural textures
  19846. this.proceduralTexturesEnabled = true;
  19847. this._proceduralTextures = new Array();
  19848. this.soundTracks = new Array();
  19849. this._audioEnabled = true;
  19850. this._headphone = false;
  19851. // Performance counters
  19852. this._totalVertices = new BABYLON.PerfCounter();
  19853. this._activeIndices = new BABYLON.PerfCounter();
  19854. this._activeParticles = new BABYLON.PerfCounter();
  19855. this._activeBones = new BABYLON.PerfCounter();
  19856. this._animationTime = 0;
  19857. this.animationTimeScale = 1;
  19858. this._renderId = 0;
  19859. this._executeWhenReadyTimeoutId = -1;
  19860. this._intermediateRendering = false;
  19861. this._viewUpdateFlag = -1;
  19862. this._projectionUpdateFlag = -1;
  19863. this._alternateViewUpdateFlag = -1;
  19864. this._alternateProjectionUpdateFlag = -1;
  19865. this._toBeDisposed = new BABYLON.SmartArray(256);
  19866. this._activeRequests = new Array();
  19867. this._pendingData = new Array();
  19868. this._isDisposed = false;
  19869. this.dispatchAllSubMeshesOfActiveMeshes = false;
  19870. this._activeMeshes = new BABYLON.SmartArray(256);
  19871. this._processedMaterials = new BABYLON.SmartArray(256);
  19872. this._renderTargets = new BABYLON.SmartArrayNoDuplicate(256);
  19873. this._activeParticleSystems = new BABYLON.SmartArray(256);
  19874. this._activeSkeletons = new BABYLON.SmartArrayNoDuplicate(32);
  19875. this._softwareSkinnedMeshes = new BABYLON.SmartArrayNoDuplicate(32);
  19876. this._activeAnimatables = new Array();
  19877. this._transformMatrix = BABYLON.Matrix.Zero();
  19878. this._useAlternateCameraConfiguration = false;
  19879. this._alternateRendering = false;
  19880. this.requireLightSorting = false;
  19881. this._activeMeshesFrozen = false;
  19882. this._tempPickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null;
  19883. this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  19884. this._engine.scenes.push(this);
  19885. this._uid = null;
  19886. this._renderingManager = new BABYLON.RenderingManager(this);
  19887. this.postProcessManager = new BABYLON.PostProcessManager(this);
  19888. if (BABYLON.OutlineRenderer) {
  19889. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  19890. }
  19891. if (BABYLON.Tools.IsWindowObjectExist()) {
  19892. this.attachControl();
  19893. }
  19894. //simplification queue
  19895. if (BABYLON.SimplificationQueue) {
  19896. this.simplificationQueue = new BABYLON.SimplificationQueue();
  19897. }
  19898. //collision coordinator initialization. For now legacy per default.
  19899. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  19900. // Uniform Buffer
  19901. this._createUbo();
  19902. // Default Image processing definition.
  19903. this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  19904. }
  19905. Object.defineProperty(Scene, "FOGMODE_NONE", {
  19906. /** The fog is deactivated */
  19907. get: function () {
  19908. return Scene._FOGMODE_NONE;
  19909. },
  19910. enumerable: true,
  19911. configurable: true
  19912. });
  19913. Object.defineProperty(Scene, "FOGMODE_EXP", {
  19914. /** The fog density is following an exponential function */
  19915. get: function () {
  19916. return Scene._FOGMODE_EXP;
  19917. },
  19918. enumerable: true,
  19919. configurable: true
  19920. });
  19921. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  19922. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  19923. get: function () {
  19924. return Scene._FOGMODE_EXP2;
  19925. },
  19926. enumerable: true,
  19927. configurable: true
  19928. });
  19929. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  19930. /** The fog density is following a linear function. */
  19931. get: function () {
  19932. return Scene._FOGMODE_LINEAR;
  19933. },
  19934. enumerable: true,
  19935. configurable: true
  19936. });
  19937. Object.defineProperty(Scene.prototype, "environmentTexture", {
  19938. /**
  19939. * Texture used in all pbr material as the reflection texture.
  19940. * As in the majority of the scene they are the same (exception for multi room and so on),
  19941. * this is easier to reference from here than from all the materials.
  19942. */
  19943. get: function () {
  19944. return this._environmentTexture;
  19945. },
  19946. /**
  19947. * Texture used in all pbr material as the reflection texture.
  19948. * As in the majority of the scene they are the same (exception for multi room and so on),
  19949. * this is easier to set here than in all the materials.
  19950. */
  19951. set: function (value) {
  19952. if (this._environmentTexture === value) {
  19953. return;
  19954. }
  19955. this._environmentTexture = value;
  19956. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  19957. },
  19958. enumerable: true,
  19959. configurable: true
  19960. });
  19961. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  19962. /**
  19963. * Default image processing configuration used either in the rendering
  19964. * Forward main pass or through the imageProcessingPostProcess if present.
  19965. * As in the majority of the scene they are the same (exception for multi camera),
  19966. * this is easier to reference from here than from all the materials and post process.
  19967. *
  19968. * No setter as we it is a shared configuration, you can set the values instead.
  19969. */
  19970. get: function () {
  19971. return this._imageProcessingConfiguration;
  19972. },
  19973. enumerable: true,
  19974. configurable: true
  19975. });
  19976. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  19977. get: function () {
  19978. return this._forcePointsCloud;
  19979. },
  19980. set: function (value) {
  19981. if (this._forcePointsCloud === value) {
  19982. return;
  19983. }
  19984. this._forcePointsCloud = value;
  19985. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  19986. },
  19987. enumerable: true,
  19988. configurable: true
  19989. });
  19990. Object.defineProperty(Scene.prototype, "onDispose", {
  19991. /** A function to be executed when this scene is disposed. */
  19992. set: function (callback) {
  19993. if (this._onDisposeObserver) {
  19994. this.onDisposeObservable.remove(this._onDisposeObserver);
  19995. }
  19996. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  19997. },
  19998. enumerable: true,
  19999. configurable: true
  20000. });
  20001. Object.defineProperty(Scene.prototype, "beforeRender", {
  20002. /** A function to be executed before rendering this scene */
  20003. set: function (callback) {
  20004. if (this._onBeforeRenderObserver) {
  20005. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  20006. }
  20007. if (callback) {
  20008. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  20009. }
  20010. },
  20011. enumerable: true,
  20012. configurable: true
  20013. });
  20014. Object.defineProperty(Scene.prototype, "afterRender", {
  20015. /** A function to be executed after rendering this scene */
  20016. set: function (callback) {
  20017. if (this._onAfterRenderObserver) {
  20018. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  20019. }
  20020. if (callback) {
  20021. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  20022. }
  20023. },
  20024. enumerable: true,
  20025. configurable: true
  20026. });
  20027. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  20028. set: function (callback) {
  20029. if (this._onBeforeCameraRenderObserver) {
  20030. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  20031. }
  20032. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  20033. },
  20034. enumerable: true,
  20035. configurable: true
  20036. });
  20037. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  20038. set: function (callback) {
  20039. if (this._onAfterCameraRenderObserver) {
  20040. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  20041. }
  20042. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  20043. },
  20044. enumerable: true,
  20045. configurable: true
  20046. });
  20047. Object.defineProperty(Scene.prototype, "gamepadManager", {
  20048. get: function () {
  20049. if (!this._gamepadManager) {
  20050. this._gamepadManager = new BABYLON.GamepadManager(this);
  20051. }
  20052. return this._gamepadManager;
  20053. },
  20054. enumerable: true,
  20055. configurable: true
  20056. });
  20057. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  20058. get: function () {
  20059. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  20060. },
  20061. enumerable: true,
  20062. configurable: true
  20063. });
  20064. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  20065. get: function () {
  20066. return this._useRightHandedSystem;
  20067. },
  20068. set: function (value) {
  20069. if (this._useRightHandedSystem === value) {
  20070. return;
  20071. }
  20072. this._useRightHandedSystem = value;
  20073. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  20074. },
  20075. enumerable: true,
  20076. configurable: true
  20077. });
  20078. Scene.prototype.setStepId = function (newStepId) {
  20079. this._currentStepId = newStepId;
  20080. };
  20081. ;
  20082. Scene.prototype.getStepId = function () {
  20083. return this._currentStepId;
  20084. };
  20085. ;
  20086. Scene.prototype.getInternalStep = function () {
  20087. return this._currentInternalStep;
  20088. };
  20089. ;
  20090. Object.defineProperty(Scene.prototype, "fogEnabled", {
  20091. get: function () {
  20092. return this._fogEnabled;
  20093. },
  20094. /**
  20095. * is fog enabled on this scene.
  20096. */
  20097. set: function (value) {
  20098. if (this._fogEnabled === value) {
  20099. return;
  20100. }
  20101. this._fogEnabled = value;
  20102. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  20103. },
  20104. enumerable: true,
  20105. configurable: true
  20106. });
  20107. Object.defineProperty(Scene.prototype, "fogMode", {
  20108. get: function () {
  20109. return this._fogMode;
  20110. },
  20111. set: function (value) {
  20112. if (this._fogMode === value) {
  20113. return;
  20114. }
  20115. this._fogMode = value;
  20116. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  20117. },
  20118. enumerable: true,
  20119. configurable: true
  20120. });
  20121. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  20122. get: function () {
  20123. return this._shadowsEnabled;
  20124. },
  20125. set: function (value) {
  20126. if (this._shadowsEnabled === value) {
  20127. return;
  20128. }
  20129. this._shadowsEnabled = value;
  20130. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  20131. },
  20132. enumerable: true,
  20133. configurable: true
  20134. });
  20135. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  20136. get: function () {
  20137. return this._lightsEnabled;
  20138. },
  20139. set: function (value) {
  20140. if (this._lightsEnabled === value) {
  20141. return;
  20142. }
  20143. this._lightsEnabled = value;
  20144. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  20145. },
  20146. enumerable: true,
  20147. configurable: true
  20148. });
  20149. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  20150. /** The default material used on meshes when no material is affected */
  20151. get: function () {
  20152. if (!this._defaultMaterial) {
  20153. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  20154. }
  20155. return this._defaultMaterial;
  20156. },
  20157. /** The default material used on meshes when no material is affected */
  20158. set: function (value) {
  20159. this._defaultMaterial = value;
  20160. },
  20161. enumerable: true,
  20162. configurable: true
  20163. });
  20164. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  20165. get: function () {
  20166. return this._texturesEnabled;
  20167. },
  20168. set: function (value) {
  20169. if (this._texturesEnabled === value) {
  20170. return;
  20171. }
  20172. this._texturesEnabled = value;
  20173. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  20174. },
  20175. enumerable: true,
  20176. configurable: true
  20177. });
  20178. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  20179. get: function () {
  20180. return this._skeletonsEnabled;
  20181. },
  20182. set: function (value) {
  20183. if (this._skeletonsEnabled === value) {
  20184. return;
  20185. }
  20186. this._skeletonsEnabled = value;
  20187. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  20188. },
  20189. enumerable: true,
  20190. configurable: true
  20191. });
  20192. Object.defineProperty(Scene.prototype, "postProcessRenderPipelineManager", {
  20193. get: function () {
  20194. if (!this._postProcessRenderPipelineManager) {
  20195. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  20196. }
  20197. return this._postProcessRenderPipelineManager;
  20198. },
  20199. enumerable: true,
  20200. configurable: true
  20201. });
  20202. Object.defineProperty(Scene.prototype, "mainSoundTrack", {
  20203. get: function () {
  20204. if (!this._mainSoundTrack) {
  20205. this._mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  20206. }
  20207. return this._mainSoundTrack;
  20208. },
  20209. enumerable: true,
  20210. configurable: true
  20211. });
  20212. Object.defineProperty(Scene.prototype, "_isAlternateRenderingEnabled", {
  20213. get: function () {
  20214. return this._alternateRendering;
  20215. },
  20216. enumerable: true,
  20217. configurable: true
  20218. });
  20219. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  20220. get: function () {
  20221. return this._frustumPlanes;
  20222. },
  20223. enumerable: true,
  20224. configurable: true
  20225. });
  20226. Object.defineProperty(Scene.prototype, "geometryBufferRenderer", {
  20227. /**
  20228. * Gets the current geometry buffer associated to the scene.
  20229. */
  20230. get: function () {
  20231. return this._geometryBufferRenderer;
  20232. },
  20233. /**
  20234. * Sets the current geometry buffer for the scene.
  20235. */
  20236. set: function (geometryBufferRenderer) {
  20237. if (geometryBufferRenderer && geometryBufferRenderer.isSupported) {
  20238. this._geometryBufferRenderer = geometryBufferRenderer;
  20239. }
  20240. },
  20241. enumerable: true,
  20242. configurable: true
  20243. });
  20244. Object.defineProperty(Scene.prototype, "debugLayer", {
  20245. // Properties
  20246. get: function () {
  20247. if (!this._debugLayer) {
  20248. this._debugLayer = new BABYLON.DebugLayer(this);
  20249. }
  20250. return this._debugLayer;
  20251. },
  20252. enumerable: true,
  20253. configurable: true
  20254. });
  20255. Object.defineProperty(Scene.prototype, "workerCollisions", {
  20256. get: function () {
  20257. return this._workerCollisions;
  20258. },
  20259. set: function (enabled) {
  20260. if (!BABYLON.CollisionCoordinatorLegacy) {
  20261. return;
  20262. }
  20263. enabled = (enabled && !!Worker);
  20264. this._workerCollisions = enabled;
  20265. if (this.collisionCoordinator) {
  20266. this.collisionCoordinator.destroy();
  20267. }
  20268. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  20269. this.collisionCoordinator.init(this);
  20270. },
  20271. enumerable: true,
  20272. configurable: true
  20273. });
  20274. Object.defineProperty(Scene.prototype, "selectionOctree", {
  20275. get: function () {
  20276. return this._selectionOctree;
  20277. },
  20278. enumerable: true,
  20279. configurable: true
  20280. });
  20281. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  20282. /**
  20283. * The mesh that is currently under the pointer.
  20284. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  20285. */
  20286. get: function () {
  20287. return this._pointerOverMesh;
  20288. },
  20289. enumerable: true,
  20290. configurable: true
  20291. });
  20292. Object.defineProperty(Scene.prototype, "pointerX", {
  20293. /**
  20294. * Current on-screen X position of the pointer
  20295. * @return {number} X position of the pointer
  20296. */
  20297. get: function () {
  20298. return this._pointerX;
  20299. },
  20300. enumerable: true,
  20301. configurable: true
  20302. });
  20303. Object.defineProperty(Scene.prototype, "pointerY", {
  20304. /**
  20305. * Current on-screen Y position of the pointer
  20306. * @return {number} Y position of the pointer
  20307. */
  20308. get: function () {
  20309. return this._pointerY;
  20310. },
  20311. enumerable: true,
  20312. configurable: true
  20313. });
  20314. Scene.prototype.getCachedMaterial = function () {
  20315. return this._cachedMaterial;
  20316. };
  20317. Scene.prototype.getCachedEffect = function () {
  20318. return this._cachedEffect;
  20319. };
  20320. Scene.prototype.getCachedVisibility = function () {
  20321. return this._cachedVisibility;
  20322. };
  20323. Scene.prototype.isCachedMaterialInvalid = function (material, effect, visibility) {
  20324. if (visibility === void 0) { visibility = 1; }
  20325. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  20326. };
  20327. Scene.prototype.getBoundingBoxRenderer = function () {
  20328. if (!this._boundingBoxRenderer) {
  20329. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  20330. }
  20331. return this._boundingBoxRenderer;
  20332. };
  20333. Scene.prototype.getOutlineRenderer = function () {
  20334. return this._outlineRenderer;
  20335. };
  20336. Scene.prototype.getEngine = function () {
  20337. return this._engine;
  20338. };
  20339. Scene.prototype.getTotalVertices = function () {
  20340. return this._totalVertices.current;
  20341. };
  20342. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  20343. get: function () {
  20344. return this._totalVertices;
  20345. },
  20346. enumerable: true,
  20347. configurable: true
  20348. });
  20349. Scene.prototype.getActiveIndices = function () {
  20350. return this._activeIndices.current;
  20351. };
  20352. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  20353. get: function () {
  20354. return this._activeIndices;
  20355. },
  20356. enumerable: true,
  20357. configurable: true
  20358. });
  20359. Scene.prototype.getActiveParticles = function () {
  20360. return this._activeParticles.current;
  20361. };
  20362. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  20363. get: function () {
  20364. return this._activeParticles;
  20365. },
  20366. enumerable: true,
  20367. configurable: true
  20368. });
  20369. Scene.prototype.getActiveBones = function () {
  20370. return this._activeBones.current;
  20371. };
  20372. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  20373. get: function () {
  20374. return this._activeBones;
  20375. },
  20376. enumerable: true,
  20377. configurable: true
  20378. });
  20379. // Stats
  20380. Scene.prototype.getInterFramePerfCounter = function () {
  20381. BABYLON.Tools.Warn("getInterFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  20382. return 0;
  20383. };
  20384. Object.defineProperty(Scene.prototype, "interFramePerfCounter", {
  20385. get: function () {
  20386. BABYLON.Tools.Warn("interFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  20387. return null;
  20388. },
  20389. enumerable: true,
  20390. configurable: true
  20391. });
  20392. Scene.prototype.getLastFrameDuration = function () {
  20393. BABYLON.Tools.Warn("getLastFrameDuration is deprecated. Please use SceneInstrumentation class");
  20394. return 0;
  20395. };
  20396. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  20397. get: function () {
  20398. BABYLON.Tools.Warn("lastFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  20399. return null;
  20400. },
  20401. enumerable: true,
  20402. configurable: true
  20403. });
  20404. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  20405. BABYLON.Tools.Warn("getEvaluateActiveMeshesDuration is deprecated. Please use SceneInstrumentation class");
  20406. return 0;
  20407. };
  20408. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  20409. get: function () {
  20410. BABYLON.Tools.Warn("evaluateActiveMeshesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  20411. return null;
  20412. },
  20413. enumerable: true,
  20414. configurable: true
  20415. });
  20416. Scene.prototype.getActiveMeshes = function () {
  20417. return this._activeMeshes;
  20418. };
  20419. Scene.prototype.getRenderTargetsDuration = function () {
  20420. BABYLON.Tools.Warn("getRenderTargetsDuration is deprecated. Please use SceneInstrumentation class");
  20421. return 0;
  20422. };
  20423. Scene.prototype.getRenderDuration = function () {
  20424. BABYLON.Tools.Warn("getRenderDuration is deprecated. Please use SceneInstrumentation class");
  20425. return 0;
  20426. };
  20427. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  20428. get: function () {
  20429. BABYLON.Tools.Warn("renderDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  20430. return null;
  20431. },
  20432. enumerable: true,
  20433. configurable: true
  20434. });
  20435. Scene.prototype.getParticlesDuration = function () {
  20436. BABYLON.Tools.Warn("getParticlesDuration is deprecated. Please use SceneInstrumentation class");
  20437. return 0;
  20438. };
  20439. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  20440. get: function () {
  20441. BABYLON.Tools.Warn("particlesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  20442. return null;
  20443. },
  20444. enumerable: true,
  20445. configurable: true
  20446. });
  20447. Scene.prototype.getSpritesDuration = function () {
  20448. BABYLON.Tools.Warn("getSpritesDuration is deprecated. Please use SceneInstrumentation class");
  20449. return 0;
  20450. };
  20451. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  20452. get: function () {
  20453. BABYLON.Tools.Warn("spriteDuractionPerfCounter is deprecated. Please use SceneInstrumentation class");
  20454. return null;
  20455. },
  20456. enumerable: true,
  20457. configurable: true
  20458. });
  20459. Scene.prototype.getAnimationRatio = function () {
  20460. return this._animationRatio;
  20461. };
  20462. Scene.prototype.getRenderId = function () {
  20463. return this._renderId;
  20464. };
  20465. Scene.prototype.incrementRenderId = function () {
  20466. this._renderId++;
  20467. };
  20468. Scene.prototype._updatePointerPosition = function (evt) {
  20469. var canvasRect = this._engine.getRenderingCanvasClientRect();
  20470. if (!canvasRect) {
  20471. return;
  20472. }
  20473. this._pointerX = evt.clientX - canvasRect.left;
  20474. this._pointerY = evt.clientY - canvasRect.top;
  20475. this._unTranslatedPointerX = this._pointerX;
  20476. this._unTranslatedPointerY = this._pointerY;
  20477. };
  20478. Scene.prototype._createUbo = function () {
  20479. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  20480. this._sceneUbo.addUniform("viewProjection", 16);
  20481. this._sceneUbo.addUniform("view", 16);
  20482. };
  20483. Scene.prototype._createAlternateUbo = function () {
  20484. this._alternateSceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  20485. this._alternateSceneUbo.addUniform("viewProjection", 16);
  20486. this._alternateSceneUbo.addUniform("view", 16);
  20487. };
  20488. // Pointers handling
  20489. /**
  20490. * Use this method to simulate a pointer move on a mesh
  20491. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  20492. */
  20493. Scene.prototype.simulatePointerMove = function (pickResult) {
  20494. var evt = new PointerEvent("pointermove");
  20495. return this._processPointerMove(pickResult, evt);
  20496. };
  20497. Scene.prototype._processPointerMove = function (pickResult, evt) {
  20498. var canvas = this._engine.getRenderingCanvas();
  20499. if (!canvas) {
  20500. return this;
  20501. }
  20502. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  20503. this.setPointerOverSprite(null);
  20504. this.setPointerOverMesh(pickResult.pickedMesh);
  20505. if (this._pointerOverMesh && this._pointerOverMesh.actionManager && this._pointerOverMesh.actionManager.hasPointerTriggers) {
  20506. if (this._pointerOverMesh.actionManager.hoverCursor) {
  20507. canvas.style.cursor = this._pointerOverMesh.actionManager.hoverCursor;
  20508. }
  20509. else {
  20510. canvas.style.cursor = this.hoverCursor;
  20511. }
  20512. }
  20513. else {
  20514. canvas.style.cursor = this.defaultCursor;
  20515. }
  20516. }
  20517. else {
  20518. this.setPointerOverMesh(null);
  20519. // Sprites
  20520. pickResult = this.pickSprite(this._unTranslatedPointerX, this._unTranslatedPointerY, this._spritePredicate, false, this.cameraToUseForPointers || undefined);
  20521. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  20522. this.setPointerOverSprite(pickResult.pickedSprite);
  20523. if (this._pointerOverSprite && this._pointerOverSprite.actionManager && this._pointerOverSprite.actionManager.hoverCursor) {
  20524. canvas.style.cursor = this._pointerOverSprite.actionManager.hoverCursor;
  20525. }
  20526. else {
  20527. canvas.style.cursor = this.hoverCursor;
  20528. }
  20529. }
  20530. else {
  20531. this.setPointerOverSprite(null);
  20532. // Restore pointer
  20533. canvas.style.cursor = this.defaultCursor;
  20534. }
  20535. }
  20536. if (pickResult) {
  20537. if (this.onPointerMove) {
  20538. this.onPointerMove(evt, pickResult);
  20539. }
  20540. if (this.onPointerObservable.hasObservers()) {
  20541. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  20542. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  20543. this.onPointerObservable.notifyObservers(pi, type);
  20544. }
  20545. }
  20546. return this;
  20547. };
  20548. /**
  20549. * Use this method to simulate a pointer down on a mesh
  20550. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  20551. */
  20552. Scene.prototype.simulatePointerDown = function (pickResult) {
  20553. var evt = new PointerEvent("pointerdown");
  20554. return this._processPointerDown(pickResult, evt);
  20555. };
  20556. Scene.prototype._processPointerDown = function (pickResult, evt) {
  20557. var _this = this;
  20558. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  20559. this._pickedDownMesh = pickResult.pickedMesh;
  20560. var actionManager = pickResult.pickedMesh.actionManager;
  20561. if (actionManager) {
  20562. if (actionManager.hasPickTriggers) {
  20563. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  20564. switch (evt.button) {
  20565. case 0:
  20566. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  20567. break;
  20568. case 1:
  20569. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  20570. break;
  20571. case 2:
  20572. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  20573. break;
  20574. }
  20575. }
  20576. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  20577. window.setTimeout(function () {
  20578. 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);
  20579. if (pickResult && pickResult.hit && pickResult.pickedMesh && actionManager) {
  20580. if (_this._totalPointersPressed !== 0 &&
  20581. ((new Date().getTime() - _this._startingPointerTime) > Scene.LongPressDelay) &&
  20582. (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold &&
  20583. Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold)) {
  20584. _this._startingPointerTime = 0;
  20585. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  20586. }
  20587. }
  20588. }, Scene.LongPressDelay);
  20589. }
  20590. }
  20591. }
  20592. if (pickResult) {
  20593. if (this.onPointerDown) {
  20594. this.onPointerDown(evt, pickResult);
  20595. }
  20596. if (this.onPointerObservable.hasObservers()) {
  20597. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  20598. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  20599. this.onPointerObservable.notifyObservers(pi, type);
  20600. }
  20601. }
  20602. return this;
  20603. };
  20604. /**
  20605. * Use this method to simulate a pointer up on a mesh
  20606. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  20607. */
  20608. Scene.prototype.simulatePointerUp = function (pickResult) {
  20609. var evt = new PointerEvent("pointerup");
  20610. var clickInfo = new ClickInfo();
  20611. clickInfo.singleClick = true;
  20612. clickInfo.ignore = true;
  20613. return this._processPointerUp(pickResult, evt, clickInfo);
  20614. };
  20615. Scene.prototype._processPointerUp = function (pickResult, evt, clickInfo) {
  20616. if (pickResult && pickResult && pickResult.pickedMesh) {
  20617. this._pickedUpMesh = pickResult.pickedMesh;
  20618. if (this._pickedDownMesh === this._pickedUpMesh) {
  20619. if (this.onPointerPick) {
  20620. this.onPointerPick(evt, pickResult);
  20621. }
  20622. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  20623. var type = BABYLON.PointerEventTypes.POINTERPICK;
  20624. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  20625. this.onPointerObservable.notifyObservers(pi, type);
  20626. }
  20627. }
  20628. if (pickResult.pickedMesh.actionManager) {
  20629. if (clickInfo.ignore) {
  20630. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  20631. }
  20632. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  20633. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  20634. }
  20635. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  20636. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  20637. }
  20638. }
  20639. }
  20640. if (this._pickedDownMesh &&
  20641. this._pickedDownMesh.actionManager &&
  20642. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  20643. this._pickedDownMesh !== this._pickedUpMesh) {
  20644. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  20645. }
  20646. if (this.onPointerUp) {
  20647. this.onPointerUp(evt, pickResult);
  20648. }
  20649. if (this.onPointerObservable.hasObservers()) {
  20650. if (!clickInfo.ignore) {
  20651. if (!clickInfo.hasSwiped) {
  20652. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  20653. var type = BABYLON.PointerEventTypes.POINTERTAP;
  20654. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  20655. this.onPointerObservable.notifyObservers(pi, type);
  20656. }
  20657. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  20658. var type = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  20659. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  20660. this.onPointerObservable.notifyObservers(pi, type);
  20661. }
  20662. }
  20663. }
  20664. else {
  20665. var type = BABYLON.PointerEventTypes.POINTERUP;
  20666. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  20667. this.onPointerObservable.notifyObservers(pi, type);
  20668. }
  20669. }
  20670. return this;
  20671. };
  20672. /**
  20673. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  20674. * @param attachUp defines if you want to attach events to pointerup
  20675. * @param attachDown defines if you want to attach events to pointerdown
  20676. * @param attachMove defines if you want to attach events to pointermove
  20677. */
  20678. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  20679. var _this = this;
  20680. if (attachUp === void 0) { attachUp = true; }
  20681. if (attachDown === void 0) { attachDown = true; }
  20682. if (attachMove === void 0) { attachMove = true; }
  20683. this._initActionManager = function (act, clickInfo) {
  20684. if (!_this._meshPickProceed) {
  20685. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  20686. _this._currentPickResult = pickResult;
  20687. if (pickResult) {
  20688. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  20689. }
  20690. _this._meshPickProceed = true;
  20691. }
  20692. return act;
  20693. };
  20694. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  20695. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  20696. if ((new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  20697. btn !== _this._previousButtonPressed) {
  20698. _this._doubleClickOccured = false;
  20699. clickInfo.singleClick = true;
  20700. clickInfo.ignore = false;
  20701. cb(clickInfo, _this._currentPickResult);
  20702. }
  20703. };
  20704. this._initClickEvent = function (obs1, obs2, evt, cb) {
  20705. var clickInfo = new ClickInfo();
  20706. _this._currentPickResult = null;
  20707. var act = null;
  20708. var checkPicking = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK)
  20709. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)
  20710. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  20711. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  20712. act = _this._initActionManager(act, clickInfo);
  20713. if (act)
  20714. checkPicking = act.hasPickTriggers;
  20715. }
  20716. if (checkPicking) {
  20717. var btn = evt.button;
  20718. clickInfo.hasSwiped = Math.abs(_this._startingPointerPosition.x - _this._pointerX) > Scene.DragMovementThreshold ||
  20719. Math.abs(_this._startingPointerPosition.y - _this._pointerY) > Scene.DragMovementThreshold;
  20720. if (!clickInfo.hasSwiped) {
  20721. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  20722. if (!checkSingleClickImmediately) {
  20723. checkSingleClickImmediately = !obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) &&
  20724. !obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  20725. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  20726. act = _this._initActionManager(act, clickInfo);
  20727. if (act)
  20728. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  20729. }
  20730. }
  20731. if (checkSingleClickImmediately) {
  20732. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  20733. if (new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  20734. btn !== _this._previousButtonPressed) {
  20735. clickInfo.singleClick = true;
  20736. cb(clickInfo, _this._currentPickResult);
  20737. }
  20738. }
  20739. else {
  20740. // wait that no double click has been raised during the double click delay
  20741. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  20742. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  20743. }
  20744. var checkDoubleClick = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) ||
  20745. obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  20746. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  20747. act = _this._initActionManager(act, clickInfo);
  20748. if (act)
  20749. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  20750. }
  20751. if (checkDoubleClick) {
  20752. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  20753. if (btn === _this._previousButtonPressed &&
  20754. new Date().getTime() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  20755. !_this._doubleClickOccured) {
  20756. // pointer has not moved for 2 clicks, it's a double click
  20757. if (!clickInfo.hasSwiped &&
  20758. Math.abs(_this._previousStartingPointerPosition.x - _this._startingPointerPosition.x) < Scene.DragMovementThreshold &&
  20759. Math.abs(_this._previousStartingPointerPosition.y - _this._startingPointerPosition.y) < Scene.DragMovementThreshold) {
  20760. _this._previousStartingPointerTime = 0;
  20761. _this._doubleClickOccured = true;
  20762. clickInfo.doubleClick = true;
  20763. clickInfo.ignore = false;
  20764. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout) {
  20765. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  20766. }
  20767. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  20768. cb(clickInfo, _this._currentPickResult);
  20769. }
  20770. else {
  20771. _this._doubleClickOccured = false;
  20772. _this._previousStartingPointerTime = _this._startingPointerTime;
  20773. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  20774. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  20775. _this._previousButtonPressed = btn;
  20776. if (Scene.ExclusiveDoubleClickMode) {
  20777. if (_this._previousDelayedSimpleClickTimeout) {
  20778. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  20779. }
  20780. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  20781. cb(clickInfo, _this._previousPickResult);
  20782. }
  20783. else {
  20784. cb(clickInfo, _this._currentPickResult);
  20785. }
  20786. }
  20787. }
  20788. else {
  20789. _this._doubleClickOccured = false;
  20790. _this._previousStartingPointerTime = _this._startingPointerTime;
  20791. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  20792. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  20793. _this._previousButtonPressed = btn;
  20794. }
  20795. }
  20796. }
  20797. }
  20798. clickInfo.ignore = true;
  20799. cb(clickInfo, _this._currentPickResult);
  20800. };
  20801. this._spritePredicate = function (sprite) {
  20802. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  20803. };
  20804. this._onPointerMove = function (evt) {
  20805. _this._updatePointerPosition(evt);
  20806. // PreObservable support
  20807. if (_this.onPrePointerObservable.hasObservers()) {
  20808. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  20809. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  20810. _this.onPrePointerObservable.notifyObservers(pi, type);
  20811. if (pi.skipOnPointerObservable) {
  20812. return;
  20813. }
  20814. }
  20815. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  20816. return;
  20817. }
  20818. if (!_this.pointerMovePredicate) {
  20819. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  20820. }
  20821. // Meshes
  20822. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  20823. _this._processPointerMove(pickResult, evt);
  20824. };
  20825. this._onPointerDown = function (evt) {
  20826. _this._totalPointersPressed++;
  20827. _this._pickedDownMesh = null;
  20828. _this._meshPickProceed = false;
  20829. _this._updatePointerPosition(evt);
  20830. if (_this.preventDefaultOnPointerDown && canvas) {
  20831. evt.preventDefault();
  20832. canvas.focus();
  20833. }
  20834. // PreObservable support
  20835. if (_this.onPrePointerObservable.hasObservers()) {
  20836. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  20837. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  20838. _this.onPrePointerObservable.notifyObservers(pi, type);
  20839. if (pi.skipOnPointerObservable) {
  20840. return;
  20841. }
  20842. }
  20843. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  20844. return;
  20845. }
  20846. _this._startingPointerPosition.x = _this._pointerX;
  20847. _this._startingPointerPosition.y = _this._pointerY;
  20848. _this._startingPointerTime = new Date().getTime();
  20849. if (!_this.pointerDownPredicate) {
  20850. _this.pointerDownPredicate = function (mesh) {
  20851. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  20852. };
  20853. }
  20854. // Meshes
  20855. _this._pickedDownMesh = null;
  20856. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  20857. _this._processPointerDown(pickResult, evt);
  20858. // Sprites
  20859. _this._pickedDownSprite = null;
  20860. if (_this.spriteManagers.length > 0) {
  20861. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  20862. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  20863. if (pickResult.pickedSprite.actionManager) {
  20864. _this._pickedDownSprite = pickResult.pickedSprite;
  20865. switch (evt.button) {
  20866. case 0:
  20867. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  20868. break;
  20869. case 1:
  20870. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  20871. break;
  20872. case 2:
  20873. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  20874. break;
  20875. }
  20876. if (pickResult.pickedSprite.actionManager) {
  20877. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  20878. }
  20879. }
  20880. }
  20881. }
  20882. };
  20883. this._onPointerUp = function (evt) {
  20884. if (_this._totalPointersPressed === 0) {
  20885. return; // So we need to test it the pointer down was pressed before.
  20886. }
  20887. _this._totalPointersPressed--;
  20888. _this._pickedUpMesh = null;
  20889. _this._meshPickProceed = false;
  20890. _this._updatePointerPosition(evt);
  20891. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, function (clickInfo, pickResult) {
  20892. // PreObservable support
  20893. if (_this.onPrePointerObservable.hasObservers()) {
  20894. if (!clickInfo.ignore) {
  20895. if (!clickInfo.hasSwiped) {
  20896. if (clickInfo.singleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  20897. var type = BABYLON.PointerEventTypes.POINTERTAP;
  20898. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  20899. _this.onPrePointerObservable.notifyObservers(pi, type);
  20900. if (pi.skipOnPointerObservable) {
  20901. return;
  20902. }
  20903. }
  20904. if (clickInfo.doubleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  20905. var type = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  20906. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  20907. _this.onPrePointerObservable.notifyObservers(pi, type);
  20908. if (pi.skipOnPointerObservable) {
  20909. return;
  20910. }
  20911. }
  20912. }
  20913. }
  20914. else {
  20915. var type = BABYLON.PointerEventTypes.POINTERUP;
  20916. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  20917. _this.onPrePointerObservable.notifyObservers(pi, type);
  20918. if (pi.skipOnPointerObservable) {
  20919. return;
  20920. }
  20921. }
  20922. }
  20923. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  20924. return;
  20925. }
  20926. if (!_this.pointerUpPredicate) {
  20927. _this.pointerUpPredicate = function (mesh) {
  20928. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  20929. };
  20930. }
  20931. // Meshes
  20932. if (!_this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || _this.onPointerObservable.hasObservers())) {
  20933. _this._initActionManager(null, clickInfo);
  20934. }
  20935. if (!pickResult) {
  20936. pickResult = _this._currentPickResult;
  20937. }
  20938. _this._processPointerUp(pickResult, evt, clickInfo);
  20939. // Sprites
  20940. if (_this.spriteManagers.length > 0) {
  20941. var spritePickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  20942. if (spritePickResult) {
  20943. if (spritePickResult.hit && spritePickResult.pickedSprite) {
  20944. if (spritePickResult.pickedSprite.actionManager) {
  20945. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  20946. if (spritePickResult.pickedSprite.actionManager) {
  20947. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold) {
  20948. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  20949. }
  20950. }
  20951. }
  20952. }
  20953. if (_this._pickedDownSprite && _this._pickedDownSprite.actionManager && _this._pickedDownSprite !== spritePickResult.pickedSprite) {
  20954. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  20955. }
  20956. }
  20957. }
  20958. _this._previousPickResult = _this._currentPickResult;
  20959. });
  20960. };
  20961. this._onKeyDown = function (evt) {
  20962. var type = BABYLON.KeyboardEventTypes.KEYDOWN;
  20963. if (_this.onPreKeyboardObservable.hasObservers()) {
  20964. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  20965. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  20966. if (pi.skipOnPointerObservable) {
  20967. return;
  20968. }
  20969. }
  20970. if (_this.onKeyboardObservable.hasObservers()) {
  20971. var pi = new BABYLON.KeyboardInfo(type, evt);
  20972. _this.onKeyboardObservable.notifyObservers(pi, type);
  20973. }
  20974. if (_this.actionManager) {
  20975. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  20976. }
  20977. };
  20978. this._onKeyUp = function (evt) {
  20979. var type = BABYLON.KeyboardEventTypes.KEYUP;
  20980. if (_this.onPreKeyboardObservable.hasObservers()) {
  20981. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  20982. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  20983. if (pi.skipOnPointerObservable) {
  20984. return;
  20985. }
  20986. }
  20987. if (_this.onKeyboardObservable.hasObservers()) {
  20988. var pi = new BABYLON.KeyboardInfo(type, evt);
  20989. _this.onKeyboardObservable.notifyObservers(pi, type);
  20990. }
  20991. if (_this.actionManager) {
  20992. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  20993. }
  20994. };
  20995. var engine = this.getEngine();
  20996. this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add(function () {
  20997. if (!canvas) {
  20998. return;
  20999. }
  21000. canvas.addEventListener("keydown", _this._onKeyDown, false);
  21001. canvas.addEventListener("keyup", _this._onKeyUp, false);
  21002. });
  21003. this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(function () {
  21004. if (!canvas) {
  21005. return;
  21006. }
  21007. canvas.removeEventListener("keydown", _this._onKeyDown);
  21008. canvas.removeEventListener("keyup", _this._onKeyUp);
  21009. });
  21010. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  21011. var canvas = this._engine.getRenderingCanvas();
  21012. if (!canvas) {
  21013. return;
  21014. }
  21015. if (attachMove) {
  21016. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  21017. // Wheel
  21018. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  21019. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  21020. }
  21021. if (attachDown) {
  21022. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  21023. }
  21024. if (attachUp) {
  21025. window.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  21026. }
  21027. canvas.tabIndex = 1;
  21028. };
  21029. Scene.prototype.detachControl = function () {
  21030. var engine = this.getEngine();
  21031. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  21032. var canvas = engine.getRenderingCanvas();
  21033. if (!canvas) {
  21034. return;
  21035. }
  21036. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  21037. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  21038. window.removeEventListener(eventPrefix + "up", this._onPointerUp);
  21039. if (this._onCanvasBlurObserver) {
  21040. engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  21041. }
  21042. if (this._onCanvasFocusObserver) {
  21043. engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver);
  21044. }
  21045. // Wheel
  21046. canvas.removeEventListener('mousewheel', this._onPointerMove);
  21047. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  21048. // Keyboard
  21049. canvas.removeEventListener("keydown", this._onKeyDown);
  21050. canvas.removeEventListener("keyup", this._onKeyUp);
  21051. // Observables
  21052. this.onKeyboardObservable.clear();
  21053. this.onPreKeyboardObservable.clear();
  21054. this.onPointerObservable.clear();
  21055. this.onPrePointerObservable.clear();
  21056. };
  21057. /**
  21058. * This function will check if the scene can be rendered (textures are loaded, shaders are compiled)
  21059. * Delay loaded resources are not taking in account
  21060. * @return true if all required resources are ready
  21061. */
  21062. Scene.prototype.isReady = function () {
  21063. if (this._isDisposed) {
  21064. return false;
  21065. }
  21066. if (this._pendingData.length > 0) {
  21067. return false;
  21068. }
  21069. var index;
  21070. var engine = this.getEngine();
  21071. // Geometries
  21072. for (index = 0; index < this._geometries.length; index++) {
  21073. var geometry = this._geometries[index];
  21074. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  21075. return false;
  21076. }
  21077. }
  21078. // Meshes
  21079. for (index = 0; index < this.meshes.length; index++) {
  21080. var mesh = this.meshes[index];
  21081. if (!mesh.isEnabled()) {
  21082. continue;
  21083. }
  21084. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  21085. continue;
  21086. }
  21087. if (!mesh.isReady()) {
  21088. return false;
  21089. }
  21090. // Highlight layers
  21091. var hardwareInstancedRendering = mesh.getClassName() === "InstancedMesh" || engine.getCaps().instancedArrays && mesh.instances.length > 0;
  21092. for (var _i = 0, _a = this.highlightLayers; _i < _a.length; _i++) {
  21093. var layer = _a[_i];
  21094. if (!layer.hasMesh(mesh)) {
  21095. continue;
  21096. }
  21097. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  21098. var subMesh = _c[_b];
  21099. if (!layer.isReady(subMesh, hardwareInstancedRendering)) {
  21100. return false;
  21101. }
  21102. }
  21103. }
  21104. }
  21105. return true;
  21106. };
  21107. Scene.prototype.resetCachedMaterial = function () {
  21108. this._cachedMaterial = null;
  21109. this._cachedEffect = null;
  21110. this._cachedVisibility = null;
  21111. };
  21112. Scene.prototype.registerBeforeRender = function (func) {
  21113. this.onBeforeRenderObservable.add(func);
  21114. };
  21115. Scene.prototype.unregisterBeforeRender = function (func) {
  21116. this.onBeforeRenderObservable.removeCallback(func);
  21117. };
  21118. Scene.prototype.registerAfterRender = function (func) {
  21119. this.onAfterRenderObservable.add(func);
  21120. };
  21121. Scene.prototype.unregisterAfterRender = function (func) {
  21122. this.onAfterRenderObservable.removeCallback(func);
  21123. };
  21124. Scene.prototype._executeOnceBeforeRender = function (func) {
  21125. var _this = this;
  21126. var execFunc = function () {
  21127. func();
  21128. setTimeout(function () {
  21129. _this.unregisterBeforeRender(execFunc);
  21130. });
  21131. };
  21132. this.registerBeforeRender(execFunc);
  21133. };
  21134. /**
  21135. * The provided function will run before render once and will be disposed afterwards.
  21136. * A timeout delay can be provided so that the function will be executed in N ms.
  21137. * The timeout is using the browser's native setTimeout so time percision cannot be guaranteed.
  21138. * @param func The function to be executed.
  21139. * @param timeout optional delay in ms
  21140. */
  21141. Scene.prototype.executeOnceBeforeRender = function (func, timeout) {
  21142. var _this = this;
  21143. if (timeout !== undefined) {
  21144. setTimeout(function () {
  21145. _this._executeOnceBeforeRender(func);
  21146. }, timeout);
  21147. }
  21148. else {
  21149. this._executeOnceBeforeRender(func);
  21150. }
  21151. };
  21152. Scene.prototype._addPendingData = function (data) {
  21153. this._pendingData.push(data);
  21154. };
  21155. Scene.prototype._removePendingData = function (data) {
  21156. var wasLoading = this.isLoading;
  21157. var index = this._pendingData.indexOf(data);
  21158. if (index !== -1) {
  21159. this._pendingData.splice(index, 1);
  21160. }
  21161. if (wasLoading && !this.isLoading) {
  21162. this.onDataLoadedObservable.notifyObservers(this);
  21163. }
  21164. };
  21165. Scene.prototype.getWaitingItemsCount = function () {
  21166. return this._pendingData.length;
  21167. };
  21168. Object.defineProperty(Scene.prototype, "isLoading", {
  21169. get: function () {
  21170. return this._pendingData.length > 0;
  21171. },
  21172. enumerable: true,
  21173. configurable: true
  21174. });
  21175. /**
  21176. * Registers a function to be executed when the scene is ready.
  21177. * @param {Function} func - the function to be executed.
  21178. */
  21179. Scene.prototype.executeWhenReady = function (func) {
  21180. var _this = this;
  21181. this.onReadyObservable.add(func);
  21182. if (this._executeWhenReadyTimeoutId !== -1) {
  21183. return;
  21184. }
  21185. this._executeWhenReadyTimeoutId = setTimeout(function () {
  21186. _this._checkIsReady();
  21187. }, 150);
  21188. };
  21189. Scene.prototype._checkIsReady = function () {
  21190. var _this = this;
  21191. if (this.isReady()) {
  21192. this.onReadyObservable.notifyObservers(this);
  21193. this.onReadyObservable.clear();
  21194. this._executeWhenReadyTimeoutId = -1;
  21195. return;
  21196. }
  21197. this._executeWhenReadyTimeoutId = setTimeout(function () {
  21198. _this._checkIsReady();
  21199. }, 150);
  21200. };
  21201. // Animations
  21202. /**
  21203. * Will start the animation sequence of a given target
  21204. * @param target - the target
  21205. * @param {number} from - from which frame should animation start
  21206. * @param {number} to - till which frame should animation run.
  21207. * @param {boolean} [loop] - should the animation loop
  21208. * @param {number} [speedRatio] - the speed in which to run the animation
  21209. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  21210. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  21211. * Returns {BABYLON.Animatable} the animatable object created for this animation
  21212. * See BABYLON.Animatable
  21213. */
  21214. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  21215. if (speedRatio === void 0) { speedRatio = 1.0; }
  21216. if (from > to && speedRatio > 0) {
  21217. speedRatio *= -1;
  21218. }
  21219. this.stopAnimation(target);
  21220. if (!animatable) {
  21221. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  21222. }
  21223. // Local animations
  21224. if (target.animations) {
  21225. animatable.appendAnimations(target, target.animations);
  21226. }
  21227. // Children animations
  21228. if (target.getAnimatables) {
  21229. var animatables = target.getAnimatables();
  21230. for (var index = 0; index < animatables.length; index++) {
  21231. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  21232. }
  21233. }
  21234. animatable.reset();
  21235. return animatable;
  21236. };
  21237. /**
  21238. * Begin a new animation on a given node
  21239. * @param {BABYLON.Node} node defines the root node where the animation will take place
  21240. * @param {BABYLON.Animation[]} defines the list of animations to start
  21241. * @param {number} from defines the initial value
  21242. * @param {number} to defines the final value
  21243. * @param {boolean} loop defines if you want animation to loop (off by default)
  21244. * @param {number} speedRatio defines the speed ratio to apply to all animations
  21245. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  21246. * @returns the list of created animatables
  21247. */
  21248. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  21249. if (speedRatio === undefined) {
  21250. speedRatio = 1.0;
  21251. }
  21252. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  21253. return animatable;
  21254. };
  21255. /**
  21256. * Begin a new animation on a given node and its hierarchy
  21257. * @param {BABYLON.Node} node defines the root node where the animation will take place
  21258. * @param {boolean} directDescendantsOnly if true only direct descendants will be used, if false direct and also indirect (children of children, an so on in a recursive manner) descendants will be used.
  21259. * @param {BABYLON.Animation[]} defines the list of animations to start
  21260. * @param {number} from defines the initial value
  21261. * @param {number} to defines the final value
  21262. * @param {boolean} loop defines if you want animation to loop (off by default)
  21263. * @param {number} speedRatio defines the speed ratio to apply to all animations
  21264. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  21265. * @returns the list of animatables created for all nodes
  21266. */
  21267. Scene.prototype.beginDirectHierarchyAnimation = function (target, directDescendantsOnly, animations, from, to, loop, speedRatio, onAnimationEnd) {
  21268. var children = target.getDescendants(directDescendantsOnly);
  21269. var result = [];
  21270. for (var _i = 0, children_1 = children; _i < children_1.length; _i++) {
  21271. var child = children_1[_i];
  21272. result.push(this.beginDirectAnimation(child, animations, from, to, loop, speedRatio, onAnimationEnd));
  21273. }
  21274. return result;
  21275. };
  21276. Scene.prototype.getAnimatableByTarget = function (target) {
  21277. for (var index = 0; index < this._activeAnimatables.length; index++) {
  21278. if (this._activeAnimatables[index].target === target) {
  21279. return this._activeAnimatables[index];
  21280. }
  21281. }
  21282. return null;
  21283. };
  21284. Object.defineProperty(Scene.prototype, "animatables", {
  21285. get: function () {
  21286. return this._activeAnimatables;
  21287. },
  21288. enumerable: true,
  21289. configurable: true
  21290. });
  21291. /**
  21292. * Will stop the animation of the given target
  21293. * @param target - the target
  21294. * @param animationName - the name of the animation to stop (all animations will be stopped is empty)
  21295. * @see beginAnimation
  21296. */
  21297. Scene.prototype.stopAnimation = function (target, animationName) {
  21298. var animatable = this.getAnimatableByTarget(target);
  21299. if (animatable) {
  21300. animatable.stop(animationName);
  21301. }
  21302. };
  21303. /**
  21304. * Stops and removes all animations that have been applied to the scene
  21305. */
  21306. Scene.prototype.stopAllAnimations = function () {
  21307. if (this._activeAnimatables) {
  21308. for (var i = 0; i < this._activeAnimatables.length; i++) {
  21309. this._activeAnimatables[i].stop();
  21310. }
  21311. this._activeAnimatables = [];
  21312. }
  21313. };
  21314. Scene.prototype._animate = function () {
  21315. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  21316. return;
  21317. }
  21318. // Getting time
  21319. var now = BABYLON.Tools.Now;
  21320. if (!this._animationTimeLast) {
  21321. if (this._pendingData.length > 0) {
  21322. return;
  21323. }
  21324. this._animationTimeLast = now;
  21325. }
  21326. var deltaTime = this.useConstantAnimationDeltaTime ? 16.0 : (now - this._animationTimeLast) * this.animationTimeScale;
  21327. this._animationTime += deltaTime;
  21328. this._animationTimeLast = now;
  21329. for (var index = 0; index < this._activeAnimatables.length; index++) {
  21330. this._activeAnimatables[index]._animate(this._animationTime);
  21331. }
  21332. };
  21333. // Matrix
  21334. Scene.prototype._switchToAlternateCameraConfiguration = function (active) {
  21335. this._useAlternateCameraConfiguration = active;
  21336. };
  21337. Scene.prototype.getViewMatrix = function () {
  21338. return this._useAlternateCameraConfiguration ? this._alternateViewMatrix : this._viewMatrix;
  21339. };
  21340. Scene.prototype.getProjectionMatrix = function () {
  21341. return this._useAlternateCameraConfiguration ? this._alternateProjectionMatrix : this._projectionMatrix;
  21342. };
  21343. Scene.prototype.getTransformMatrix = function () {
  21344. return this._useAlternateCameraConfiguration ? this._alternateTransformMatrix : this._transformMatrix;
  21345. };
  21346. Scene.prototype.setTransformMatrix = function (view, projection) {
  21347. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  21348. return;
  21349. }
  21350. this._viewUpdateFlag = view.updateFlag;
  21351. this._projectionUpdateFlag = projection.updateFlag;
  21352. this._viewMatrix = view;
  21353. this._projectionMatrix = projection;
  21354. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  21355. // Update frustum
  21356. if (!this._frustumPlanes) {
  21357. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  21358. }
  21359. else {
  21360. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  21361. }
  21362. if (this.activeCamera && this.activeCamera._alternateCamera) {
  21363. var otherCamera = this.activeCamera._alternateCamera;
  21364. otherCamera.getViewMatrix().multiplyToRef(otherCamera.getProjectionMatrix(), BABYLON.Tmp.Matrix[0]);
  21365. BABYLON.Frustum.GetRightPlaneToRef(BABYLON.Tmp.Matrix[0], this._frustumPlanes[3]); // Replace right plane by second camera right plane
  21366. }
  21367. if (this._sceneUbo.useUbo) {
  21368. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  21369. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  21370. this._sceneUbo.update();
  21371. }
  21372. };
  21373. Scene.prototype._setAlternateTransformMatrix = function (view, projection) {
  21374. if (this._alternateViewUpdateFlag === view.updateFlag && this._alternateProjectionUpdateFlag === projection.updateFlag) {
  21375. return;
  21376. }
  21377. this._alternateViewUpdateFlag = view.updateFlag;
  21378. this._alternateProjectionUpdateFlag = projection.updateFlag;
  21379. this._alternateViewMatrix = view;
  21380. this._alternateProjectionMatrix = projection;
  21381. if (!this._alternateTransformMatrix) {
  21382. this._alternateTransformMatrix = BABYLON.Matrix.Zero();
  21383. }
  21384. this._alternateViewMatrix.multiplyToRef(this._alternateProjectionMatrix, this._alternateTransformMatrix);
  21385. if (!this._alternateSceneUbo) {
  21386. this._createAlternateUbo();
  21387. }
  21388. if (this._alternateSceneUbo.useUbo) {
  21389. this._alternateSceneUbo.updateMatrix("viewProjection", this._alternateTransformMatrix);
  21390. this._alternateSceneUbo.updateMatrix("view", this._alternateViewMatrix);
  21391. this._alternateSceneUbo.update();
  21392. }
  21393. };
  21394. Scene.prototype.getSceneUniformBuffer = function () {
  21395. return this._useAlternateCameraConfiguration ? this._alternateSceneUbo : this._sceneUbo;
  21396. };
  21397. // Methods
  21398. Scene.prototype.getUniqueId = function () {
  21399. var result = Scene._uniqueIdCounter;
  21400. Scene._uniqueIdCounter++;
  21401. return result;
  21402. };
  21403. Scene.prototype.addMesh = function (newMesh) {
  21404. this.meshes.push(newMesh);
  21405. //notify the collision coordinator
  21406. if (this.collisionCoordinator) {
  21407. this.collisionCoordinator.onMeshAdded(newMesh);
  21408. }
  21409. newMesh._resyncLightSources();
  21410. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  21411. };
  21412. Scene.prototype.removeMesh = function (toRemove) {
  21413. var index = this.meshes.indexOf(toRemove);
  21414. if (index !== -1) {
  21415. // Remove from the scene if mesh found
  21416. this.meshes.splice(index, 1);
  21417. }
  21418. this.onMeshRemovedObservable.notifyObservers(toRemove);
  21419. return index;
  21420. };
  21421. Scene.prototype.addTransformNode = function (newTransformNode) {
  21422. this.transformNodes.push(newTransformNode);
  21423. this.onNewTransformNodeAddedObservable.notifyObservers(newTransformNode);
  21424. };
  21425. Scene.prototype.removeTransformNode = function (toRemove) {
  21426. var index = this.transformNodes.indexOf(toRemove);
  21427. if (index !== -1) {
  21428. // Remove from the scene if found
  21429. this.transformNodes.splice(index, 1);
  21430. }
  21431. this.onTransformNodeRemovedObservable.notifyObservers(toRemove);
  21432. return index;
  21433. };
  21434. Scene.prototype.removeSkeleton = function (toRemove) {
  21435. var index = this.skeletons.indexOf(toRemove);
  21436. if (index !== -1) {
  21437. // Remove from the scene if found
  21438. this.skeletons.splice(index, 1);
  21439. }
  21440. return index;
  21441. };
  21442. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  21443. var index = this.morphTargetManagers.indexOf(toRemove);
  21444. if (index !== -1) {
  21445. // Remove from the scene if found
  21446. this.morphTargetManagers.splice(index, 1);
  21447. }
  21448. return index;
  21449. };
  21450. Scene.prototype.removeLight = function (toRemove) {
  21451. var index = this.lights.indexOf(toRemove);
  21452. if (index !== -1) {
  21453. // Remove from meshes
  21454. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  21455. var mesh = _a[_i];
  21456. mesh._removeLightSource(toRemove);
  21457. }
  21458. // Remove from the scene if mesh found
  21459. this.lights.splice(index, 1);
  21460. this.sortLightsByPriority();
  21461. }
  21462. this.onLightRemovedObservable.notifyObservers(toRemove);
  21463. return index;
  21464. };
  21465. Scene.prototype.removeCamera = function (toRemove) {
  21466. var index = this.cameras.indexOf(toRemove);
  21467. if (index !== -1) {
  21468. // Remove from the scene if mesh found
  21469. this.cameras.splice(index, 1);
  21470. }
  21471. // Remove from activeCameras
  21472. var index2 = this.activeCameras.indexOf(toRemove);
  21473. if (index2 !== -1) {
  21474. // Remove from the scene if mesh found
  21475. this.activeCameras.splice(index2, 1);
  21476. }
  21477. // Reset the activeCamera
  21478. if (this.activeCamera === toRemove) {
  21479. if (this.cameras.length > 0) {
  21480. this.activeCamera = this.cameras[0];
  21481. }
  21482. else {
  21483. this.activeCamera = null;
  21484. }
  21485. }
  21486. this.onCameraRemovedObservable.notifyObservers(toRemove);
  21487. return index;
  21488. };
  21489. Scene.prototype.removeParticleSystem = function (toRemove) {
  21490. var index = this.particleSystems.indexOf(toRemove);
  21491. if (index !== -1) {
  21492. this.particleSystems.splice(index, 1);
  21493. }
  21494. return index;
  21495. };
  21496. ;
  21497. Scene.prototype.removeAnimation = function (toRemove) {
  21498. var index = this.animations.indexOf(toRemove);
  21499. if (index !== -1) {
  21500. this.animations.splice(index, 1);
  21501. }
  21502. return index;
  21503. };
  21504. ;
  21505. Scene.prototype.removeMultiMaterial = function (toRemove) {
  21506. var index = this.multiMaterials.indexOf(toRemove);
  21507. if (index !== -1) {
  21508. this.multiMaterials.splice(index, 1);
  21509. }
  21510. return index;
  21511. };
  21512. ;
  21513. Scene.prototype.removeMaterial = function (toRemove) {
  21514. var index = this.materials.indexOf(toRemove);
  21515. if (index !== -1) {
  21516. this.materials.splice(index, 1);
  21517. }
  21518. return index;
  21519. };
  21520. ;
  21521. Scene.prototype.removeLensFlareSystem = function (toRemove) {
  21522. var index = this.lensFlareSystems.indexOf(toRemove);
  21523. if (index !== -1) {
  21524. this.lensFlareSystems.splice(index, 1);
  21525. }
  21526. return index;
  21527. };
  21528. ;
  21529. Scene.prototype.removeActionManager = function (toRemove) {
  21530. var index = this._actionManagers.indexOf(toRemove);
  21531. if (index !== -1) {
  21532. this._actionManagers.splice(index, 1);
  21533. }
  21534. return index;
  21535. };
  21536. ;
  21537. Scene.prototype.addLight = function (newLight) {
  21538. this.lights.push(newLight);
  21539. this.sortLightsByPriority();
  21540. // Add light to all meshes (To support if the light is removed and then readded)
  21541. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  21542. var mesh = _a[_i];
  21543. if (mesh._lightSources.indexOf(newLight) === -1) {
  21544. mesh._lightSources.push(newLight);
  21545. mesh._resyncLightSources();
  21546. }
  21547. }
  21548. this.onNewLightAddedObservable.notifyObservers(newLight);
  21549. };
  21550. Scene.prototype.sortLightsByPriority = function () {
  21551. if (this.requireLightSorting) {
  21552. this.lights.sort(BABYLON.Light.compareLightsPriority);
  21553. }
  21554. };
  21555. Scene.prototype.addCamera = function (newCamera) {
  21556. this.cameras.push(newCamera);
  21557. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  21558. };
  21559. Scene.prototype.addSkeleton = function (newSkeleton) {
  21560. this.skeletons.push(newSkeleton);
  21561. };
  21562. Scene.prototype.addParticleSystem = function (newParticleSystem) {
  21563. this.particleSystems.push(newParticleSystem);
  21564. };
  21565. Scene.prototype.addAnimation = function (newAnimation) {
  21566. this.animations.push(newAnimation);
  21567. };
  21568. Scene.prototype.addMultiMaterial = function (newMultiMaterial) {
  21569. this.multiMaterials.push(newMultiMaterial);
  21570. };
  21571. Scene.prototype.addMaterial = function (newMaterial) {
  21572. this.materials.push(newMaterial);
  21573. };
  21574. Scene.prototype.addMorphTargetManager = function (newMorphTargetManager) {
  21575. this.morphTargetManagers.push(newMorphTargetManager);
  21576. };
  21577. Scene.prototype.addGeometry = function (newGeometrie) {
  21578. this._geometries.push(newGeometrie);
  21579. };
  21580. Scene.prototype.addLensFlareSystem = function (newLensFlareSystem) {
  21581. this.lensFlareSystems.push(newLensFlareSystem);
  21582. };
  21583. Scene.prototype.addActionManager = function (newActionManager) {
  21584. this._actionManagers.push(newActionManager);
  21585. };
  21586. /**
  21587. * Switch active camera
  21588. * @param {Camera} newCamera - new active camera
  21589. * @param {boolean} attachControl - call attachControl for the new active camera (default: true)
  21590. */
  21591. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  21592. if (attachControl === void 0) { attachControl = true; }
  21593. var canvas = this._engine.getRenderingCanvas();
  21594. if (!canvas) {
  21595. return;
  21596. }
  21597. if (this.activeCamera) {
  21598. this.activeCamera.detachControl(canvas);
  21599. }
  21600. this.activeCamera = newCamera;
  21601. if (attachControl) {
  21602. newCamera.attachControl(canvas);
  21603. }
  21604. };
  21605. /**
  21606. * sets the active camera of the scene using its ID
  21607. * @param {string} id - the camera's ID
  21608. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  21609. * @see activeCamera
  21610. */
  21611. Scene.prototype.setActiveCameraByID = function (id) {
  21612. var camera = this.getCameraByID(id);
  21613. if (camera) {
  21614. this.activeCamera = camera;
  21615. return camera;
  21616. }
  21617. return null;
  21618. };
  21619. /**
  21620. * sets the active camera of the scene using its name
  21621. * @param {string} name - the camera's name
  21622. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  21623. * @see activeCamera
  21624. */
  21625. Scene.prototype.setActiveCameraByName = function (name) {
  21626. var camera = this.getCameraByName(name);
  21627. if (camera) {
  21628. this.activeCamera = camera;
  21629. return camera;
  21630. }
  21631. return null;
  21632. };
  21633. /**
  21634. * get an animation group using its name
  21635. * @param {string} the material's name
  21636. * @return {BABYLON.AnimationGroup|null} the animation group or null if none found.
  21637. */
  21638. Scene.prototype.getAnimationGroupByName = function (name) {
  21639. for (var index = 0; index < this.animationGroups.length; index++) {
  21640. if (this.animationGroups[index].name === name) {
  21641. return this.animationGroups[index];
  21642. }
  21643. }
  21644. return null;
  21645. };
  21646. /**
  21647. * get a material using its id
  21648. * @param {string} the material's ID
  21649. * @return {BABYLON.Material|null} the material or null if none found.
  21650. */
  21651. Scene.prototype.getMaterialByID = function (id) {
  21652. for (var index = 0; index < this.materials.length; index++) {
  21653. if (this.materials[index].id === id) {
  21654. return this.materials[index];
  21655. }
  21656. }
  21657. return null;
  21658. };
  21659. /**
  21660. * get a material using its name
  21661. * @param {string} the material's name
  21662. * @return {BABYLON.Material|null} the material or null if none found.
  21663. */
  21664. Scene.prototype.getMaterialByName = function (name) {
  21665. for (var index = 0; index < this.materials.length; index++) {
  21666. if (this.materials[index].name === name) {
  21667. return this.materials[index];
  21668. }
  21669. }
  21670. return null;
  21671. };
  21672. Scene.prototype.getLensFlareSystemByName = function (name) {
  21673. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  21674. if (this.lensFlareSystems[index].name === name) {
  21675. return this.lensFlareSystems[index];
  21676. }
  21677. }
  21678. return null;
  21679. };
  21680. Scene.prototype.getLensFlareSystemByID = function (id) {
  21681. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  21682. if (this.lensFlareSystems[index].id === id) {
  21683. return this.lensFlareSystems[index];
  21684. }
  21685. }
  21686. return null;
  21687. };
  21688. Scene.prototype.getCameraByID = function (id) {
  21689. for (var index = 0; index < this.cameras.length; index++) {
  21690. if (this.cameras[index].id === id) {
  21691. return this.cameras[index];
  21692. }
  21693. }
  21694. return null;
  21695. };
  21696. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  21697. for (var index = 0; index < this.cameras.length; index++) {
  21698. if (this.cameras[index].uniqueId === uniqueId) {
  21699. return this.cameras[index];
  21700. }
  21701. }
  21702. return null;
  21703. };
  21704. /**
  21705. * get a camera using its name
  21706. * @param {string} the camera's name
  21707. * @return {BABYLON.Camera|null} the camera or null if none found.
  21708. */
  21709. Scene.prototype.getCameraByName = function (name) {
  21710. for (var index = 0; index < this.cameras.length; index++) {
  21711. if (this.cameras[index].name === name) {
  21712. return this.cameras[index];
  21713. }
  21714. }
  21715. return null;
  21716. };
  21717. /**
  21718. * get a bone using its id
  21719. * @param {string} the bone's id
  21720. * @return {BABYLON.Bone|null} the bone or null if not found
  21721. */
  21722. Scene.prototype.getBoneByID = function (id) {
  21723. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  21724. var skeleton = this.skeletons[skeletonIndex];
  21725. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  21726. if (skeleton.bones[boneIndex].id === id) {
  21727. return skeleton.bones[boneIndex];
  21728. }
  21729. }
  21730. }
  21731. return null;
  21732. };
  21733. /**
  21734. * get a bone using its id
  21735. * @param {string} the bone's name
  21736. * @return {BABYLON.Bone|null} the bone or null if not found
  21737. */
  21738. Scene.prototype.getBoneByName = function (name) {
  21739. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  21740. var skeleton = this.skeletons[skeletonIndex];
  21741. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  21742. if (skeleton.bones[boneIndex].name === name) {
  21743. return skeleton.bones[boneIndex];
  21744. }
  21745. }
  21746. }
  21747. return null;
  21748. };
  21749. /**
  21750. * get a light node using its name
  21751. * @param {string} the light's name
  21752. * @return {BABYLON.Light|null} the light or null if none found.
  21753. */
  21754. Scene.prototype.getLightByName = function (name) {
  21755. for (var index = 0; index < this.lights.length; index++) {
  21756. if (this.lights[index].name === name) {
  21757. return this.lights[index];
  21758. }
  21759. }
  21760. return null;
  21761. };
  21762. /**
  21763. * get a light node using its ID
  21764. * @param {string} the light's id
  21765. * @return {BABYLON.Light|null} the light or null if none found.
  21766. */
  21767. Scene.prototype.getLightByID = function (id) {
  21768. for (var index = 0; index < this.lights.length; index++) {
  21769. if (this.lights[index].id === id) {
  21770. return this.lights[index];
  21771. }
  21772. }
  21773. return null;
  21774. };
  21775. /**
  21776. * get a light node using its scene-generated unique ID
  21777. * @param {number} the light's unique id
  21778. * @return {BABYLON.Light|null} the light or null if none found.
  21779. */
  21780. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  21781. for (var index = 0; index < this.lights.length; index++) {
  21782. if (this.lights[index].uniqueId === uniqueId) {
  21783. return this.lights[index];
  21784. }
  21785. }
  21786. return null;
  21787. };
  21788. /**
  21789. * get a particle system by id
  21790. * @param id {number} the particle system id
  21791. * @return {BABYLON.IParticleSystem|null} the corresponding system or null if none found.
  21792. */
  21793. Scene.prototype.getParticleSystemByID = function (id) {
  21794. for (var index = 0; index < this.particleSystems.length; index++) {
  21795. if (this.particleSystems[index].id === id) {
  21796. return this.particleSystems[index];
  21797. }
  21798. }
  21799. return null;
  21800. };
  21801. /**
  21802. * get a geometry using its ID
  21803. * @param {string} the geometry's id
  21804. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  21805. */
  21806. Scene.prototype.getGeometryByID = function (id) {
  21807. for (var index = 0; index < this._geometries.length; index++) {
  21808. if (this._geometries[index].id === id) {
  21809. return this._geometries[index];
  21810. }
  21811. }
  21812. return null;
  21813. };
  21814. /**
  21815. * add a new geometry to this scene.
  21816. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  21817. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  21818. * @return {boolean} was the geometry added or not
  21819. */
  21820. Scene.prototype.pushGeometry = function (geometry, force) {
  21821. if (!force && this.getGeometryByID(geometry.id)) {
  21822. return false;
  21823. }
  21824. this._geometries.push(geometry);
  21825. //notify the collision coordinator
  21826. if (this.collisionCoordinator) {
  21827. this.collisionCoordinator.onGeometryAdded(geometry);
  21828. }
  21829. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  21830. return true;
  21831. };
  21832. /**
  21833. * Removes an existing geometry
  21834. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  21835. * @return {boolean} was the geometry removed or not
  21836. */
  21837. Scene.prototype.removeGeometry = function (geometry) {
  21838. var index = this._geometries.indexOf(geometry);
  21839. if (index > -1) {
  21840. this._geometries.splice(index, 1);
  21841. //notify the collision coordinator
  21842. if (this.collisionCoordinator) {
  21843. this.collisionCoordinator.onGeometryDeleted(geometry);
  21844. }
  21845. this.onGeometryRemovedObservable.notifyObservers(geometry);
  21846. return true;
  21847. }
  21848. return false;
  21849. };
  21850. Scene.prototype.getGeometries = function () {
  21851. return this._geometries;
  21852. };
  21853. /**
  21854. * Get the first added mesh found of a given ID
  21855. * @param {string} id - the id to search for
  21856. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  21857. */
  21858. Scene.prototype.getMeshByID = function (id) {
  21859. for (var index = 0; index < this.meshes.length; index++) {
  21860. if (this.meshes[index].id === id) {
  21861. return this.meshes[index];
  21862. }
  21863. }
  21864. return null;
  21865. };
  21866. Scene.prototype.getMeshesByID = function (id) {
  21867. return this.meshes.filter(function (m) {
  21868. return m.id === id;
  21869. });
  21870. };
  21871. /**
  21872. * Get the first added transform node found of a given ID
  21873. * @param {string} id - the id to search for
  21874. * @return {BABYLON.TransformNode|null} the transform node found or null if not found at all.
  21875. */
  21876. Scene.prototype.getTransformNodeByID = function (id) {
  21877. for (var index = 0; index < this.transformNodes.length; index++) {
  21878. if (this.transformNodes[index].id === id) {
  21879. return this.transformNodes[index];
  21880. }
  21881. }
  21882. return null;
  21883. };
  21884. Scene.prototype.getTransformNodesByID = function (id) {
  21885. return this.transformNodes.filter(function (m) {
  21886. return m.id === id;
  21887. });
  21888. };
  21889. /**
  21890. * Get a mesh with its auto-generated unique id
  21891. * @param {number} uniqueId - the unique id to search for
  21892. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  21893. */
  21894. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  21895. for (var index = 0; index < this.meshes.length; index++) {
  21896. if (this.meshes[index].uniqueId === uniqueId) {
  21897. return this.meshes[index];
  21898. }
  21899. }
  21900. return null;
  21901. };
  21902. /**
  21903. * Get a the last added mesh found of a given ID
  21904. * @param {string} id - the id to search for
  21905. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  21906. */
  21907. Scene.prototype.getLastMeshByID = function (id) {
  21908. for (var index = this.meshes.length - 1; index >= 0; index--) {
  21909. if (this.meshes[index].id === id) {
  21910. return this.meshes[index];
  21911. }
  21912. }
  21913. return null;
  21914. };
  21915. /**
  21916. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  21917. * @param {string} id - the id to search for
  21918. * @return {BABYLON.Node|null} the node found or null if not found at all.
  21919. */
  21920. Scene.prototype.getLastEntryByID = function (id) {
  21921. var index;
  21922. for (index = this.meshes.length - 1; index >= 0; index--) {
  21923. if (this.meshes[index].id === id) {
  21924. return this.meshes[index];
  21925. }
  21926. }
  21927. for (index = this.transformNodes.length - 1; index >= 0; index--) {
  21928. if (this.transformNodes[index].id === id) {
  21929. return this.transformNodes[index];
  21930. }
  21931. }
  21932. for (index = this.cameras.length - 1; index >= 0; index--) {
  21933. if (this.cameras[index].id === id) {
  21934. return this.cameras[index];
  21935. }
  21936. }
  21937. for (index = this.lights.length - 1; index >= 0; index--) {
  21938. if (this.lights[index].id === id) {
  21939. return this.lights[index];
  21940. }
  21941. }
  21942. return null;
  21943. };
  21944. Scene.prototype.getNodeByID = function (id) {
  21945. var mesh = this.getMeshByID(id);
  21946. if (mesh) {
  21947. return mesh;
  21948. }
  21949. var light = this.getLightByID(id);
  21950. if (light) {
  21951. return light;
  21952. }
  21953. var camera = this.getCameraByID(id);
  21954. if (camera) {
  21955. return camera;
  21956. }
  21957. var bone = this.getBoneByID(id);
  21958. return bone;
  21959. };
  21960. Scene.prototype.getNodeByName = function (name) {
  21961. var mesh = this.getMeshByName(name);
  21962. if (mesh) {
  21963. return mesh;
  21964. }
  21965. var light = this.getLightByName(name);
  21966. if (light) {
  21967. return light;
  21968. }
  21969. var camera = this.getCameraByName(name);
  21970. if (camera) {
  21971. return camera;
  21972. }
  21973. var bone = this.getBoneByName(name);
  21974. return bone;
  21975. };
  21976. Scene.prototype.getMeshByName = function (name) {
  21977. for (var index = 0; index < this.meshes.length; index++) {
  21978. if (this.meshes[index].name === name) {
  21979. return this.meshes[index];
  21980. }
  21981. }
  21982. return null;
  21983. };
  21984. Scene.prototype.getTransformNodeByName = function (name) {
  21985. for (var index = 0; index < this.transformNodes.length; index++) {
  21986. if (this.transformNodes[index].name === name) {
  21987. return this.transformNodes[index];
  21988. }
  21989. }
  21990. return null;
  21991. };
  21992. Scene.prototype.getSoundByName = function (name) {
  21993. var index;
  21994. if (BABYLON.AudioEngine) {
  21995. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  21996. if (this.mainSoundTrack.soundCollection[index].name === name) {
  21997. return this.mainSoundTrack.soundCollection[index];
  21998. }
  21999. }
  22000. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  22001. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  22002. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  22003. return this.soundTracks[sdIndex].soundCollection[index];
  22004. }
  22005. }
  22006. }
  22007. }
  22008. return null;
  22009. };
  22010. Scene.prototype.getLastSkeletonByID = function (id) {
  22011. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  22012. if (this.skeletons[index].id === id) {
  22013. return this.skeletons[index];
  22014. }
  22015. }
  22016. return null;
  22017. };
  22018. Scene.prototype.getSkeletonById = function (id) {
  22019. for (var index = 0; index < this.skeletons.length; index++) {
  22020. if (this.skeletons[index].id === id) {
  22021. return this.skeletons[index];
  22022. }
  22023. }
  22024. return null;
  22025. };
  22026. Scene.prototype.getSkeletonByName = function (name) {
  22027. for (var index = 0; index < this.skeletons.length; index++) {
  22028. if (this.skeletons[index].name === name) {
  22029. return this.skeletons[index];
  22030. }
  22031. }
  22032. return null;
  22033. };
  22034. Scene.prototype.getMorphTargetManagerById = function (id) {
  22035. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  22036. if (this.morphTargetManagers[index].uniqueId === id) {
  22037. return this.morphTargetManagers[index];
  22038. }
  22039. }
  22040. return null;
  22041. };
  22042. Scene.prototype.isActiveMesh = function (mesh) {
  22043. return (this._activeMeshes.indexOf(mesh) !== -1);
  22044. };
  22045. /**
  22046. * Return a the first highlight layer of the scene with a given name.
  22047. * @param name The name of the highlight layer to look for.
  22048. * @return The highlight layer if found otherwise null.
  22049. */
  22050. Scene.prototype.getHighlightLayerByName = function (name) {
  22051. for (var index = 0; index < this.highlightLayers.length; index++) {
  22052. if (this.highlightLayers[index].name === name) {
  22053. return this.highlightLayers[index];
  22054. }
  22055. }
  22056. return null;
  22057. };
  22058. Object.defineProperty(Scene.prototype, "uid", {
  22059. /**
  22060. * Return a unique id as a string which can serve as an identifier for the scene
  22061. */
  22062. get: function () {
  22063. if (!this._uid) {
  22064. this._uid = BABYLON.Tools.RandomId();
  22065. }
  22066. return this._uid;
  22067. },
  22068. enumerable: true,
  22069. configurable: true
  22070. });
  22071. /**
  22072. * Add an externaly attached data from its key.
  22073. * This method call will fail and return false, if such key already exists.
  22074. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  22075. * @param key the unique key that identifies the data
  22076. * @param data the data object to associate to the key for this Engine instance
  22077. * @return true if no such key were already present and the data was added successfully, false otherwise
  22078. */
  22079. Scene.prototype.addExternalData = function (key, data) {
  22080. if (!this._externalData) {
  22081. this._externalData = new BABYLON.StringDictionary();
  22082. }
  22083. return this._externalData.add(key, data);
  22084. };
  22085. /**
  22086. * Get an externaly attached data from its key
  22087. * @param key the unique key that identifies the data
  22088. * @return the associated data, if present (can be null), or undefined if not present
  22089. */
  22090. Scene.prototype.getExternalData = function (key) {
  22091. if (!this._externalData) {
  22092. return null;
  22093. }
  22094. return this._externalData.get(key);
  22095. };
  22096. /**
  22097. * Get an externaly attached data from its key, create it using a factory if it's not already present
  22098. * @param key the unique key that identifies the data
  22099. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  22100. * @return the associated data, can be null if the factory returned null.
  22101. */
  22102. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  22103. if (!this._externalData) {
  22104. this._externalData = new BABYLON.StringDictionary();
  22105. }
  22106. return this._externalData.getOrAddWithFactory(key, factory);
  22107. };
  22108. /**
  22109. * Remove an externaly attached data from the Engine instance
  22110. * @param key the unique key that identifies the data
  22111. * @return true if the data was successfully removed, false if it doesn't exist
  22112. */
  22113. Scene.prototype.removeExternalData = function (key) {
  22114. return this._externalData.remove(key);
  22115. };
  22116. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  22117. if (this.dispatchAllSubMeshesOfActiveMeshes || mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  22118. if (mesh.showSubMeshesBoundingBox) {
  22119. var boundingInfo = subMesh.getBoundingInfo();
  22120. if (boundingInfo !== null && boundingInfo !== undefined) {
  22121. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  22122. }
  22123. }
  22124. var material = subMesh.getMaterial();
  22125. if (material !== null && material !== undefined) {
  22126. // Render targets
  22127. if (material.getRenderTargetTextures !== undefined) {
  22128. if (this._processedMaterials.indexOf(material) === -1) {
  22129. this._processedMaterials.push(material);
  22130. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  22131. }
  22132. }
  22133. // Dispatch
  22134. this._activeIndices.addCount(subMesh.indexCount, false);
  22135. this._renderingManager.dispatch(subMesh, mesh, material);
  22136. }
  22137. }
  22138. };
  22139. Scene.prototype._isInIntermediateRendering = function () {
  22140. return this._intermediateRendering;
  22141. };
  22142. Scene.prototype.setActiveMeshCandidateProvider = function (provider) {
  22143. this._activeMeshCandidateProvider = provider;
  22144. };
  22145. Scene.prototype.getActiveMeshCandidateProvider = function () {
  22146. return this._activeMeshCandidateProvider;
  22147. };
  22148. /**
  22149. * Use this function to stop evaluating active meshes. The current list will be keep alive between frames
  22150. */
  22151. Scene.prototype.freezeActiveMeshes = function () {
  22152. this._evaluateActiveMeshes();
  22153. this._activeMeshesFrozen = true;
  22154. return this;
  22155. };
  22156. /**
  22157. * Use this function to restart evaluating active meshes on every frame
  22158. */
  22159. Scene.prototype.unfreezeActiveMeshes = function () {
  22160. this._activeMeshesFrozen = false;
  22161. return this;
  22162. };
  22163. Scene.prototype._evaluateActiveMeshes = function () {
  22164. if (this._activeMeshesFrozen && this._activeMeshes.length) {
  22165. return;
  22166. }
  22167. if (!this.activeCamera) {
  22168. return;
  22169. }
  22170. this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this);
  22171. this.activeCamera._activeMeshes.reset();
  22172. this._activeMeshes.reset();
  22173. this._renderingManager.reset();
  22174. this._processedMaterials.reset();
  22175. this._activeParticleSystems.reset();
  22176. this._activeSkeletons.reset();
  22177. this._softwareSkinnedMeshes.reset();
  22178. if (this._boundingBoxRenderer) {
  22179. this._boundingBoxRenderer.reset();
  22180. }
  22181. // Meshes
  22182. var meshes;
  22183. var len;
  22184. var checkIsEnabled = true;
  22185. // Determine mesh candidates
  22186. if (this._activeMeshCandidateProvider !== undefined) {
  22187. // Use _activeMeshCandidateProvider
  22188. meshes = this._activeMeshCandidateProvider.getMeshes(this);
  22189. checkIsEnabled = this._activeMeshCandidateProvider.checksIsEnabled === false;
  22190. if (meshes !== undefined) {
  22191. len = meshes.length;
  22192. }
  22193. else {
  22194. len = 0;
  22195. }
  22196. }
  22197. else if (this._selectionOctree !== undefined) {
  22198. // Octree
  22199. var selection = this._selectionOctree.select(this._frustumPlanes);
  22200. meshes = selection.data;
  22201. len = selection.length;
  22202. }
  22203. else {
  22204. // Full scene traversal
  22205. len = this.meshes.length;
  22206. meshes = this.meshes;
  22207. }
  22208. // Check each mesh
  22209. for (var meshIndex = 0, mesh, meshLOD; meshIndex < len; meshIndex++) {
  22210. mesh = meshes[meshIndex];
  22211. if (mesh.isBlocked) {
  22212. continue;
  22213. }
  22214. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  22215. if (!mesh.isReady() || (checkIsEnabled && !mesh.isEnabled())) {
  22216. continue;
  22217. }
  22218. mesh.computeWorldMatrix();
  22219. // Intersections
  22220. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  22221. this._meshesForIntersections.pushNoDuplicate(mesh);
  22222. }
  22223. // Switch to current LOD
  22224. meshLOD = mesh.getLOD(this.activeCamera);
  22225. if (meshLOD === undefined || meshLOD === null) {
  22226. continue;
  22227. }
  22228. mesh._preActivate();
  22229. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  22230. this._activeMeshes.push(mesh);
  22231. this.activeCamera._activeMeshes.push(mesh);
  22232. mesh._activate(this._renderId);
  22233. if (meshLOD !== mesh) {
  22234. meshLOD._activate(this._renderId);
  22235. }
  22236. this._activeMesh(mesh, meshLOD);
  22237. }
  22238. }
  22239. this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this);
  22240. // Particle systems
  22241. if (this.particlesEnabled) {
  22242. this.onBeforeParticlesRenderingObservable.notifyObservers(this);
  22243. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  22244. var particleSystem = this.particleSystems[particleIndex];
  22245. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  22246. continue;
  22247. }
  22248. var emitter = particleSystem.emitter;
  22249. if (!emitter.position || emitter.isEnabled()) {
  22250. this._activeParticleSystems.push(particleSystem);
  22251. particleSystem.animate();
  22252. this._renderingManager.dispatchParticles(particleSystem);
  22253. }
  22254. }
  22255. this.onAfterParticlesRenderingObservable.notifyObservers(this);
  22256. }
  22257. };
  22258. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  22259. if (this.skeletonsEnabled && mesh.skeleton !== null && mesh.skeleton !== undefined) {
  22260. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  22261. mesh.skeleton.prepare();
  22262. }
  22263. if (!mesh.computeBonesUsingShaders) {
  22264. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  22265. }
  22266. }
  22267. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  22268. var boundingInfo = sourceMesh.getBoundingInfo();
  22269. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  22270. }
  22271. if (mesh !== undefined && mesh !== null
  22272. && mesh.subMeshes !== undefined && mesh.subMeshes !== null && mesh.subMeshes.length > 0) {
  22273. // Submeshes Octrees
  22274. var len;
  22275. var subMeshes;
  22276. if (mesh.useOctreeForRenderingSelection && mesh._submeshesOctree !== undefined && mesh._submeshesOctree !== null) {
  22277. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  22278. len = intersections.length;
  22279. subMeshes = intersections.data;
  22280. }
  22281. else {
  22282. subMeshes = mesh.subMeshes;
  22283. len = subMeshes.length;
  22284. }
  22285. for (var subIndex = 0, subMesh; subIndex < len; subIndex++) {
  22286. subMesh = subMeshes[subIndex];
  22287. this._evaluateSubMesh(subMesh, mesh);
  22288. }
  22289. }
  22290. };
  22291. Scene.prototype.updateTransformMatrix = function (force) {
  22292. if (!this.activeCamera) {
  22293. return;
  22294. }
  22295. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  22296. };
  22297. Scene.prototype.updateAlternateTransformMatrix = function (alternateCamera) {
  22298. this._setAlternateTransformMatrix(alternateCamera.getViewMatrix(), alternateCamera.getProjectionMatrix());
  22299. };
  22300. Scene.prototype._renderForCamera = function (camera) {
  22301. if (camera && camera._skipRendering) {
  22302. return;
  22303. }
  22304. var engine = this._engine;
  22305. this.activeCamera = camera;
  22306. if (!this.activeCamera)
  22307. throw new Error("Active camera not set");
  22308. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  22309. // Viewport
  22310. engine.setViewport(this.activeCamera.viewport);
  22311. // Camera
  22312. this.resetCachedMaterial();
  22313. this._renderId++;
  22314. this.activeCamera.update();
  22315. this.updateTransformMatrix();
  22316. if (camera._alternateCamera) {
  22317. this.updateAlternateTransformMatrix(camera._alternateCamera);
  22318. this._alternateRendering = true;
  22319. }
  22320. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  22321. // Meshes
  22322. this._evaluateActiveMeshes();
  22323. // Software skinning
  22324. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  22325. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  22326. mesh.applySkeleton(mesh.skeleton);
  22327. }
  22328. // Render targets
  22329. this.OnBeforeRenderTargetsRenderObservable.notifyObservers(this);
  22330. var needsRestoreFrameBuffer = false;
  22331. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  22332. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  22333. }
  22334. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  22335. this._intermediateRendering = true;
  22336. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  22337. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  22338. var renderTarget = this._renderTargets.data[renderIndex];
  22339. if (renderTarget._shouldRender()) {
  22340. this._renderId++;
  22341. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  22342. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  22343. }
  22344. }
  22345. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  22346. this._intermediateRendering = false;
  22347. this._renderId++;
  22348. needsRestoreFrameBuffer = true; // Restore back buffer
  22349. }
  22350. // Render HighlightLayer Texture
  22351. var stencilState = this._engine.getStencilBuffer();
  22352. var renderhighlights = false;
  22353. if (this.renderTargetsEnabled && this.highlightLayers && this.highlightLayers.length > 0) {
  22354. this._intermediateRendering = true;
  22355. for (var i = 0; i < this.highlightLayers.length; i++) {
  22356. var highlightLayer = this.highlightLayers[i];
  22357. if (highlightLayer.shouldRender() &&
  22358. (!highlightLayer.camera ||
  22359. (highlightLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === highlightLayer.camera) ||
  22360. (highlightLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && highlightLayer.camera._rigCameras.indexOf(camera) > -1))) {
  22361. renderhighlights = true;
  22362. var renderTarget = highlightLayer._mainTexture;
  22363. if (renderTarget._shouldRender()) {
  22364. this._renderId++;
  22365. renderTarget.render(false, false);
  22366. needsRestoreFrameBuffer = true;
  22367. }
  22368. }
  22369. }
  22370. this._intermediateRendering = false;
  22371. this._renderId++;
  22372. }
  22373. if (needsRestoreFrameBuffer) {
  22374. engine.restoreDefaultFramebuffer(); // Restore back buffer
  22375. }
  22376. this.OnAfterRenderTargetsRenderObservable.notifyObservers(this);
  22377. // Prepare Frame
  22378. this.postProcessManager._prepareFrame();
  22379. // Backgrounds
  22380. var layerIndex;
  22381. var layer;
  22382. if (this.layers.length) {
  22383. engine.setDepthBuffer(false);
  22384. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  22385. layer = this.layers[layerIndex];
  22386. if (layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  22387. layer.render();
  22388. }
  22389. }
  22390. engine.setDepthBuffer(true);
  22391. }
  22392. // Activate HighlightLayer stencil
  22393. if (renderhighlights) {
  22394. this._engine.setStencilBuffer(true);
  22395. }
  22396. // Render
  22397. this.onBeforeDrawPhaseObservable.notifyObservers(this);
  22398. this._renderingManager.render(null, null, true, true);
  22399. this.onAfterDrawPhaseObservable.notifyObservers(this);
  22400. // Restore HighlightLayer stencil
  22401. if (renderhighlights) {
  22402. this._engine.setStencilBuffer(stencilState);
  22403. }
  22404. // Bounding boxes
  22405. if (this._boundingBoxRenderer) {
  22406. this._boundingBoxRenderer.render();
  22407. }
  22408. // Lens flares
  22409. if (this.lensFlaresEnabled) {
  22410. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  22411. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  22412. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  22413. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  22414. lensFlareSystem.render();
  22415. }
  22416. }
  22417. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  22418. }
  22419. // Foregrounds
  22420. if (this.layers.length) {
  22421. engine.setDepthBuffer(false);
  22422. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  22423. layer = this.layers[layerIndex];
  22424. if (!layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  22425. layer.render();
  22426. }
  22427. }
  22428. engine.setDepthBuffer(true);
  22429. }
  22430. // Highlight Layer
  22431. if (renderhighlights) {
  22432. engine.setDepthBuffer(false);
  22433. for (var i = 0; i < this.highlightLayers.length; i++) {
  22434. if (this.highlightLayers[i].shouldRender()) {
  22435. this.highlightLayers[i].render();
  22436. }
  22437. }
  22438. engine.setDepthBuffer(true);
  22439. }
  22440. // Finalize frame
  22441. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  22442. // Reset some special arrays
  22443. this._renderTargets.reset();
  22444. this._alternateRendering = false;
  22445. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  22446. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  22447. };
  22448. Scene.prototype._processSubCameras = function (camera) {
  22449. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  22450. this._renderForCamera(camera);
  22451. return;
  22452. }
  22453. // Update camera
  22454. if (this.activeCamera) {
  22455. this.activeCamera.update();
  22456. }
  22457. // rig cameras
  22458. for (var index = 0; index < camera._rigCameras.length; index++) {
  22459. this._renderForCamera(camera._rigCameras[index]);
  22460. }
  22461. this.activeCamera = camera;
  22462. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  22463. };
  22464. Scene.prototype._checkIntersections = function () {
  22465. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  22466. var sourceMesh = this._meshesForIntersections.data[index];
  22467. if (!sourceMesh.actionManager) {
  22468. continue;
  22469. }
  22470. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  22471. var action = sourceMesh.actionManager.actions[actionIndex];
  22472. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  22473. var parameters = action.getTriggerParameter();
  22474. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  22475. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  22476. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  22477. if (areIntersecting && currentIntersectionInProgress === -1) {
  22478. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  22479. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  22480. sourceMesh._intersectionsInProgress.push(otherMesh);
  22481. }
  22482. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  22483. sourceMesh._intersectionsInProgress.push(otherMesh);
  22484. }
  22485. }
  22486. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  22487. //They intersected, and now they don't.
  22488. //is this trigger an exit trigger? execute an event.
  22489. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  22490. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  22491. }
  22492. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  22493. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  22494. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  22495. }
  22496. }
  22497. }
  22498. }
  22499. }
  22500. };
  22501. Scene.prototype.render = function () {
  22502. if (this.isDisposed) {
  22503. return;
  22504. }
  22505. this._activeParticles.fetchNewFrame();
  22506. this._totalVertices.fetchNewFrame();
  22507. this._activeIndices.fetchNewFrame();
  22508. this._activeBones.fetchNewFrame();
  22509. this._meshesForIntersections.reset();
  22510. this.resetCachedMaterial();
  22511. this.onBeforeAnimationsObservable.notifyObservers(this);
  22512. // Actions
  22513. if (this.actionManager) {
  22514. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger);
  22515. }
  22516. //Simplification Queue
  22517. if (this.simplificationQueue && !this.simplificationQueue.running) {
  22518. this.simplificationQueue.executeNext();
  22519. }
  22520. if (this._engine.isDeterministicLockStep()) {
  22521. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) + this._timeAccumulator;
  22522. var defaultFPS = (60.0 / 1000.0);
  22523. var defaultFrameTime = 1000 / 60; // frame time in MS
  22524. if (this._physicsEngine) {
  22525. defaultFrameTime = this._physicsEngine.getTimeStep() * 1000;
  22526. }
  22527. var stepsTaken = 0;
  22528. var maxSubSteps = this._engine.getLockstepMaxSteps();
  22529. var internalSteps = Math.floor(deltaTime / (1000 * defaultFPS));
  22530. internalSteps = Math.min(internalSteps, maxSubSteps);
  22531. do {
  22532. this.onBeforeStepObservable.notifyObservers(this);
  22533. // Animations
  22534. this._animationRatio = defaultFrameTime * defaultFPS;
  22535. this._animate();
  22536. this.onAfterAnimationsObservable.notifyObservers(this);
  22537. // Physics
  22538. if (this._physicsEngine) {
  22539. this.onBeforePhysicsObservable.notifyObservers(this);
  22540. this._physicsEngine._step(defaultFrameTime / 1000);
  22541. this.onAfterPhysicsObservable.notifyObservers(this);
  22542. }
  22543. this.onAfterStepObservable.notifyObservers(this);
  22544. this._currentStepId++;
  22545. stepsTaken++;
  22546. deltaTime -= defaultFrameTime;
  22547. } while (deltaTime > 0 && stepsTaken < internalSteps);
  22548. this._timeAccumulator = deltaTime < 0 ? 0 : deltaTime;
  22549. }
  22550. else {
  22551. // Animations
  22552. var deltaTime = this.useConstantAnimationDeltaTime ? 16 : Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  22553. this._animationRatio = deltaTime * (60.0 / 1000.0);
  22554. this._animate();
  22555. this.onAfterAnimationsObservable.notifyObservers(this);
  22556. // Physics
  22557. if (this._physicsEngine) {
  22558. this.onBeforePhysicsObservable.notifyObservers(this);
  22559. this._physicsEngine._step(deltaTime / 1000.0);
  22560. this.onAfterPhysicsObservable.notifyObservers(this);
  22561. }
  22562. }
  22563. // update gamepad manager
  22564. if (this._gamepadManager && this._gamepadManager._isMonitoring) {
  22565. this._gamepadManager._checkGamepadsStatus();
  22566. }
  22567. // Before render
  22568. this.onBeforeRenderObservable.notifyObservers(this);
  22569. // Customs render targets
  22570. this.OnBeforeRenderTargetsRenderObservable.notifyObservers(this);
  22571. var engine = this.getEngine();
  22572. var currentActiveCamera = this.activeCamera;
  22573. if (this.renderTargetsEnabled) {
  22574. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  22575. this._intermediateRendering = true;
  22576. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  22577. var renderTarget = this.customRenderTargets[customIndex];
  22578. if (renderTarget._shouldRender()) {
  22579. this._renderId++;
  22580. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  22581. if (!this.activeCamera)
  22582. throw new Error("Active camera not set");
  22583. // Viewport
  22584. engine.setViewport(this.activeCamera.viewport);
  22585. // Camera
  22586. this.updateTransformMatrix();
  22587. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  22588. }
  22589. }
  22590. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  22591. this._intermediateRendering = false;
  22592. this._renderId++;
  22593. }
  22594. // Restore back buffer
  22595. if (this.customRenderTargets.length > 0) {
  22596. engine.restoreDefaultFramebuffer();
  22597. }
  22598. this.OnAfterRenderTargetsRenderObservable.notifyObservers(this);
  22599. this.activeCamera = currentActiveCamera;
  22600. // Procedural textures
  22601. if (this.proceduralTexturesEnabled) {
  22602. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  22603. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  22604. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  22605. if (proceduralTexture._shouldRender()) {
  22606. proceduralTexture.render();
  22607. }
  22608. }
  22609. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  22610. }
  22611. // Clear
  22612. if (this.autoClearDepthAndStencil || this.autoClear) {
  22613. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  22614. }
  22615. // Shadows
  22616. if (this.shadowsEnabled) {
  22617. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  22618. var light = this.lights[lightIndex];
  22619. var shadowGenerator = light.getShadowGenerator();
  22620. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  22621. var shadowMap = (shadowGenerator.getShadowMap());
  22622. if (this.textures.indexOf(shadowMap) !== -1) {
  22623. this._renderTargets.push(shadowMap);
  22624. }
  22625. }
  22626. }
  22627. }
  22628. // Depth renderer
  22629. if (this._depthRenderer) {
  22630. this._renderTargets.push(this._depthRenderer.getDepthMap());
  22631. }
  22632. // Geometry renderer
  22633. if (this._geometryBufferRenderer) {
  22634. this._renderTargets.push(this._geometryBufferRenderer.getGBuffer());
  22635. }
  22636. // RenderPipeline
  22637. if (this._postProcessRenderPipelineManager) {
  22638. this._postProcessRenderPipelineManager.update();
  22639. }
  22640. // Multi-cameras?
  22641. if (this.activeCameras.length > 0) {
  22642. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  22643. if (cameraIndex > 0) {
  22644. this._engine.clear(null, false, true, true);
  22645. }
  22646. this._processSubCameras(this.activeCameras[cameraIndex]);
  22647. }
  22648. }
  22649. else {
  22650. if (!this.activeCamera) {
  22651. throw new Error("No camera defined");
  22652. }
  22653. this._processSubCameras(this.activeCamera);
  22654. }
  22655. // Intersection checks
  22656. this._checkIntersections();
  22657. // Update the audio listener attached to the camera
  22658. if (BABYLON.AudioEngine) {
  22659. this._updateAudioParameters();
  22660. }
  22661. // After render
  22662. if (this.afterRender) {
  22663. this.afterRender();
  22664. }
  22665. this.onAfterRenderObservable.notifyObservers(this);
  22666. // Cleaning
  22667. for (var index = 0; index < this._toBeDisposed.length; index++) {
  22668. var data = this._toBeDisposed.data[index];
  22669. if (data) {
  22670. data.dispose();
  22671. }
  22672. this._toBeDisposed[index] = null;
  22673. }
  22674. this._toBeDisposed.reset();
  22675. if (this.dumpNextRenderTargets) {
  22676. this.dumpNextRenderTargets = false;
  22677. }
  22678. this._activeBones.addCount(0, true);
  22679. this._activeIndices.addCount(0, true);
  22680. this._activeParticles.addCount(0, true);
  22681. };
  22682. Scene.prototype._updateAudioParameters = function () {
  22683. if (!this.audioEnabled || !this._mainSoundTrack || (this._mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  22684. return;
  22685. }
  22686. var listeningCamera;
  22687. var audioEngine = BABYLON.Engine.audioEngine;
  22688. if (this.activeCameras.length > 0) {
  22689. listeningCamera = this.activeCameras[0];
  22690. }
  22691. else {
  22692. listeningCamera = this.activeCamera;
  22693. }
  22694. if (listeningCamera && audioEngine.canUseWebAudio && audioEngine.audioContext) {
  22695. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  22696. // for VR cameras
  22697. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  22698. listeningCamera = listeningCamera.rigCameras[0];
  22699. }
  22700. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  22701. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  22702. cameraDirection.normalize();
  22703. // To avoid some errors on GearVR
  22704. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  22705. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  22706. }
  22707. var i;
  22708. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  22709. var sound = this.mainSoundTrack.soundCollection[i];
  22710. if (sound.useCustomAttenuation) {
  22711. sound.updateDistanceFromListener();
  22712. }
  22713. }
  22714. for (i = 0; i < this.soundTracks.length; i++) {
  22715. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  22716. sound = this.soundTracks[i].soundCollection[j];
  22717. if (sound.useCustomAttenuation) {
  22718. sound.updateDistanceFromListener();
  22719. }
  22720. }
  22721. }
  22722. }
  22723. };
  22724. Object.defineProperty(Scene.prototype, "audioEnabled", {
  22725. // Audio
  22726. get: function () {
  22727. return this._audioEnabled;
  22728. },
  22729. set: function (value) {
  22730. this._audioEnabled = value;
  22731. if (BABYLON.AudioEngine) {
  22732. if (this._audioEnabled) {
  22733. this._enableAudio();
  22734. }
  22735. else {
  22736. this._disableAudio();
  22737. }
  22738. }
  22739. },
  22740. enumerable: true,
  22741. configurable: true
  22742. });
  22743. Scene.prototype._disableAudio = function () {
  22744. var i;
  22745. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  22746. this.mainSoundTrack.soundCollection[i].pause();
  22747. }
  22748. for (i = 0; i < this.soundTracks.length; i++) {
  22749. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  22750. this.soundTracks[i].soundCollection[j].pause();
  22751. }
  22752. }
  22753. };
  22754. Scene.prototype._enableAudio = function () {
  22755. var i;
  22756. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  22757. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  22758. this.mainSoundTrack.soundCollection[i].play();
  22759. }
  22760. }
  22761. for (i = 0; i < this.soundTracks.length; i++) {
  22762. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  22763. if (this.soundTracks[i].soundCollection[j].isPaused) {
  22764. this.soundTracks[i].soundCollection[j].play();
  22765. }
  22766. }
  22767. }
  22768. };
  22769. Object.defineProperty(Scene.prototype, "headphone", {
  22770. get: function () {
  22771. return this._headphone;
  22772. },
  22773. set: function (value) {
  22774. this._headphone = value;
  22775. if (BABYLON.AudioEngine) {
  22776. if (this._headphone) {
  22777. this._switchAudioModeForHeadphones();
  22778. }
  22779. else {
  22780. this._switchAudioModeForNormalSpeakers();
  22781. }
  22782. }
  22783. },
  22784. enumerable: true,
  22785. configurable: true
  22786. });
  22787. Scene.prototype._switchAudioModeForHeadphones = function () {
  22788. this.mainSoundTrack.switchPanningModelToHRTF();
  22789. for (var i = 0; i < this.soundTracks.length; i++) {
  22790. this.soundTracks[i].switchPanningModelToHRTF();
  22791. }
  22792. };
  22793. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  22794. this.mainSoundTrack.switchPanningModelToEqualPower();
  22795. for (var i = 0; i < this.soundTracks.length; i++) {
  22796. this.soundTracks[i].switchPanningModelToEqualPower();
  22797. }
  22798. };
  22799. Scene.prototype.enableDepthRenderer = function () {
  22800. if (this._depthRenderer) {
  22801. return this._depthRenderer;
  22802. }
  22803. this._depthRenderer = new BABYLON.DepthRenderer(this);
  22804. return this._depthRenderer;
  22805. };
  22806. Scene.prototype.disableDepthRenderer = function () {
  22807. if (!this._depthRenderer) {
  22808. return;
  22809. }
  22810. this._depthRenderer.dispose();
  22811. this._depthRenderer = null;
  22812. };
  22813. Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  22814. if (ratio === void 0) { ratio = 1; }
  22815. if (this._geometryBufferRenderer) {
  22816. return this._geometryBufferRenderer;
  22817. }
  22818. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  22819. if (!this._geometryBufferRenderer.isSupported) {
  22820. this._geometryBufferRenderer = null;
  22821. }
  22822. return this._geometryBufferRenderer;
  22823. };
  22824. Scene.prototype.disableGeometryBufferRenderer = function () {
  22825. if (!this._geometryBufferRenderer) {
  22826. return;
  22827. }
  22828. this._geometryBufferRenderer.dispose();
  22829. this._geometryBufferRenderer = null;
  22830. };
  22831. Scene.prototype.freezeMaterials = function () {
  22832. for (var i = 0; i < this.materials.length; i++) {
  22833. this.materials[i].freeze();
  22834. }
  22835. };
  22836. Scene.prototype.unfreezeMaterials = function () {
  22837. for (var i = 0; i < this.materials.length; i++) {
  22838. this.materials[i].unfreeze();
  22839. }
  22840. };
  22841. Scene.prototype.dispose = function () {
  22842. this.beforeRender = null;
  22843. this.afterRender = null;
  22844. this.skeletons = [];
  22845. this.morphTargetManagers = [];
  22846. this.importedMeshesFiles = new Array();
  22847. this.stopAllAnimations();
  22848. this.resetCachedMaterial();
  22849. if (this._depthRenderer) {
  22850. this._depthRenderer.dispose();
  22851. }
  22852. if (this._gamepadManager) {
  22853. this._gamepadManager.dispose();
  22854. this._gamepadManager = null;
  22855. }
  22856. // Smart arrays
  22857. if (this.activeCamera) {
  22858. this.activeCamera._activeMeshes.dispose();
  22859. this.activeCamera = null;
  22860. }
  22861. this._activeMeshes.dispose();
  22862. this._renderingManager.dispose();
  22863. this._processedMaterials.dispose();
  22864. this._activeParticleSystems.dispose();
  22865. this._activeSkeletons.dispose();
  22866. this._softwareSkinnedMeshes.dispose();
  22867. this._renderTargets.dispose();
  22868. if (this._boundingBoxRenderer) {
  22869. this._boundingBoxRenderer.dispose();
  22870. }
  22871. this._meshesForIntersections.dispose();
  22872. this._toBeDisposed.dispose();
  22873. // Abort active requests
  22874. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  22875. var request = _a[_i];
  22876. request.abort();
  22877. }
  22878. // Debug layer
  22879. if (this._debugLayer) {
  22880. this._debugLayer.hide();
  22881. }
  22882. // Events
  22883. this.onDisposeObservable.notifyObservers(this);
  22884. this.onDisposeObservable.clear();
  22885. this.onBeforeRenderObservable.clear();
  22886. this.onAfterRenderObservable.clear();
  22887. this.OnBeforeRenderTargetsRenderObservable.clear();
  22888. this.OnAfterRenderTargetsRenderObservable.clear();
  22889. this.onAfterStepObservable.clear();
  22890. this.onBeforeStepObservable.clear();
  22891. this.onBeforeActiveMeshesEvaluationObservable.clear();
  22892. this.onAfterActiveMeshesEvaluationObservable.clear();
  22893. this.onBeforeParticlesRenderingObservable.clear();
  22894. this.onAfterParticlesRenderingObservable.clear();
  22895. this.onBeforeSpritesRenderingObservable.clear();
  22896. this.onAfterSpritesRenderingObservable.clear();
  22897. this.onBeforeDrawPhaseObservable.clear();
  22898. this.onAfterDrawPhaseObservable.clear();
  22899. this.onBeforePhysicsObservable.clear();
  22900. this.onAfterPhysicsObservable.clear();
  22901. this.onBeforeAnimationsObservable.clear();
  22902. this.onAfterAnimationsObservable.clear();
  22903. this.onDataLoadedObservable.clear();
  22904. this.detachControl();
  22905. // Release sounds & sounds tracks
  22906. if (BABYLON.AudioEngine) {
  22907. this.disposeSounds();
  22908. }
  22909. // VR Helper
  22910. if (this.VRHelper) {
  22911. this.VRHelper.dispose();
  22912. }
  22913. // Detach cameras
  22914. var canvas = this._engine.getRenderingCanvas();
  22915. if (canvas) {
  22916. var index;
  22917. for (index = 0; index < this.cameras.length; index++) {
  22918. this.cameras[index].detachControl(canvas);
  22919. }
  22920. }
  22921. // Release animation groups
  22922. while (this.animationGroups.length) {
  22923. this.animationGroups[0].dispose();
  22924. }
  22925. // Release lights
  22926. while (this.lights.length) {
  22927. this.lights[0].dispose();
  22928. }
  22929. // Release meshes
  22930. while (this.meshes.length) {
  22931. this.meshes[0].dispose(true);
  22932. }
  22933. while (this.transformNodes.length) {
  22934. this.removeTransformNode(this.transformNodes[0]);
  22935. }
  22936. // Release cameras
  22937. while (this.cameras.length) {
  22938. this.cameras[0].dispose();
  22939. }
  22940. // Release materials
  22941. if (this.defaultMaterial) {
  22942. this.defaultMaterial.dispose();
  22943. }
  22944. while (this.multiMaterials.length) {
  22945. this.multiMaterials[0].dispose();
  22946. }
  22947. while (this.materials.length) {
  22948. this.materials[0].dispose();
  22949. }
  22950. // Release particles
  22951. while (this.particleSystems.length) {
  22952. this.particleSystems[0].dispose();
  22953. }
  22954. // Release sprites
  22955. while (this.spriteManagers.length) {
  22956. this.spriteManagers[0].dispose();
  22957. }
  22958. // Release postProcesses
  22959. while (this.postProcesses.length) {
  22960. this.postProcesses[0].dispose();
  22961. }
  22962. // Release layers
  22963. while (this.layers.length) {
  22964. this.layers[0].dispose();
  22965. }
  22966. while (this.highlightLayers.length) {
  22967. this.highlightLayers[0].dispose();
  22968. }
  22969. // Release textures
  22970. while (this.textures.length) {
  22971. this.textures[0].dispose();
  22972. }
  22973. // Release UBO
  22974. this._sceneUbo.dispose();
  22975. if (this._alternateSceneUbo) {
  22976. this._alternateSceneUbo.dispose();
  22977. }
  22978. // Post-processes
  22979. this.postProcessManager.dispose();
  22980. if (this._postProcessRenderPipelineManager) {
  22981. this._postProcessRenderPipelineManager.dispose();
  22982. }
  22983. // Physics
  22984. if (this._physicsEngine) {
  22985. this.disablePhysicsEngine();
  22986. }
  22987. // Remove from engine
  22988. index = this._engine.scenes.indexOf(this);
  22989. if (index > -1) {
  22990. this._engine.scenes.splice(index, 1);
  22991. }
  22992. this._engine.wipeCaches(true);
  22993. this._isDisposed = true;
  22994. };
  22995. Object.defineProperty(Scene.prototype, "isDisposed", {
  22996. get: function () {
  22997. return this._isDisposed;
  22998. },
  22999. enumerable: true,
  23000. configurable: true
  23001. });
  23002. // Release sounds & sounds tracks
  23003. Scene.prototype.disposeSounds = function () {
  23004. if (!this._mainSoundTrack) {
  23005. return;
  23006. }
  23007. this.mainSoundTrack.dispose();
  23008. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  23009. this.soundTracks[scIndex].dispose();
  23010. }
  23011. };
  23012. // Octrees
  23013. Scene.prototype.getWorldExtends = function () {
  23014. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  23015. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  23016. for (var index = 0; index < this.meshes.length; index++) {
  23017. var mesh = this.meshes[index];
  23018. if (!mesh.subMeshes || mesh.subMeshes.length === 0 || mesh.infiniteDistance) {
  23019. continue;
  23020. }
  23021. mesh.computeWorldMatrix(true);
  23022. var boundingInfo = mesh.getBoundingInfo();
  23023. var minBox = boundingInfo.boundingBox.minimumWorld;
  23024. var maxBox = boundingInfo.boundingBox.maximumWorld;
  23025. BABYLON.Tools.CheckExtends(minBox, min, max);
  23026. BABYLON.Tools.CheckExtends(maxBox, min, max);
  23027. }
  23028. return {
  23029. min: min,
  23030. max: max
  23031. };
  23032. };
  23033. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  23034. if (maxCapacity === void 0) { maxCapacity = 64; }
  23035. if (maxDepth === void 0) { maxDepth = 2; }
  23036. if (!this._selectionOctree) {
  23037. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  23038. }
  23039. var worldExtends = this.getWorldExtends();
  23040. // Update octree
  23041. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  23042. return this._selectionOctree;
  23043. };
  23044. // Picking
  23045. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  23046. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  23047. var result = BABYLON.Ray.Zero();
  23048. this.createPickingRayToRef(x, y, world, result, camera, cameraViewSpace);
  23049. return result;
  23050. };
  23051. Scene.prototype.createPickingRayToRef = function (x, y, world, result, camera, cameraViewSpace) {
  23052. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  23053. var engine = this._engine;
  23054. if (!camera) {
  23055. if (!this.activeCamera)
  23056. throw new Error("Active camera not set");
  23057. camera = this.activeCamera;
  23058. }
  23059. var cameraViewport = camera.viewport;
  23060. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  23061. // Moving coordinates to local viewport world
  23062. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  23063. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  23064. result.update(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  23065. return this;
  23066. };
  23067. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  23068. var result = BABYLON.Ray.Zero();
  23069. this.createPickingRayInCameraSpaceToRef(x, y, result, camera);
  23070. return result;
  23071. };
  23072. Scene.prototype.createPickingRayInCameraSpaceToRef = function (x, y, result, camera) {
  23073. if (!BABYLON.PickingInfo) {
  23074. return this;
  23075. }
  23076. var engine = this._engine;
  23077. if (!camera) {
  23078. if (!this.activeCamera)
  23079. throw new Error("Active camera not set");
  23080. camera = this.activeCamera;
  23081. }
  23082. var cameraViewport = camera.viewport;
  23083. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  23084. var identity = BABYLON.Matrix.Identity();
  23085. // Moving coordinates to local viewport world
  23086. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  23087. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  23088. result.update(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  23089. return this;
  23090. };
  23091. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  23092. if (!BABYLON.PickingInfo) {
  23093. return null;
  23094. }
  23095. var pickingInfo = null;
  23096. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  23097. var mesh = this.meshes[meshIndex];
  23098. if (predicate) {
  23099. if (!predicate(mesh)) {
  23100. continue;
  23101. }
  23102. }
  23103. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  23104. continue;
  23105. }
  23106. var world = mesh.getWorldMatrix();
  23107. var ray = rayFunction(world);
  23108. var result = mesh.intersects(ray, fastCheck);
  23109. if (!result || !result.hit)
  23110. continue;
  23111. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  23112. continue;
  23113. pickingInfo = result;
  23114. if (fastCheck) {
  23115. break;
  23116. }
  23117. }
  23118. return pickingInfo || new BABYLON.PickingInfo();
  23119. };
  23120. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  23121. if (!BABYLON.PickingInfo) {
  23122. return null;
  23123. }
  23124. var pickingInfos = new Array();
  23125. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  23126. var mesh = this.meshes[meshIndex];
  23127. if (predicate) {
  23128. if (!predicate(mesh)) {
  23129. continue;
  23130. }
  23131. }
  23132. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  23133. continue;
  23134. }
  23135. var world = mesh.getWorldMatrix();
  23136. var ray = rayFunction(world);
  23137. var result = mesh.intersects(ray, false);
  23138. if (!result || !result.hit)
  23139. continue;
  23140. pickingInfos.push(result);
  23141. }
  23142. return pickingInfos;
  23143. };
  23144. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  23145. if (!BABYLON.PickingInfo) {
  23146. return null;
  23147. }
  23148. var pickingInfo = null;
  23149. if (!camera) {
  23150. if (!this.activeCamera) {
  23151. return null;
  23152. }
  23153. camera = this.activeCamera;
  23154. }
  23155. if (this.spriteManagers.length > 0) {
  23156. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  23157. var spriteManager = this.spriteManagers[spriteIndex];
  23158. if (!spriteManager.isPickable) {
  23159. continue;
  23160. }
  23161. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  23162. if (!result || !result.hit)
  23163. continue;
  23164. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  23165. continue;
  23166. pickingInfo = result;
  23167. if (fastCheck) {
  23168. break;
  23169. }
  23170. }
  23171. }
  23172. return pickingInfo || new BABYLON.PickingInfo();
  23173. };
  23174. /** Launch a ray to try to pick a mesh in the scene
  23175. * @param x position on screen
  23176. * @param y position on screen
  23177. * @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
  23178. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  23179. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  23180. */
  23181. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  23182. var _this = this;
  23183. if (!BABYLON.PickingInfo) {
  23184. return null;
  23185. }
  23186. return this._internalPick(function (world) {
  23187. _this.createPickingRayToRef(x, y, world, _this._tempPickingRay, camera || null);
  23188. return _this._tempPickingRay;
  23189. }, predicate, fastCheck);
  23190. };
  23191. /** Launch a ray to try to pick a sprite in the scene
  23192. * @param x position on screen
  23193. * @param y position on screen
  23194. * @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
  23195. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  23196. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  23197. */
  23198. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  23199. this.createPickingRayInCameraSpaceToRef(x, y, this._tempPickingRay, camera);
  23200. return this._internalPickSprites(this._tempPickingRay, predicate, fastCheck, camera);
  23201. };
  23202. /** Use the given ray to pick a mesh in the scene
  23203. * @param ray The ray to use to pick meshes
  23204. * @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
  23205. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  23206. */
  23207. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  23208. var _this = this;
  23209. return this._internalPick(function (world) {
  23210. if (!_this._pickWithRayInverseMatrix) {
  23211. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  23212. }
  23213. world.invertToRef(_this._pickWithRayInverseMatrix);
  23214. if (!_this._cachedRayForTransform) {
  23215. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  23216. }
  23217. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  23218. return _this._cachedRayForTransform;
  23219. }, predicate, fastCheck);
  23220. };
  23221. /**
  23222. * Launch a ray to try to pick a mesh in the scene
  23223. * @param x X position on screen
  23224. * @param y Y position on screen
  23225. * @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
  23226. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  23227. */
  23228. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  23229. var _this = this;
  23230. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera || null); }, predicate);
  23231. };
  23232. /**
  23233. * Launch a ray to try to pick a mesh in the scene
  23234. * @param ray Ray to use
  23235. * @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
  23236. */
  23237. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  23238. var _this = this;
  23239. return this._internalMultiPick(function (world) {
  23240. if (!_this._pickWithRayInverseMatrix) {
  23241. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  23242. }
  23243. world.invertToRef(_this._pickWithRayInverseMatrix);
  23244. if (!_this._cachedRayForTransform) {
  23245. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  23246. }
  23247. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  23248. return _this._cachedRayForTransform;
  23249. }, predicate);
  23250. };
  23251. Scene.prototype.setPointerOverMesh = function (mesh) {
  23252. if (this._pointerOverMesh === mesh) {
  23253. return;
  23254. }
  23255. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  23256. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  23257. }
  23258. this._pointerOverMesh = mesh;
  23259. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  23260. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  23261. }
  23262. };
  23263. Scene.prototype.getPointerOverMesh = function () {
  23264. return this._pointerOverMesh;
  23265. };
  23266. Scene.prototype.setPointerOverSprite = function (sprite) {
  23267. if (this._pointerOverSprite === sprite) {
  23268. return;
  23269. }
  23270. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  23271. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  23272. }
  23273. this._pointerOverSprite = sprite;
  23274. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  23275. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  23276. }
  23277. };
  23278. Scene.prototype.getPointerOverSprite = function () {
  23279. return this._pointerOverSprite;
  23280. };
  23281. // Physics
  23282. Scene.prototype.getPhysicsEngine = function () {
  23283. return this._physicsEngine;
  23284. };
  23285. /**
  23286. * Enables physics to the current scene
  23287. * @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine
  23288. * @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS.
  23289. * @return {boolean} was the physics engine initialized
  23290. */
  23291. Scene.prototype.enablePhysics = function (gravity, plugin) {
  23292. if (gravity === void 0) { gravity = null; }
  23293. if (this._physicsEngine) {
  23294. return true;
  23295. }
  23296. try {
  23297. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  23298. return true;
  23299. }
  23300. catch (e) {
  23301. BABYLON.Tools.Error(e.message);
  23302. return false;
  23303. }
  23304. };
  23305. Scene.prototype.disablePhysicsEngine = function () {
  23306. if (!this._physicsEngine) {
  23307. return;
  23308. }
  23309. this._physicsEngine.dispose();
  23310. this._physicsEngine = null;
  23311. };
  23312. Scene.prototype.isPhysicsEnabled = function () {
  23313. return this._physicsEngine !== undefined;
  23314. };
  23315. Scene.prototype.deleteCompoundImpostor = function (compound) {
  23316. var mesh = compound.parts[0].mesh;
  23317. if (mesh.physicsImpostor) {
  23318. mesh.physicsImpostor.dispose();
  23319. mesh.physicsImpostor = null;
  23320. }
  23321. };
  23322. // Misc.
  23323. Scene.prototype._rebuildGeometries = function () {
  23324. for (var _i = 0, _a = this._geometries; _i < _a.length; _i++) {
  23325. var geometry = _a[_i];
  23326. geometry._rebuild();
  23327. }
  23328. for (var _b = 0, _c = this.meshes; _b < _c.length; _b++) {
  23329. var mesh = _c[_b];
  23330. mesh._rebuild();
  23331. }
  23332. if (this.postProcessManager) {
  23333. this.postProcessManager._rebuild();
  23334. }
  23335. for (var _d = 0, _e = this.layers; _d < _e.length; _d++) {
  23336. var layer = _e[_d];
  23337. layer._rebuild();
  23338. }
  23339. for (var _f = 0, _g = this.highlightLayers; _f < _g.length; _f++) {
  23340. var highlightLayer = _g[_f];
  23341. highlightLayer._rebuild();
  23342. }
  23343. if (this._boundingBoxRenderer) {
  23344. this._boundingBoxRenderer._rebuild();
  23345. }
  23346. for (var _h = 0, _j = this.particleSystems; _h < _j.length; _h++) {
  23347. var system = _j[_h];
  23348. system.rebuild();
  23349. }
  23350. if (this._postProcessRenderPipelineManager) {
  23351. this._postProcessRenderPipelineManager._rebuild();
  23352. }
  23353. };
  23354. Scene.prototype._rebuildTextures = function () {
  23355. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  23356. var texture = _a[_i];
  23357. texture._rebuild();
  23358. }
  23359. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  23360. };
  23361. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
  23362. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  23363. if (replace === void 0) { replace = false; }
  23364. if (attachCameraControls === void 0) { attachCameraControls = false; }
  23365. // Dispose existing camera or light in replace mode.
  23366. if (replace) {
  23367. if (this.activeCamera) {
  23368. this.activeCamera.dispose();
  23369. this.activeCamera = null;
  23370. }
  23371. if (this.lights) {
  23372. for (var i = 0; i < this.lights.length; i++) {
  23373. this.lights[i].dispose();
  23374. }
  23375. }
  23376. }
  23377. // Light
  23378. if (this.lights.length === 0) {
  23379. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  23380. }
  23381. // Camera
  23382. if (!this.activeCamera) {
  23383. var worldExtends = this.getWorldExtends();
  23384. var worldSize = worldExtends.max.subtract(worldExtends.min);
  23385. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  23386. var camera;
  23387. var radius = worldSize.length() * 1.5;
  23388. if (createArcRotateCamera) {
  23389. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  23390. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  23391. arcRotateCamera.wheelPrecision = 100 / radius;
  23392. camera = arcRotateCamera;
  23393. }
  23394. else {
  23395. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);
  23396. freeCamera.setTarget(worldCenter);
  23397. camera = freeCamera;
  23398. }
  23399. camera.minZ = radius * 0.01;
  23400. camera.maxZ = radius * 1000;
  23401. camera.speed = radius * 0.2;
  23402. this.activeCamera = camera;
  23403. var canvas = this.getEngine().getRenderingCanvas();
  23404. if (attachCameraControls && canvas) {
  23405. camera.attachControl(canvas);
  23406. }
  23407. }
  23408. };
  23409. Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur) {
  23410. if (pbr === void 0) { pbr = false; }
  23411. if (scale === void 0) { scale = 1000; }
  23412. if (blur === void 0) { blur = 0; }
  23413. if (environmentTexture) {
  23414. this.environmentTexture = environmentTexture;
  23415. }
  23416. if (!this.environmentTexture) {
  23417. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  23418. return null;
  23419. }
  23420. // Skybox
  23421. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
  23422. if (pbr) {
  23423. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  23424. hdrSkyboxMaterial.backFaceCulling = false;
  23425. hdrSkyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  23426. if (hdrSkyboxMaterial.reflectionTexture) {
  23427. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  23428. }
  23429. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  23430. hdrSkyboxMaterial.disableLighting = true;
  23431. hdrSkyboxMaterial.twoSidedLighting = true;
  23432. hdrSkybox.infiniteDistance = true;
  23433. hdrSkybox.material = hdrSkyboxMaterial;
  23434. }
  23435. else {
  23436. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  23437. skyboxMaterial.backFaceCulling = false;
  23438. skyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  23439. if (skyboxMaterial.reflectionTexture) {
  23440. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  23441. }
  23442. skyboxMaterial.disableLighting = true;
  23443. hdrSkybox.infiniteDistance = true;
  23444. hdrSkybox.material = skyboxMaterial;
  23445. }
  23446. return hdrSkybox;
  23447. };
  23448. Scene.prototype.createDefaultEnvironment = function (options) {
  23449. if (BABYLON.EnvironmentHelper) {
  23450. return new BABYLON.EnvironmentHelper(options, this);
  23451. }
  23452. return null;
  23453. };
  23454. Scene.prototype.createDefaultVRExperience = function (webVROptions) {
  23455. if (webVROptions === void 0) { webVROptions = {}; }
  23456. return new BABYLON.VRExperienceHelper(this, webVROptions);
  23457. };
  23458. // Tags
  23459. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  23460. if (tagsQuery === undefined) {
  23461. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  23462. return list;
  23463. }
  23464. var listByTags = [];
  23465. forEach = forEach || (function (item) { return; });
  23466. for (var i in list) {
  23467. var item = list[i];
  23468. if (BABYLON.Tags && BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  23469. listByTags.push(item);
  23470. forEach(item);
  23471. }
  23472. }
  23473. return listByTags;
  23474. };
  23475. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  23476. return this._getByTags(this.meshes, tagsQuery, forEach);
  23477. };
  23478. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  23479. return this._getByTags(this.cameras, tagsQuery, forEach);
  23480. };
  23481. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  23482. return this._getByTags(this.lights, tagsQuery, forEach);
  23483. };
  23484. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  23485. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  23486. };
  23487. /**
  23488. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  23489. * This allowed control for front to back rendering or reversly depending of the special needs.
  23490. *
  23491. * @param renderingGroupId The rendering group id corresponding to its index
  23492. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  23493. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  23494. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  23495. */
  23496. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  23497. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  23498. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  23499. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  23500. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  23501. };
  23502. /**
  23503. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  23504. *
  23505. * @param renderingGroupId The rendering group id corresponding to its index
  23506. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  23507. * @param depth Automatically clears depth between groups if true and autoClear is true.
  23508. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  23509. */
  23510. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  23511. if (depth === void 0) { depth = true; }
  23512. if (stencil === void 0) { stencil = true; }
  23513. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  23514. };
  23515. /**
  23516. * Will flag all materials as dirty to trigger new shader compilation
  23517. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  23518. */
  23519. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  23520. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  23521. var material = _a[_i];
  23522. if (predicate && !predicate(material)) {
  23523. continue;
  23524. }
  23525. material.markAsDirty(flag);
  23526. }
  23527. };
  23528. Scene.prototype._loadFile = function (url, onSuccess, onProgress, useDatabase, useArrayBuffer, onError) {
  23529. var _this = this;
  23530. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, useDatabase ? this.database : undefined, useArrayBuffer, onError);
  23531. this._activeRequests.push(request);
  23532. request.onCompleteObservable.add(function (request) {
  23533. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  23534. });
  23535. return request;
  23536. };
  23537. /** @ignore */
  23538. Scene.prototype._loadFileAsync = function (url, useDatabase, useArrayBuffer) {
  23539. var _this = this;
  23540. return new Promise(function (resolve, reject) {
  23541. _this._loadFile(url, function (data) {
  23542. resolve(data);
  23543. }, undefined, useDatabase, useArrayBuffer, function (request, exception) {
  23544. reject(exception);
  23545. });
  23546. });
  23547. };
  23548. // Statics
  23549. Scene._FOGMODE_NONE = 0;
  23550. Scene._FOGMODE_EXP = 1;
  23551. Scene._FOGMODE_EXP2 = 2;
  23552. Scene._FOGMODE_LINEAR = 3;
  23553. Scene._uniqueIdCounter = 0;
  23554. Scene.MinDeltaTime = 1.0;
  23555. Scene.MaxDeltaTime = 1000.0;
  23556. /** The distance in pixel that you have to move to prevent some events */
  23557. Scene.DragMovementThreshold = 10; // in pixels
  23558. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  23559. Scene.LongPressDelay = 500; // in milliseconds
  23560. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  23561. Scene.DoubleClickDelay = 300; // in milliseconds
  23562. /** If you need to check double click without raising a single click at first click, enable this flag */
  23563. Scene.ExclusiveDoubleClickMode = false;
  23564. return Scene;
  23565. }());
  23566. BABYLON.Scene = Scene;
  23567. })(BABYLON || (BABYLON = {}));
  23568. //# sourceMappingURL=babylon.scene.js.map
  23569. var BABYLON;
  23570. (function (BABYLON) {
  23571. /**
  23572. * Set of assets to keep when moving a scene into an asset container.
  23573. */
  23574. var KeepAssets = /** @class */ (function () {
  23575. function KeepAssets() {
  23576. /**
  23577. * Cameras to keep.
  23578. */
  23579. this.cameras = new Array();
  23580. /**
  23581. * Lights to keep.
  23582. */
  23583. this.lights = new Array();
  23584. /**
  23585. * Meshes to keep.
  23586. */
  23587. this.meshes = new Array();
  23588. /**
  23589. * Skeletons to keep.
  23590. */
  23591. this.skeletons = new Array();
  23592. /**
  23593. * ParticleSystems to keep.
  23594. */
  23595. this.particleSystems = new Array();
  23596. /**
  23597. * Animations to keep.
  23598. */
  23599. this.animations = new Array();
  23600. /**
  23601. * MultiMaterials to keep.
  23602. */
  23603. this.multiMaterials = new Array();
  23604. /**
  23605. * Materials to keep.
  23606. */
  23607. this.materials = new Array();
  23608. /**
  23609. * MorphTargetManagers to keep.
  23610. */
  23611. this.morphTargetManagers = new Array();
  23612. /**
  23613. * Geometries to keep.
  23614. */
  23615. this.geometries = new Array();
  23616. /**
  23617. * TransformNodes to keep.
  23618. */
  23619. this.transformNodes = new Array();
  23620. /**
  23621. * LensFlareSystems to keep.
  23622. */
  23623. this.lensFlareSystems = new Array();
  23624. /**
  23625. * ShadowGenerators to keep.
  23626. */
  23627. this.shadowGenerators = new Array();
  23628. /**
  23629. * ActionManagers to keep.
  23630. */
  23631. this.actionManagers = new Array();
  23632. /**
  23633. * Sounds to keep.
  23634. */
  23635. this.sounds = new Array();
  23636. }
  23637. return KeepAssets;
  23638. }());
  23639. BABYLON.KeepAssets = KeepAssets;
  23640. /**
  23641. * Container with a set of assets that can be added or removed from a scene.
  23642. */
  23643. var AssetContainer = /** @class */ (function () {
  23644. /**
  23645. * Instantiates an AssetContainer.
  23646. * @param scene The scene the AssetContainer belongs to.
  23647. */
  23648. function AssetContainer(scene) {
  23649. // Objects
  23650. /**
  23651. * Cameras populated in the container.
  23652. */
  23653. this.cameras = new Array();
  23654. /**
  23655. * Lights populated in the container.
  23656. */
  23657. this.lights = new Array();
  23658. /**
  23659. * Meshes populated in the container.
  23660. */
  23661. this.meshes = new Array();
  23662. /**
  23663. * Skeletons populated in the container.
  23664. */
  23665. this.skeletons = new Array();
  23666. /**
  23667. * ParticleSystems populated in the container.
  23668. */
  23669. this.particleSystems = new Array();
  23670. /**
  23671. * Animations populated in the container.
  23672. */
  23673. this.animations = new Array();
  23674. /**
  23675. * MultiMaterials populated in the container.
  23676. */
  23677. this.multiMaterials = new Array();
  23678. /**
  23679. * Materials populated in the container.
  23680. */
  23681. this.materials = new Array();
  23682. /**
  23683. * MorphTargetManagers populated in the container.
  23684. */
  23685. this.morphTargetManagers = new Array();
  23686. /**
  23687. * Geometries populated in the container.
  23688. */
  23689. this.geometries = new Array();
  23690. /**
  23691. * TransformNodes populated in the container.
  23692. */
  23693. this.transformNodes = new Array();
  23694. /**
  23695. * LensFlareSystems populated in the container.
  23696. */
  23697. this.lensFlareSystems = new Array();
  23698. /**
  23699. * ShadowGenerators populated in the container.
  23700. */
  23701. this.shadowGenerators = new Array();
  23702. /**
  23703. * ActionManagers populated in the container.
  23704. */
  23705. this.actionManagers = new Array();
  23706. /**
  23707. * Sounds populated in the container.
  23708. */
  23709. this.sounds = new Array();
  23710. this.scene = scene;
  23711. }
  23712. /**
  23713. * Adds all the assets from the container to the scene.
  23714. */
  23715. AssetContainer.prototype.addAllToScene = function () {
  23716. var _this = this;
  23717. this.cameras.forEach(function (o) {
  23718. _this.scene.addCamera(o);
  23719. });
  23720. this.lights.forEach(function (o) {
  23721. _this.scene.addLight(o);
  23722. });
  23723. this.meshes.forEach(function (o) {
  23724. _this.scene.addMesh(o);
  23725. });
  23726. this.skeletons.forEach(function (o) {
  23727. _this.scene.addSkeleton(o);
  23728. });
  23729. this.particleSystems.forEach(function (o) {
  23730. _this.scene.addParticleSystem(o);
  23731. });
  23732. this.animations.forEach(function (o) {
  23733. _this.scene.addAnimation(o);
  23734. });
  23735. this.multiMaterials.forEach(function (o) {
  23736. _this.scene.addMultiMaterial(o);
  23737. });
  23738. this.materials.forEach(function (o) {
  23739. _this.scene.addMaterial(o);
  23740. });
  23741. this.morphTargetManagers.forEach(function (o) {
  23742. _this.scene.addMorphTargetManager(o);
  23743. });
  23744. this.geometries.forEach(function (o) {
  23745. _this.scene.addGeometry(o);
  23746. });
  23747. this.transformNodes.forEach(function (o) {
  23748. _this.scene.addTransformNode(o);
  23749. });
  23750. this.lensFlareSystems.forEach(function (o) {
  23751. _this.scene.addLensFlareSystem(o);
  23752. });
  23753. this.actionManagers.forEach(function (o) {
  23754. _this.scene.addActionManager(o);
  23755. });
  23756. this.sounds.forEach(function (o) {
  23757. o.play();
  23758. o.autoplay = true;
  23759. _this.scene.mainSoundTrack.AddSound(o);
  23760. });
  23761. };
  23762. /**
  23763. * Removes all the assets in the container from the scene
  23764. */
  23765. AssetContainer.prototype.removeAllFromScene = function () {
  23766. var _this = this;
  23767. this.cameras.forEach(function (o) {
  23768. _this.scene.removeCamera(o);
  23769. });
  23770. this.lights.forEach(function (o) {
  23771. _this.scene.removeLight(o);
  23772. });
  23773. this.meshes.forEach(function (o) {
  23774. _this.scene.removeMesh(o);
  23775. });
  23776. this.skeletons.forEach(function (o) {
  23777. _this.scene.removeSkeleton(o);
  23778. });
  23779. this.particleSystems.forEach(function (o) {
  23780. _this.scene.removeParticleSystem(o);
  23781. });
  23782. this.animations.forEach(function (o) {
  23783. _this.scene.removeAnimation(o);
  23784. });
  23785. this.multiMaterials.forEach(function (o) {
  23786. _this.scene.removeMultiMaterial(o);
  23787. });
  23788. this.materials.forEach(function (o) {
  23789. _this.scene.removeMaterial(o);
  23790. });
  23791. this.morphTargetManagers.forEach(function (o) {
  23792. _this.scene.removeMorphTargetManager(o);
  23793. });
  23794. this.geometries.forEach(function (o) {
  23795. _this.scene.removeGeometry(o);
  23796. });
  23797. this.transformNodes.forEach(function (o) {
  23798. _this.scene.removeTransformNode(o);
  23799. });
  23800. this.lensFlareSystems.forEach(function (o) {
  23801. _this.scene.removeLensFlareSystem(o);
  23802. });
  23803. this.actionManagers.forEach(function (o) {
  23804. _this.scene.removeActionManager(o);
  23805. });
  23806. this.sounds.forEach(function (o) {
  23807. o.stop();
  23808. o.autoplay = false;
  23809. _this.scene.mainSoundTrack.RemoveSound(o);
  23810. });
  23811. };
  23812. AssetContainer.prototype._moveAssets = function (sourceAssets, targetAssets, keepAssets) {
  23813. for (var _i = 0, sourceAssets_1 = sourceAssets; _i < sourceAssets_1.length; _i++) {
  23814. var asset = sourceAssets_1[_i];
  23815. var move = true;
  23816. for (var _a = 0, keepAssets_1 = keepAssets; _a < keepAssets_1.length; _a++) {
  23817. var keepAsset = keepAssets_1[_a];
  23818. if (asset === keepAsset) {
  23819. move = false;
  23820. break;
  23821. }
  23822. }
  23823. if (move) {
  23824. targetAssets.push(asset);
  23825. }
  23826. }
  23827. };
  23828. /**
  23829. * Removes all the assets contained in the scene and adds them to the container.
  23830. * @param keepAssets Set of assets to keep in the scene. (default: empty)
  23831. */
  23832. AssetContainer.prototype.moveAllFromScene = function (keepAssets) {
  23833. if (keepAssets === undefined) {
  23834. keepAssets = new KeepAssets();
  23835. }
  23836. this._moveAssets(this.scene.cameras, this.cameras, keepAssets.cameras);
  23837. this._moveAssets(this.scene.meshes, this.meshes, keepAssets.meshes);
  23838. this._moveAssets(this.scene.getGeometries(), this.geometries, keepAssets.geometries);
  23839. this._moveAssets(this.scene.materials, this.materials, keepAssets.materials);
  23840. Array.prototype.push.apply(this.actionManagers, this.scene._actionManagers);
  23841. Array.prototype.push.apply(this.animations, this.scene.animations);
  23842. Array.prototype.push.apply(this.lensFlareSystems, this.scene.lensFlareSystems);
  23843. Array.prototype.push.apply(this.lights, this.scene.lights);
  23844. Array.prototype.push.apply(this.morphTargetManagers, this.scene.morphTargetManagers);
  23845. Array.prototype.push.apply(this.multiMaterials, this.scene.multiMaterials);
  23846. Array.prototype.push.apply(this.skeletons, this.scene.skeletons);
  23847. Array.prototype.push.apply(this.particleSystems, this.scene.particleSystems);
  23848. Array.prototype.push.apply(this.sounds, this.scene.mainSoundTrack.soundCollection);
  23849. Array.prototype.push.apply(this.transformNodes, this.scene.transformNodes);
  23850. this.removeAllFromScene();
  23851. };
  23852. return AssetContainer;
  23853. }());
  23854. BABYLON.AssetContainer = AssetContainer;
  23855. })(BABYLON || (BABYLON = {}));
  23856. //# sourceMappingURL=babylon.assetContainer.js.map
  23857. var BABYLON;
  23858. (function (BABYLON) {
  23859. var Buffer = /** @class */ (function () {
  23860. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced) {
  23861. if (instanced === void 0) { instanced = false; }
  23862. if (engine instanceof BABYLON.Mesh) {
  23863. this._engine = engine.getScene().getEngine();
  23864. }
  23865. else {
  23866. this._engine = engine;
  23867. }
  23868. this._updatable = updatable;
  23869. this._data = data;
  23870. this._strideSize = stride;
  23871. if (!postponeInternalCreation) {
  23872. this.create();
  23873. }
  23874. this._instanced = instanced;
  23875. this._instanceDivisor = instanced ? 1 : 0;
  23876. }
  23877. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride) {
  23878. // a lot of these parameters are ignored as they are overriden by the buffer
  23879. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, stride ? stride : this._strideSize, this._instanced, offset, size);
  23880. };
  23881. // Properties
  23882. Buffer.prototype.isUpdatable = function () {
  23883. return this._updatable;
  23884. };
  23885. Buffer.prototype.getData = function () {
  23886. return this._data;
  23887. };
  23888. Buffer.prototype.getBuffer = function () {
  23889. return this._buffer;
  23890. };
  23891. Buffer.prototype.getStrideSize = function () {
  23892. return this._strideSize;
  23893. };
  23894. Buffer.prototype.getIsInstanced = function () {
  23895. return this._instanced;
  23896. };
  23897. Object.defineProperty(Buffer.prototype, "instanceDivisor", {
  23898. get: function () {
  23899. return this._instanceDivisor;
  23900. },
  23901. set: function (value) {
  23902. this._instanceDivisor = value;
  23903. if (value == 0) {
  23904. this._instanced = false;
  23905. }
  23906. else {
  23907. this._instanced = true;
  23908. }
  23909. },
  23910. enumerable: true,
  23911. configurable: true
  23912. });
  23913. // Methods
  23914. Buffer.prototype.create = function (data) {
  23915. if (data === void 0) { data = null; }
  23916. if (!data && this._buffer) {
  23917. return; // nothing to do
  23918. }
  23919. data = data || this._data;
  23920. if (!data) {
  23921. return;
  23922. }
  23923. if (!this._buffer) {
  23924. if (this._updatable) {
  23925. this._buffer = this._engine.createDynamicVertexBuffer(data);
  23926. this._data = data;
  23927. }
  23928. else {
  23929. this._buffer = this._engine.createVertexBuffer(data);
  23930. }
  23931. }
  23932. else if (this._updatable) {
  23933. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  23934. this._data = data;
  23935. }
  23936. };
  23937. Buffer.prototype._rebuild = function () {
  23938. this._buffer = null;
  23939. this.create(this._data);
  23940. };
  23941. Buffer.prototype.update = function (data) {
  23942. this.create(data);
  23943. };
  23944. Buffer.prototype.updateDirectly = function (data, offset, vertexCount) {
  23945. if (!this._buffer) {
  23946. return;
  23947. }
  23948. if (this._updatable) {
  23949. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset, (vertexCount ? vertexCount * this.getStrideSize() : undefined));
  23950. this._data = null;
  23951. }
  23952. };
  23953. Buffer.prototype.dispose = function () {
  23954. if (!this._buffer) {
  23955. return;
  23956. }
  23957. if (this._engine._releaseBuffer(this._buffer)) {
  23958. this._buffer = null;
  23959. }
  23960. };
  23961. return Buffer;
  23962. }());
  23963. BABYLON.Buffer = Buffer;
  23964. })(BABYLON || (BABYLON = {}));
  23965. //# sourceMappingURL=babylon.buffer.js.map
  23966. var BABYLON;
  23967. (function (BABYLON) {
  23968. var VertexBuffer = /** @class */ (function () {
  23969. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size) {
  23970. if (!stride) {
  23971. // Deduce stride from kind
  23972. switch (kind) {
  23973. case VertexBuffer.PositionKind:
  23974. stride = 3;
  23975. break;
  23976. case VertexBuffer.NormalKind:
  23977. stride = 3;
  23978. break;
  23979. case VertexBuffer.UVKind:
  23980. case VertexBuffer.UV2Kind:
  23981. case VertexBuffer.UV3Kind:
  23982. case VertexBuffer.UV4Kind:
  23983. case VertexBuffer.UV5Kind:
  23984. case VertexBuffer.UV6Kind:
  23985. stride = 2;
  23986. break;
  23987. case VertexBuffer.TangentKind:
  23988. case VertexBuffer.ColorKind:
  23989. stride = 4;
  23990. break;
  23991. case VertexBuffer.MatricesIndicesKind:
  23992. case VertexBuffer.MatricesIndicesExtraKind:
  23993. stride = 4;
  23994. break;
  23995. case VertexBuffer.MatricesWeightsKind:
  23996. case VertexBuffer.MatricesWeightsExtraKind:
  23997. default:
  23998. stride = 4;
  23999. break;
  24000. }
  24001. }
  24002. if (data instanceof BABYLON.Buffer) {
  24003. if (!stride) {
  24004. stride = data.getStrideSize();
  24005. }
  24006. this._buffer = data;
  24007. this._ownsBuffer = false;
  24008. }
  24009. else {
  24010. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced);
  24011. this._ownsBuffer = true;
  24012. }
  24013. this._stride = stride;
  24014. this._offset = offset ? offset : 0;
  24015. this._size = size ? size : stride;
  24016. this._kind = kind;
  24017. }
  24018. VertexBuffer.prototype._rebuild = function () {
  24019. if (!this._buffer) {
  24020. return;
  24021. }
  24022. this._buffer._rebuild();
  24023. };
  24024. /**
  24025. * Returns the kind of the VertexBuffer (string).
  24026. */
  24027. VertexBuffer.prototype.getKind = function () {
  24028. return this._kind;
  24029. };
  24030. // Properties
  24031. /**
  24032. * Boolean : is the VertexBuffer updatable ?
  24033. */
  24034. VertexBuffer.prototype.isUpdatable = function () {
  24035. return this._buffer.isUpdatable();
  24036. };
  24037. /**
  24038. * Returns an array of numbers or a Float32Array containing the VertexBuffer data.
  24039. */
  24040. VertexBuffer.prototype.getData = function () {
  24041. return this._buffer.getData();
  24042. };
  24043. /**
  24044. * Returns the WebGLBuffer associated to the VertexBuffer.
  24045. */
  24046. VertexBuffer.prototype.getBuffer = function () {
  24047. return this._buffer.getBuffer();
  24048. };
  24049. /**
  24050. * Returns the stride of the VertexBuffer (integer).
  24051. */
  24052. VertexBuffer.prototype.getStrideSize = function () {
  24053. return this._stride;
  24054. };
  24055. /**
  24056. * Returns the offset (integer).
  24057. */
  24058. VertexBuffer.prototype.getOffset = function () {
  24059. return this._offset;
  24060. };
  24061. /**
  24062. * Returns the VertexBuffer total size (integer).
  24063. */
  24064. VertexBuffer.prototype.getSize = function () {
  24065. return this._size;
  24066. };
  24067. /**
  24068. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  24069. */
  24070. VertexBuffer.prototype.getIsInstanced = function () {
  24071. return this._buffer.getIsInstanced();
  24072. };
  24073. /**
  24074. * Returns the instancing divisor, zero for non-instanced (integer).
  24075. */
  24076. VertexBuffer.prototype.getInstanceDivisor = function () {
  24077. return this._buffer.instanceDivisor;
  24078. };
  24079. // Methods
  24080. /**
  24081. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  24082. * Returns the created WebGLBuffer.
  24083. */
  24084. VertexBuffer.prototype.create = function (data) {
  24085. return this._buffer.create(data);
  24086. };
  24087. /**
  24088. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  24089. * This function will create a new buffer if the current one is not updatable
  24090. * Returns the updated WebGLBuffer.
  24091. */
  24092. VertexBuffer.prototype.update = function (data) {
  24093. return this._buffer.update(data);
  24094. };
  24095. /**
  24096. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  24097. * Returns the directly updated WebGLBuffer.
  24098. */
  24099. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  24100. return this._buffer.updateDirectly(data, offset);
  24101. };
  24102. /**
  24103. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  24104. */
  24105. VertexBuffer.prototype.dispose = function () {
  24106. if (this._ownsBuffer) {
  24107. this._buffer.dispose();
  24108. }
  24109. };
  24110. Object.defineProperty(VertexBuffer, "PositionKind", {
  24111. get: function () {
  24112. return VertexBuffer._PositionKind;
  24113. },
  24114. enumerable: true,
  24115. configurable: true
  24116. });
  24117. Object.defineProperty(VertexBuffer, "NormalKind", {
  24118. get: function () {
  24119. return VertexBuffer._NormalKind;
  24120. },
  24121. enumerable: true,
  24122. configurable: true
  24123. });
  24124. Object.defineProperty(VertexBuffer, "TangentKind", {
  24125. get: function () {
  24126. return VertexBuffer._TangentKind;
  24127. },
  24128. enumerable: true,
  24129. configurable: true
  24130. });
  24131. Object.defineProperty(VertexBuffer, "UVKind", {
  24132. get: function () {
  24133. return VertexBuffer._UVKind;
  24134. },
  24135. enumerable: true,
  24136. configurable: true
  24137. });
  24138. Object.defineProperty(VertexBuffer, "UV2Kind", {
  24139. get: function () {
  24140. return VertexBuffer._UV2Kind;
  24141. },
  24142. enumerable: true,
  24143. configurable: true
  24144. });
  24145. Object.defineProperty(VertexBuffer, "UV3Kind", {
  24146. get: function () {
  24147. return VertexBuffer._UV3Kind;
  24148. },
  24149. enumerable: true,
  24150. configurable: true
  24151. });
  24152. Object.defineProperty(VertexBuffer, "UV4Kind", {
  24153. get: function () {
  24154. return VertexBuffer._UV4Kind;
  24155. },
  24156. enumerable: true,
  24157. configurable: true
  24158. });
  24159. Object.defineProperty(VertexBuffer, "UV5Kind", {
  24160. get: function () {
  24161. return VertexBuffer._UV5Kind;
  24162. },
  24163. enumerable: true,
  24164. configurable: true
  24165. });
  24166. Object.defineProperty(VertexBuffer, "UV6Kind", {
  24167. get: function () {
  24168. return VertexBuffer._UV6Kind;
  24169. },
  24170. enumerable: true,
  24171. configurable: true
  24172. });
  24173. Object.defineProperty(VertexBuffer, "ColorKind", {
  24174. get: function () {
  24175. return VertexBuffer._ColorKind;
  24176. },
  24177. enumerable: true,
  24178. configurable: true
  24179. });
  24180. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  24181. get: function () {
  24182. return VertexBuffer._MatricesIndicesKind;
  24183. },
  24184. enumerable: true,
  24185. configurable: true
  24186. });
  24187. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  24188. get: function () {
  24189. return VertexBuffer._MatricesWeightsKind;
  24190. },
  24191. enumerable: true,
  24192. configurable: true
  24193. });
  24194. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  24195. get: function () {
  24196. return VertexBuffer._MatricesIndicesExtraKind;
  24197. },
  24198. enumerable: true,
  24199. configurable: true
  24200. });
  24201. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  24202. get: function () {
  24203. return VertexBuffer._MatricesWeightsExtraKind;
  24204. },
  24205. enumerable: true,
  24206. configurable: true
  24207. });
  24208. // Enums
  24209. VertexBuffer._PositionKind = "position";
  24210. VertexBuffer._NormalKind = "normal";
  24211. VertexBuffer._TangentKind = "tangent";
  24212. VertexBuffer._UVKind = "uv";
  24213. VertexBuffer._UV2Kind = "uv2";
  24214. VertexBuffer._UV3Kind = "uv3";
  24215. VertexBuffer._UV4Kind = "uv4";
  24216. VertexBuffer._UV5Kind = "uv5";
  24217. VertexBuffer._UV6Kind = "uv6";
  24218. VertexBuffer._ColorKind = "color";
  24219. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  24220. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  24221. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  24222. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  24223. return VertexBuffer;
  24224. }());
  24225. BABYLON.VertexBuffer = VertexBuffer;
  24226. })(BABYLON || (BABYLON = {}));
  24227. //# sourceMappingURL=babylon.vertexBuffer.js.map
  24228. var BABYLON;
  24229. (function (BABYLON) {
  24230. /**
  24231. * Internal class used by the engine to get list of {BABYLON.InternalTexture} already bound to the GL context
  24232. */
  24233. var DummyInternalTextureTracker = /** @class */ (function () {
  24234. function DummyInternalTextureTracker() {
  24235. /**
  24236. * Gets or set the previous tracker in the list
  24237. */
  24238. this.previous = null;
  24239. /**
  24240. * Gets or set the next tracker in the list
  24241. */
  24242. this.next = null;
  24243. }
  24244. return DummyInternalTextureTracker;
  24245. }());
  24246. BABYLON.DummyInternalTextureTracker = DummyInternalTextureTracker;
  24247. })(BABYLON || (BABYLON = {}));
  24248. //# sourceMappingURL=babylon.internalTextureTracker.js.map
  24249. var BABYLON;
  24250. (function (BABYLON) {
  24251. /**
  24252. * Class used to store data associated with WebGL texture data for the engine
  24253. * This class should not be used directly
  24254. */
  24255. var InternalTexture = /** @class */ (function () {
  24256. /**
  24257. * Creates a new InternalTexture
  24258. * @param engine defines the engine to use
  24259. * @param dataSource defines the type of data that will be used
  24260. */
  24261. function InternalTexture(engine, dataSource) {
  24262. /**
  24263. * Observable called when the texture is loaded
  24264. */
  24265. this.onLoadedObservable = new BABYLON.Observable();
  24266. /**
  24267. * Gets or set the previous tracker in the list
  24268. */
  24269. this.previous = null;
  24270. /**
  24271. * Gets or set the next tracker in the list
  24272. */
  24273. this.next = null;
  24274. // Private
  24275. /** @ignore */
  24276. this._initialSlot = -1;
  24277. /** @ignore */
  24278. this._designatedSlot = -1;
  24279. /** @ignore */
  24280. this._dataSource = InternalTexture.DATASOURCE_UNKNOWN;
  24281. /** @ignore */
  24282. this._references = 1;
  24283. this._engine = engine;
  24284. this._dataSource = dataSource;
  24285. this._webGLTexture = engine._createTexture();
  24286. }
  24287. Object.defineProperty(InternalTexture.prototype, "dataSource", {
  24288. /**
  24289. * Gets the data source type of the texture (can be one of the BABYLON.InternalTexture.DATASOURCE_XXXX)
  24290. */
  24291. get: function () {
  24292. return this._dataSource;
  24293. },
  24294. enumerable: true,
  24295. configurable: true
  24296. });
  24297. /**
  24298. * Increments the number of references (ie. the number of {BABYLON.Texture} that point to it)
  24299. */
  24300. InternalTexture.prototype.incrementReferences = function () {
  24301. this._references++;
  24302. };
  24303. /**
  24304. * Change the size of the texture (not the size of the content)
  24305. * @param width defines the new width
  24306. * @param height defines the new height
  24307. * @param depth defines the new depth (1 by default)
  24308. */
  24309. InternalTexture.prototype.updateSize = function (width, height, depth) {
  24310. if (depth === void 0) { depth = 1; }
  24311. this.width = width;
  24312. this.height = height;
  24313. this.depth = depth;
  24314. this.baseWidth = width;
  24315. this.baseHeight = height;
  24316. this.baseDepth = depth;
  24317. this._size = width * height * depth;
  24318. };
  24319. /** @ignore */
  24320. InternalTexture.prototype._rebuild = function () {
  24321. var _this = this;
  24322. var proxy;
  24323. this.isReady = false;
  24324. this._cachedCoordinatesMode = null;
  24325. this._cachedWrapU = null;
  24326. this._cachedWrapV = null;
  24327. this._cachedAnisotropicFilteringLevel = null;
  24328. switch (this._dataSource) {
  24329. case InternalTexture.DATASOURCE_TEMP:
  24330. return;
  24331. case InternalTexture.DATASOURCE_URL:
  24332. proxy = this._engine.createTexture(this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function () {
  24333. _this.isReady = true;
  24334. }, null, this._buffer, undefined, this.format);
  24335. proxy._swapAndDie(this);
  24336. return;
  24337. case InternalTexture.DATASOURCE_RAW:
  24338. proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  24339. proxy._swapAndDie(this);
  24340. this.isReady = true;
  24341. return;
  24342. case InternalTexture.DATASOURCE_RAW3D:
  24343. proxy = this._engine.createRawTexture3D(this._bufferView, this.baseWidth, this.baseHeight, this.baseDepth, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  24344. proxy._swapAndDie(this);
  24345. this.isReady = true;
  24346. return;
  24347. case InternalTexture.DATASOURCE_DYNAMIC:
  24348. proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);
  24349. proxy._swapAndDie(this);
  24350. // The engine will make sure to update content so no need to flag it as isReady = true
  24351. return;
  24352. case InternalTexture.DATASOURCE_RENDERTARGET:
  24353. var options = new BABYLON.RenderTargetCreationOptions();
  24354. options.generateDepthBuffer = this._generateDepthBuffer;
  24355. options.generateMipMaps = this.generateMipMaps;
  24356. options.generateStencilBuffer = this._generateStencilBuffer;
  24357. options.samplingMode = this.samplingMode;
  24358. options.type = this.type;
  24359. if (this.isCube) {
  24360. proxy = this._engine.createRenderTargetCubeTexture(this.width, options);
  24361. }
  24362. else {
  24363. var size = {
  24364. width: this.width,
  24365. height: this.height
  24366. };
  24367. proxy = this._engine.createRenderTargetTexture(size, options);
  24368. }
  24369. proxy._swapAndDie(this);
  24370. this.isReady = true;
  24371. return;
  24372. case InternalTexture.DATASOURCE_CUBE:
  24373. proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function () {
  24374. _this.isReady = true;
  24375. }, null, this.format, this._extension);
  24376. proxy._swapAndDie(this);
  24377. return;
  24378. case InternalTexture.DATASOURCE_CUBERAW:
  24379. proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  24380. proxy._swapAndDie(this);
  24381. this.isReady = true;
  24382. return;
  24383. case InternalTexture.DATASOURCE_CUBEPREFILTERED:
  24384. proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function (proxy) {
  24385. if (proxy) {
  24386. proxy._swapAndDie(_this);
  24387. }
  24388. _this.isReady = true;
  24389. }, null, this.format, this._extension);
  24390. return;
  24391. }
  24392. };
  24393. InternalTexture.prototype._swapAndDie = function (target) {
  24394. target._webGLTexture = this._webGLTexture;
  24395. if (this._framebuffer) {
  24396. target._framebuffer = this._framebuffer;
  24397. }
  24398. if (this._depthStencilBuffer) {
  24399. target._depthStencilBuffer = this._depthStencilBuffer;
  24400. }
  24401. if (this._lodTextureHigh) {
  24402. if (target._lodTextureHigh) {
  24403. target._lodTextureHigh.dispose();
  24404. }
  24405. target._lodTextureHigh = this._lodTextureHigh;
  24406. }
  24407. if (this._lodTextureMid) {
  24408. if (target._lodTextureMid) {
  24409. target._lodTextureMid.dispose();
  24410. }
  24411. target._lodTextureMid = this._lodTextureMid;
  24412. }
  24413. if (this._lodTextureLow) {
  24414. if (target._lodTextureLow) {
  24415. target._lodTextureLow.dispose();
  24416. }
  24417. target._lodTextureLow = this._lodTextureLow;
  24418. }
  24419. var cache = this._engine.getLoadedTexturesCache();
  24420. var index = cache.indexOf(this);
  24421. if (index !== -1) {
  24422. cache.splice(index, 1);
  24423. }
  24424. };
  24425. /**
  24426. * Dispose the current allocated resources
  24427. */
  24428. InternalTexture.prototype.dispose = function () {
  24429. if (!this._webGLTexture) {
  24430. return;
  24431. }
  24432. this._references--;
  24433. if (this._references === 0) {
  24434. this._engine._releaseTexture(this);
  24435. this._webGLTexture = null;
  24436. this.previous = null;
  24437. this.next = null;
  24438. }
  24439. };
  24440. /**
  24441. * The source of the texture data is unknown
  24442. */
  24443. InternalTexture.DATASOURCE_UNKNOWN = 0;
  24444. /**
  24445. * Texture data comes from an URL
  24446. */
  24447. InternalTexture.DATASOURCE_URL = 1;
  24448. /**
  24449. * Texture data is only used for temporary storage
  24450. */
  24451. InternalTexture.DATASOURCE_TEMP = 2;
  24452. /**
  24453. * Texture data comes from raw data (ArrayBuffer)
  24454. */
  24455. InternalTexture.DATASOURCE_RAW = 3;
  24456. /**
  24457. * Texture content is dynamic (video or dynamic texture)
  24458. */
  24459. InternalTexture.DATASOURCE_DYNAMIC = 4;
  24460. /**
  24461. * Texture content is generated by rendering to it
  24462. */
  24463. InternalTexture.DATASOURCE_RENDERTARGET = 5;
  24464. /**
  24465. * Texture content is part of a multi render target process
  24466. */
  24467. InternalTexture.DATASOURCE_MULTIRENDERTARGET = 6;
  24468. /**
  24469. * Texture data comes from a cube data file
  24470. */
  24471. InternalTexture.DATASOURCE_CUBE = 7;
  24472. /**
  24473. * Texture data comes from a raw cube data
  24474. */
  24475. InternalTexture.DATASOURCE_CUBERAW = 8;
  24476. /**
  24477. * Texture data come from a prefiltered cube data file
  24478. */
  24479. InternalTexture.DATASOURCE_CUBEPREFILTERED = 9;
  24480. /**
  24481. * Texture content is raw 3D data
  24482. */
  24483. InternalTexture.DATASOURCE_RAW3D = 10;
  24484. return InternalTexture;
  24485. }());
  24486. BABYLON.InternalTexture = InternalTexture;
  24487. })(BABYLON || (BABYLON = {}));
  24488. //# sourceMappingURL=babylon.internalTexture.js.map
  24489. var BABYLON;
  24490. (function (BABYLON) {
  24491. var BaseTexture = /** @class */ (function () {
  24492. function BaseTexture(scene) {
  24493. this._hasAlpha = false;
  24494. this.getAlphaFromRGB = false;
  24495. this.level = 1;
  24496. this.coordinatesIndex = 0;
  24497. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  24498. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  24499. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  24500. this.wrapR = BABYLON.Texture.WRAP_ADDRESSMODE;
  24501. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  24502. this.isCube = false;
  24503. this.is3D = false;
  24504. this.gammaSpace = true;
  24505. this.invertZ = false;
  24506. this.lodLevelInAlpha = false;
  24507. this.lodGenerationOffset = 0.0;
  24508. this.lodGenerationScale = 0.8;
  24509. this.isRenderTarget = false;
  24510. this.animations = new Array();
  24511. /**
  24512. * An event triggered when the texture is disposed.
  24513. * @type {BABYLON.Observable}
  24514. */
  24515. this.onDisposeObservable = new BABYLON.Observable();
  24516. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  24517. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  24518. if (this._scene) {
  24519. this._scene.textures.push(this);
  24520. }
  24521. this._uid = null;
  24522. }
  24523. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  24524. get: function () {
  24525. return this._hasAlpha;
  24526. },
  24527. set: function (value) {
  24528. if (this._hasAlpha === value) {
  24529. return;
  24530. }
  24531. this._hasAlpha = value;
  24532. if (this._scene) {
  24533. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  24534. }
  24535. },
  24536. enumerable: true,
  24537. configurable: true
  24538. });
  24539. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  24540. get: function () {
  24541. return this._coordinatesMode;
  24542. },
  24543. set: function (value) {
  24544. if (this._coordinatesMode === value) {
  24545. return;
  24546. }
  24547. this._coordinatesMode = value;
  24548. if (this._scene) {
  24549. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  24550. }
  24551. },
  24552. enumerable: true,
  24553. configurable: true
  24554. });
  24555. Object.defineProperty(BaseTexture.prototype, "uid", {
  24556. get: function () {
  24557. if (!this._uid) {
  24558. this._uid = BABYLON.Tools.RandomId();
  24559. }
  24560. return this._uid;
  24561. },
  24562. enumerable: true,
  24563. configurable: true
  24564. });
  24565. BaseTexture.prototype.toString = function () {
  24566. return this.name;
  24567. };
  24568. BaseTexture.prototype.getClassName = function () {
  24569. return "BaseTexture";
  24570. };
  24571. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  24572. set: function (callback) {
  24573. if (this._onDisposeObserver) {
  24574. this.onDisposeObservable.remove(this._onDisposeObserver);
  24575. }
  24576. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  24577. },
  24578. enumerable: true,
  24579. configurable: true
  24580. });
  24581. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  24582. get: function () {
  24583. return true;
  24584. },
  24585. enumerable: true,
  24586. configurable: true
  24587. });
  24588. BaseTexture.prototype.getScene = function () {
  24589. return this._scene;
  24590. };
  24591. BaseTexture.prototype.getTextureMatrix = function () {
  24592. return BABYLON.Matrix.IdentityReadOnly;
  24593. };
  24594. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  24595. return BABYLON.Matrix.IdentityReadOnly;
  24596. };
  24597. BaseTexture.prototype.getInternalTexture = function () {
  24598. return this._texture;
  24599. };
  24600. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  24601. return !this.isBlocking || this.isReady();
  24602. };
  24603. BaseTexture.prototype.isReady = function () {
  24604. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  24605. this.delayLoad();
  24606. return false;
  24607. }
  24608. if (this._texture) {
  24609. return this._texture.isReady;
  24610. }
  24611. return false;
  24612. };
  24613. BaseTexture.prototype.getSize = function () {
  24614. if (this._texture && this._texture.width) {
  24615. return new BABYLON.Size(this._texture.width, this._texture.height);
  24616. }
  24617. if (this._texture && this._texture._size) {
  24618. return new BABYLON.Size(this._texture._size, this._texture._size);
  24619. }
  24620. return BABYLON.Size.Zero();
  24621. };
  24622. BaseTexture.prototype.getBaseSize = function () {
  24623. if (!this.isReady() || !this._texture)
  24624. return BABYLON.Size.Zero();
  24625. if (this._texture._size) {
  24626. return new BABYLON.Size(this._texture._size, this._texture._size);
  24627. }
  24628. return new BABYLON.Size(this._texture.baseWidth, this._texture.baseHeight);
  24629. };
  24630. BaseTexture.prototype.scale = function (ratio) {
  24631. };
  24632. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  24633. get: function () {
  24634. return false;
  24635. },
  24636. enumerable: true,
  24637. configurable: true
  24638. });
  24639. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  24640. if (!this._scene) {
  24641. return null;
  24642. }
  24643. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  24644. for (var index = 0; index < texturesCache.length; index++) {
  24645. var texturesCacheEntry = texturesCache[index];
  24646. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  24647. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  24648. texturesCacheEntry.incrementReferences();
  24649. return texturesCacheEntry;
  24650. }
  24651. }
  24652. }
  24653. return null;
  24654. };
  24655. BaseTexture.prototype._rebuild = function () {
  24656. };
  24657. BaseTexture.prototype.delayLoad = function () {
  24658. };
  24659. BaseTexture.prototype.clone = function () {
  24660. return null;
  24661. };
  24662. Object.defineProperty(BaseTexture.prototype, "textureType", {
  24663. get: function () {
  24664. if (!this._texture) {
  24665. return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  24666. }
  24667. return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  24668. },
  24669. enumerable: true,
  24670. configurable: true
  24671. });
  24672. Object.defineProperty(BaseTexture.prototype, "textureFormat", {
  24673. get: function () {
  24674. if (!this._texture) {
  24675. return BABYLON.Engine.TEXTUREFORMAT_RGBA;
  24676. }
  24677. return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;
  24678. },
  24679. enumerable: true,
  24680. configurable: true
  24681. });
  24682. BaseTexture.prototype.readPixels = function (faceIndex) {
  24683. if (faceIndex === void 0) { faceIndex = 0; }
  24684. if (!this._texture) {
  24685. return null;
  24686. }
  24687. var size = this.getSize();
  24688. var scene = this.getScene();
  24689. if (!scene) {
  24690. return null;
  24691. }
  24692. var engine = scene.getEngine();
  24693. if (this._texture.isCube) {
  24694. return engine._readTexturePixels(this._texture, size.width, size.height, faceIndex);
  24695. }
  24696. return engine._readTexturePixels(this._texture, size.width, size.height, -1);
  24697. };
  24698. BaseTexture.prototype.releaseInternalTexture = function () {
  24699. if (this._texture) {
  24700. this._texture.dispose();
  24701. this._texture = null;
  24702. }
  24703. };
  24704. Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
  24705. get: function () {
  24706. if (!this._texture || !BABYLON.CubeMapToSphericalPolynomialTools || !this.isReady()) {
  24707. return null;
  24708. }
  24709. if (!this._texture._sphericalPolynomial) {
  24710. this._texture._sphericalPolynomial =
  24711. BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
  24712. }
  24713. return this._texture._sphericalPolynomial;
  24714. },
  24715. set: function (value) {
  24716. if (this._texture) {
  24717. this._texture._sphericalPolynomial = value;
  24718. }
  24719. },
  24720. enumerable: true,
  24721. configurable: true
  24722. });
  24723. Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", {
  24724. get: function () {
  24725. if (this._texture) {
  24726. return this._texture._lodTextureHigh;
  24727. }
  24728. return null;
  24729. },
  24730. enumerable: true,
  24731. configurable: true
  24732. });
  24733. Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", {
  24734. get: function () {
  24735. if (this._texture) {
  24736. return this._texture._lodTextureMid;
  24737. }
  24738. return null;
  24739. },
  24740. enumerable: true,
  24741. configurable: true
  24742. });
  24743. Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", {
  24744. get: function () {
  24745. if (this._texture) {
  24746. return this._texture._lodTextureLow;
  24747. }
  24748. return null;
  24749. },
  24750. enumerable: true,
  24751. configurable: true
  24752. });
  24753. BaseTexture.prototype.dispose = function () {
  24754. if (!this._scene) {
  24755. return;
  24756. }
  24757. // Animations
  24758. this._scene.stopAnimation(this);
  24759. // Remove from scene
  24760. this._scene._removePendingData(this);
  24761. var index = this._scene.textures.indexOf(this);
  24762. if (index >= 0) {
  24763. this._scene.textures.splice(index, 1);
  24764. }
  24765. if (this._texture === undefined) {
  24766. return;
  24767. }
  24768. // Release
  24769. this.releaseInternalTexture();
  24770. // Callback
  24771. this.onDisposeObservable.notifyObservers(this);
  24772. this.onDisposeObservable.clear();
  24773. };
  24774. BaseTexture.prototype.serialize = function () {
  24775. if (!this.name) {
  24776. return null;
  24777. }
  24778. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  24779. // Animations
  24780. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  24781. return serializationObject;
  24782. };
  24783. BaseTexture.WhenAllReady = function (textures, callback) {
  24784. var numRemaining = textures.length;
  24785. if (numRemaining === 0) {
  24786. callback();
  24787. return;
  24788. }
  24789. var _loop_1 = function () {
  24790. texture = textures[i];
  24791. if (texture.isReady()) {
  24792. if (--numRemaining === 0) {
  24793. callback();
  24794. }
  24795. }
  24796. else {
  24797. onLoadObservable = texture.onLoadObservable;
  24798. var onLoadCallback_1 = function () {
  24799. onLoadObservable.removeCallback(onLoadCallback_1);
  24800. if (--numRemaining === 0) {
  24801. callback();
  24802. }
  24803. };
  24804. onLoadObservable.add(onLoadCallback_1);
  24805. }
  24806. };
  24807. var texture, onLoadObservable;
  24808. for (var i = 0; i < textures.length; i++) {
  24809. _loop_1();
  24810. }
  24811. };
  24812. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  24813. __decorate([
  24814. BABYLON.serialize()
  24815. ], BaseTexture.prototype, "name", void 0);
  24816. __decorate([
  24817. BABYLON.serialize("hasAlpha")
  24818. ], BaseTexture.prototype, "_hasAlpha", void 0);
  24819. __decorate([
  24820. BABYLON.serialize()
  24821. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  24822. __decorate([
  24823. BABYLON.serialize()
  24824. ], BaseTexture.prototype, "level", void 0);
  24825. __decorate([
  24826. BABYLON.serialize()
  24827. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  24828. __decorate([
  24829. BABYLON.serialize("coordinatesMode")
  24830. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  24831. __decorate([
  24832. BABYLON.serialize()
  24833. ], BaseTexture.prototype, "wrapU", void 0);
  24834. __decorate([
  24835. BABYLON.serialize()
  24836. ], BaseTexture.prototype, "wrapV", void 0);
  24837. __decorate([
  24838. BABYLON.serialize()
  24839. ], BaseTexture.prototype, "wrapR", void 0);
  24840. __decorate([
  24841. BABYLON.serialize()
  24842. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  24843. __decorate([
  24844. BABYLON.serialize()
  24845. ], BaseTexture.prototype, "isCube", void 0);
  24846. __decorate([
  24847. BABYLON.serialize()
  24848. ], BaseTexture.prototype, "is3D", void 0);
  24849. __decorate([
  24850. BABYLON.serialize()
  24851. ], BaseTexture.prototype, "gammaSpace", void 0);
  24852. __decorate([
  24853. BABYLON.serialize()
  24854. ], BaseTexture.prototype, "invertZ", void 0);
  24855. __decorate([
  24856. BABYLON.serialize()
  24857. ], BaseTexture.prototype, "lodLevelInAlpha", void 0);
  24858. __decorate([
  24859. BABYLON.serialize()
  24860. ], BaseTexture.prototype, "lodGenerationOffset", void 0);
  24861. __decorate([
  24862. BABYLON.serialize()
  24863. ], BaseTexture.prototype, "lodGenerationScale", void 0);
  24864. __decorate([
  24865. BABYLON.serialize()
  24866. ], BaseTexture.prototype, "isRenderTarget", void 0);
  24867. return BaseTexture;
  24868. }());
  24869. BABYLON.BaseTexture = BaseTexture;
  24870. })(BABYLON || (BABYLON = {}));
  24871. //# sourceMappingURL=babylon.baseTexture.js.map
  24872. var BABYLON;
  24873. (function (BABYLON) {
  24874. var Texture = /** @class */ (function (_super) {
  24875. __extends(Texture, _super);
  24876. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  24877. if (noMipmap === void 0) { noMipmap = false; }
  24878. if (invertY === void 0) { invertY = true; }
  24879. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  24880. if (onLoad === void 0) { onLoad = null; }
  24881. if (onError === void 0) { onError = null; }
  24882. if (buffer === void 0) { buffer = null; }
  24883. if (deleteBuffer === void 0) { deleteBuffer = false; }
  24884. var _this = _super.call(this, scene) || this;
  24885. _this.uOffset = 0;
  24886. _this.vOffset = 0;
  24887. _this.uScale = 1.0;
  24888. _this.vScale = 1.0;
  24889. _this.uAng = 0;
  24890. _this.vAng = 0;
  24891. _this.wAng = 0;
  24892. _this._isBlocking = true;
  24893. _this.name = url || "";
  24894. _this.url = url;
  24895. _this._noMipmap = noMipmap;
  24896. _this._invertY = invertY;
  24897. _this._samplingMode = samplingMode;
  24898. _this._buffer = buffer;
  24899. _this._deleteBuffer = deleteBuffer;
  24900. if (format) {
  24901. _this._format = format;
  24902. }
  24903. scene = _this.getScene();
  24904. if (!scene) {
  24905. return _this;
  24906. }
  24907. scene.getEngine().onBeforeTextureInitObservable.notifyObservers(_this);
  24908. var load = function () {
  24909. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  24910. _this.onLoadObservable.notifyObservers(_this);
  24911. }
  24912. if (onLoad) {
  24913. onLoad();
  24914. }
  24915. if (!_this.isBlocking && scene) {
  24916. scene.resetCachedMaterial();
  24917. }
  24918. };
  24919. if (!_this.url) {
  24920. _this._delayedOnLoad = load;
  24921. _this._delayedOnError = onError;
  24922. return _this;
  24923. }
  24924. _this._texture = _this._getFromCache(_this.url, noMipmap, samplingMode);
  24925. if (!_this._texture) {
  24926. if (!scene.useDelayedTextureLoading) {
  24927. _this._texture = scene.getEngine().createTexture(_this.url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, undefined, _this._format);
  24928. if (deleteBuffer) {
  24929. delete _this._buffer;
  24930. }
  24931. }
  24932. else {
  24933. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  24934. _this._delayedOnLoad = load;
  24935. _this._delayedOnError = onError;
  24936. }
  24937. }
  24938. else {
  24939. if (_this._texture.isReady) {
  24940. BABYLON.Tools.SetImmediate(function () { return load(); });
  24941. }
  24942. else {
  24943. _this._texture.onLoadedObservable.add(load);
  24944. }
  24945. }
  24946. return _this;
  24947. }
  24948. Object.defineProperty(Texture.prototype, "noMipmap", {
  24949. get: function () {
  24950. return this._noMipmap;
  24951. },
  24952. enumerable: true,
  24953. configurable: true
  24954. });
  24955. Object.defineProperty(Texture.prototype, "isBlocking", {
  24956. get: function () {
  24957. return this._isBlocking;
  24958. },
  24959. set: function (value) {
  24960. this._isBlocking = value;
  24961. },
  24962. enumerable: true,
  24963. configurable: true
  24964. });
  24965. Object.defineProperty(Texture.prototype, "samplingMode", {
  24966. get: function () {
  24967. return this._samplingMode;
  24968. },
  24969. enumerable: true,
  24970. configurable: true
  24971. });
  24972. Texture.prototype.updateURL = function (url) {
  24973. this.url = url;
  24974. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  24975. this.delayLoad();
  24976. };
  24977. Texture.prototype.delayLoad = function () {
  24978. var _this = this;
  24979. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  24980. return;
  24981. }
  24982. var scene = this.getScene();
  24983. if (!scene) {
  24984. return;
  24985. }
  24986. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  24987. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  24988. if (!this._texture) {
  24989. this._texture = scene.getEngine().createTexture(this.url, this._noMipmap, this._invertY, scene, this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer, null, this._format);
  24990. if (this._deleteBuffer) {
  24991. delete this._buffer;
  24992. }
  24993. }
  24994. else {
  24995. if (this._texture.isReady) {
  24996. BABYLON.Tools.SetImmediate(function () {
  24997. if (!_this._delayedOnLoad) {
  24998. return;
  24999. }
  25000. _this._delayedOnLoad();
  25001. });
  25002. }
  25003. else {
  25004. if (this._delayedOnLoad) {
  25005. this._texture.onLoadedObservable.add(this._delayedOnLoad);
  25006. }
  25007. }
  25008. }
  25009. };
  25010. Texture.prototype.updateSamplingMode = function (samplingMode) {
  25011. if (!this._texture) {
  25012. return;
  25013. }
  25014. var scene = this.getScene();
  25015. if (!scene) {
  25016. return;
  25017. }
  25018. this._samplingMode = samplingMode;
  25019. scene.getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  25020. };
  25021. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  25022. x *= this.uScale;
  25023. y *= this.vScale;
  25024. x -= 0.5 * this.uScale;
  25025. y -= 0.5 * this.vScale;
  25026. z -= 0.5;
  25027. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  25028. t.x += 0.5 * this.uScale + this.uOffset;
  25029. t.y += 0.5 * this.vScale + this.vOffset;
  25030. t.z += 0.5;
  25031. };
  25032. Texture.prototype.getTextureMatrix = function () {
  25033. var _this = this;
  25034. if (this.uOffset === this._cachedUOffset &&
  25035. this.vOffset === this._cachedVOffset &&
  25036. this.uScale === this._cachedUScale &&
  25037. this.vScale === this._cachedVScale &&
  25038. this.uAng === this._cachedUAng &&
  25039. this.vAng === this._cachedVAng &&
  25040. this.wAng === this._cachedWAng) {
  25041. return this._cachedTextureMatrix;
  25042. }
  25043. this._cachedUOffset = this.uOffset;
  25044. this._cachedVOffset = this.vOffset;
  25045. this._cachedUScale = this.uScale;
  25046. this._cachedVScale = this.vScale;
  25047. this._cachedUAng = this.uAng;
  25048. this._cachedVAng = this.vAng;
  25049. this._cachedWAng = this.wAng;
  25050. if (!this._cachedTextureMatrix) {
  25051. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  25052. this._rowGenerationMatrix = new BABYLON.Matrix();
  25053. this._t0 = BABYLON.Vector3.Zero();
  25054. this._t1 = BABYLON.Vector3.Zero();
  25055. this._t2 = BABYLON.Vector3.Zero();
  25056. }
  25057. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  25058. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  25059. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  25060. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  25061. this._t1.subtractInPlace(this._t0);
  25062. this._t2.subtractInPlace(this._t0);
  25063. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  25064. this._cachedTextureMatrix.m[0] = this._t1.x;
  25065. this._cachedTextureMatrix.m[1] = this._t1.y;
  25066. this._cachedTextureMatrix.m[2] = this._t1.z;
  25067. this._cachedTextureMatrix.m[4] = this._t2.x;
  25068. this._cachedTextureMatrix.m[5] = this._t2.y;
  25069. this._cachedTextureMatrix.m[6] = this._t2.z;
  25070. this._cachedTextureMatrix.m[8] = this._t0.x;
  25071. this._cachedTextureMatrix.m[9] = this._t0.y;
  25072. this._cachedTextureMatrix.m[10] = this._t0.z;
  25073. var scene = this.getScene();
  25074. if (!scene) {
  25075. return this._cachedTextureMatrix;
  25076. }
  25077. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  25078. return mat.hasTexture(_this);
  25079. });
  25080. return this._cachedTextureMatrix;
  25081. };
  25082. Texture.prototype.getReflectionTextureMatrix = function () {
  25083. var _this = this;
  25084. var scene = this.getScene();
  25085. if (!scene) {
  25086. return this._cachedTextureMatrix;
  25087. }
  25088. if (this.uOffset === this._cachedUOffset &&
  25089. this.vOffset === this._cachedVOffset &&
  25090. this.uScale === this._cachedUScale &&
  25091. this.vScale === this._cachedVScale &&
  25092. this.coordinatesMode === this._cachedCoordinatesMode) {
  25093. if (this.coordinatesMode === Texture.PROJECTION_MODE) {
  25094. if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {
  25095. return this._cachedTextureMatrix;
  25096. }
  25097. }
  25098. else {
  25099. return this._cachedTextureMatrix;
  25100. }
  25101. }
  25102. if (!this._cachedTextureMatrix) {
  25103. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  25104. }
  25105. if (!this._projectionModeMatrix) {
  25106. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  25107. }
  25108. this._cachedUOffset = this.uOffset;
  25109. this._cachedVOffset = this.vOffset;
  25110. this._cachedUScale = this.uScale;
  25111. this._cachedVScale = this.vScale;
  25112. this._cachedCoordinatesMode = this.coordinatesMode;
  25113. switch (this.coordinatesMode) {
  25114. case Texture.PLANAR_MODE:
  25115. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  25116. this._cachedTextureMatrix[0] = this.uScale;
  25117. this._cachedTextureMatrix[5] = this.vScale;
  25118. this._cachedTextureMatrix[12] = this.uOffset;
  25119. this._cachedTextureMatrix[13] = this.vOffset;
  25120. break;
  25121. case Texture.PROJECTION_MODE:
  25122. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  25123. this._projectionModeMatrix.m[0] = 0.5;
  25124. this._projectionModeMatrix.m[5] = -0.5;
  25125. this._projectionModeMatrix.m[10] = 0.0;
  25126. this._projectionModeMatrix.m[12] = 0.5;
  25127. this._projectionModeMatrix.m[13] = 0.5;
  25128. this._projectionModeMatrix.m[14] = 1.0;
  25129. this._projectionModeMatrix.m[15] = 1.0;
  25130. var projectionMatrix = scene.getProjectionMatrix();
  25131. this._cachedProjectionMatrixId = projectionMatrix.updateFlag;
  25132. projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  25133. break;
  25134. default:
  25135. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  25136. break;
  25137. }
  25138. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  25139. return (mat.getActiveTextures().indexOf(_this) !== -1);
  25140. });
  25141. return this._cachedTextureMatrix;
  25142. };
  25143. Texture.prototype.clone = function () {
  25144. var _this = this;
  25145. return BABYLON.SerializationHelper.Clone(function () {
  25146. return new Texture(_this._texture ? _this._texture.url : null, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  25147. }, this);
  25148. };
  25149. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  25150. get: function () {
  25151. if (!this._onLoadObservable) {
  25152. this._onLoadObservable = new BABYLON.Observable();
  25153. }
  25154. return this._onLoadObservable;
  25155. },
  25156. enumerable: true,
  25157. configurable: true
  25158. });
  25159. Texture.prototype.serialize = function () {
  25160. var serializationObject = _super.prototype.serialize.call(this);
  25161. if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") {
  25162. serializationObject.base64String = this._buffer;
  25163. serializationObject.name = serializationObject.name.replace("data:", "");
  25164. }
  25165. return serializationObject;
  25166. };
  25167. Texture.prototype.getClassName = function () {
  25168. return "Texture";
  25169. };
  25170. Texture.prototype.dispose = function () {
  25171. _super.prototype.dispose.call(this);
  25172. if (this.onLoadObservable) {
  25173. this.onLoadObservable.clear();
  25174. this._onLoadObservable = null;
  25175. }
  25176. this._delayedOnLoad = null;
  25177. this._delayedOnError = null;
  25178. };
  25179. // Statics
  25180. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  25181. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  25182. if (onLoad === void 0) { onLoad = null; }
  25183. if (onError === void 0) { onError = null; }
  25184. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  25185. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  25186. };
  25187. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  25188. if (parsedTexture.customType) {
  25189. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  25190. // Update Sampling Mode
  25191. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  25192. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  25193. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  25194. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  25195. }
  25196. }
  25197. return parsedCustomTexture;
  25198. }
  25199. if (parsedTexture.isCube) {
  25200. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  25201. }
  25202. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  25203. return null;
  25204. }
  25205. var texture = BABYLON.SerializationHelper.Parse(function () {
  25206. var generateMipMaps = true;
  25207. if (parsedTexture.noMipmap) {
  25208. generateMipMaps = false;
  25209. }
  25210. if (parsedTexture.mirrorPlane) {
  25211. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  25212. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  25213. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  25214. return mirrorTexture;
  25215. }
  25216. else if (parsedTexture.isRenderTarget) {
  25217. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  25218. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  25219. return renderTargetTexture;
  25220. }
  25221. else {
  25222. var texture;
  25223. if (parsedTexture.base64String) {
  25224. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene, !generateMipMaps);
  25225. }
  25226. else {
  25227. texture = new Texture(rootUrl + parsedTexture.name, scene, !generateMipMaps);
  25228. }
  25229. return texture;
  25230. }
  25231. }, parsedTexture, scene);
  25232. // Update Sampling Mode
  25233. if (parsedTexture.samplingMode) {
  25234. var sampling = parsedTexture.samplingMode;
  25235. if (texture._samplingMode !== sampling) {
  25236. texture.updateSamplingMode(sampling);
  25237. }
  25238. }
  25239. // Animations
  25240. if (parsedTexture.animations) {
  25241. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  25242. var parsedAnimation = parsedTexture.animations[animationIndex];
  25243. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  25244. }
  25245. }
  25246. return texture;
  25247. };
  25248. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  25249. if (deleteBuffer === void 0) { deleteBuffer = false; }
  25250. if (noMipmap === void 0) { noMipmap = false; }
  25251. if (invertY === void 0) { invertY = true; }
  25252. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  25253. if (onLoad === void 0) { onLoad = null; }
  25254. if (onError === void 0) { onError = null; }
  25255. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  25256. if (name.substr(0, 5) !== "data:") {
  25257. name = "data:" + name;
  25258. }
  25259. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  25260. };
  25261. // Constants
  25262. Texture.NEAREST_SAMPLINGMODE = 1;
  25263. Texture.NEAREST_NEAREST_MIPLINEAR = 1; // nearest is mag = nearest and min = nearest and mip = linear
  25264. Texture.BILINEAR_SAMPLINGMODE = 2;
  25265. Texture.LINEAR_LINEAR_MIPNEAREST = 2; // Bilinear is mag = linear and min = linear and mip = nearest
  25266. Texture.TRILINEAR_SAMPLINGMODE = 3;
  25267. Texture.LINEAR_LINEAR_MIPLINEAR = 3; // Trilinear is mag = linear and min = linear and mip = linear
  25268. Texture.NEAREST_NEAREST_MIPNEAREST = 4;
  25269. Texture.NEAREST_LINEAR_MIPNEAREST = 5;
  25270. Texture.NEAREST_LINEAR_MIPLINEAR = 6;
  25271. Texture.NEAREST_LINEAR = 7;
  25272. Texture.NEAREST_NEAREST = 8;
  25273. Texture.LINEAR_NEAREST_MIPNEAREST = 9;
  25274. Texture.LINEAR_NEAREST_MIPLINEAR = 10;
  25275. Texture.LINEAR_LINEAR = 11;
  25276. Texture.LINEAR_NEAREST = 12;
  25277. Texture.EXPLICIT_MODE = 0;
  25278. Texture.SPHERICAL_MODE = 1;
  25279. Texture.PLANAR_MODE = 2;
  25280. Texture.CUBIC_MODE = 3;
  25281. Texture.PROJECTION_MODE = 4;
  25282. Texture.SKYBOX_MODE = 5;
  25283. Texture.INVCUBIC_MODE = 6;
  25284. Texture.EQUIRECTANGULAR_MODE = 7;
  25285. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  25286. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  25287. Texture.CLAMP_ADDRESSMODE = 0;
  25288. Texture.WRAP_ADDRESSMODE = 1;
  25289. Texture.MIRROR_ADDRESSMODE = 2;
  25290. __decorate([
  25291. BABYLON.serialize()
  25292. ], Texture.prototype, "url", void 0);
  25293. __decorate([
  25294. BABYLON.serialize()
  25295. ], Texture.prototype, "uOffset", void 0);
  25296. __decorate([
  25297. BABYLON.serialize()
  25298. ], Texture.prototype, "vOffset", void 0);
  25299. __decorate([
  25300. BABYLON.serialize()
  25301. ], Texture.prototype, "uScale", void 0);
  25302. __decorate([
  25303. BABYLON.serialize()
  25304. ], Texture.prototype, "vScale", void 0);
  25305. __decorate([
  25306. BABYLON.serialize()
  25307. ], Texture.prototype, "uAng", void 0);
  25308. __decorate([
  25309. BABYLON.serialize()
  25310. ], Texture.prototype, "vAng", void 0);
  25311. __decorate([
  25312. BABYLON.serialize()
  25313. ], Texture.prototype, "wAng", void 0);
  25314. __decorate([
  25315. BABYLON.serialize()
  25316. ], Texture.prototype, "isBlocking", null);
  25317. return Texture;
  25318. }(BABYLON.BaseTexture));
  25319. BABYLON.Texture = Texture;
  25320. })(BABYLON || (BABYLON = {}));
  25321. //# sourceMappingURL=babylon.texture.js.map
  25322. var BABYLON;
  25323. (function (BABYLON) {
  25324. var _InstancesBatch = /** @class */ (function () {
  25325. function _InstancesBatch() {
  25326. this.mustReturn = false;
  25327. this.visibleInstances = new Array();
  25328. this.renderSelf = new Array();
  25329. }
  25330. return _InstancesBatch;
  25331. }());
  25332. BABYLON._InstancesBatch = _InstancesBatch;
  25333. var Mesh = /** @class */ (function (_super) {
  25334. __extends(Mesh, _super);
  25335. /**
  25336. * @constructor
  25337. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  25338. * @param {Scene} scene The scene to add this mesh to.
  25339. * @param {Node} parent The parent of this mesh, if it has one
  25340. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  25341. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  25342. * When false, achieved by calling a clone(), also passing False.
  25343. * This will make creation of children, recursive.
  25344. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  25345. */
  25346. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  25347. if (scene === void 0) { scene = null; }
  25348. if (parent === void 0) { parent = null; }
  25349. if (source === void 0) { source = null; }
  25350. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  25351. var _this = _super.call(this, name, scene) || this;
  25352. // Events
  25353. /**
  25354. * An event triggered before rendering the mesh
  25355. * @type {BABYLON.Observable}
  25356. */
  25357. _this.onBeforeRenderObservable = new BABYLON.Observable();
  25358. /**
  25359. * An event triggered after rendering the mesh
  25360. * @type {BABYLON.Observable}
  25361. */
  25362. _this.onAfterRenderObservable = new BABYLON.Observable();
  25363. /**
  25364. * An event triggered before drawing the mesh
  25365. * @type {BABYLON.Observable}
  25366. */
  25367. _this.onBeforeDrawObservable = new BABYLON.Observable();
  25368. // Members
  25369. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  25370. _this.instances = new Array();
  25371. _this._LODLevels = new Array();
  25372. _this._visibleInstances = {};
  25373. _this._renderIdForInstances = new Array();
  25374. _this._batchCache = new _InstancesBatch();
  25375. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  25376. // Use by builder only to know what orientation were the mesh build in.
  25377. _this._originalBuilderSideOrientation = Mesh._DEFAULTSIDE;
  25378. _this.overrideMaterialSideOrientation = null;
  25379. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  25380. // Will be used to save a source mesh reference, If any
  25381. _this._source = null;
  25382. scene = _this.getScene();
  25383. if (source) {
  25384. // Source mesh
  25385. _this._source = source;
  25386. // Geometry
  25387. if (source._geometry) {
  25388. source._geometry.applyToMesh(_this);
  25389. }
  25390. // Deep copy
  25391. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId", "source", "metadata"], ["_poseMatrix", "_source"]);
  25392. // Metadata
  25393. if (source.metadata && source.metadata.clone) {
  25394. _this.metadata = source.metadata.clone();
  25395. }
  25396. else {
  25397. _this.metadata = source.metadata;
  25398. }
  25399. // Tags
  25400. if (BABYLON.Tags && BABYLON.Tags.HasTags(source)) {
  25401. BABYLON.Tags.AddTagsTo(_this, BABYLON.Tags.GetTags(source, true));
  25402. }
  25403. // Parent
  25404. _this.parent = source.parent;
  25405. // Pivot
  25406. _this.setPivotMatrix(source.getPivotMatrix());
  25407. _this.id = name + "." + source.id;
  25408. // Material
  25409. _this.material = source.material;
  25410. var index;
  25411. if (!doNotCloneChildren) {
  25412. // Children
  25413. var directDescendants = source.getDescendants(true);
  25414. for (var index_1 = 0; index_1 < directDescendants.length; index_1++) {
  25415. var child = directDescendants[index_1];
  25416. if (child.clone) {
  25417. child.clone(name + "." + child.name, _this);
  25418. }
  25419. }
  25420. }
  25421. // Physics clone
  25422. var physicsEngine = _this.getScene().getPhysicsEngine();
  25423. if (clonePhysicsImpostor && physicsEngine) {
  25424. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  25425. if (impostor) {
  25426. _this.physicsImpostor = impostor.clone(_this);
  25427. }
  25428. }
  25429. // Particles
  25430. for (index = 0; index < scene.particleSystems.length; index++) {
  25431. var system = scene.particleSystems[index];
  25432. if (system.emitter === source) {
  25433. system.clone(system.name, _this);
  25434. }
  25435. }
  25436. _this.computeWorldMatrix(true);
  25437. }
  25438. // Parent
  25439. if (parent !== null) {
  25440. _this.parent = parent;
  25441. }
  25442. return _this;
  25443. }
  25444. Object.defineProperty(Mesh, "FRONTSIDE", {
  25445. /**
  25446. * Mesh side orientation : usually the external or front surface
  25447. */
  25448. get: function () {
  25449. return Mesh._FRONTSIDE;
  25450. },
  25451. enumerable: true,
  25452. configurable: true
  25453. });
  25454. Object.defineProperty(Mesh, "BACKSIDE", {
  25455. /**
  25456. * Mesh side orientation : usually the internal or back surface
  25457. */
  25458. get: function () {
  25459. return Mesh._BACKSIDE;
  25460. },
  25461. enumerable: true,
  25462. configurable: true
  25463. });
  25464. Object.defineProperty(Mesh, "DOUBLESIDE", {
  25465. /**
  25466. * Mesh side orientation : both internal and external or front and back surfaces
  25467. */
  25468. get: function () {
  25469. return Mesh._DOUBLESIDE;
  25470. },
  25471. enumerable: true,
  25472. configurable: true
  25473. });
  25474. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  25475. /**
  25476. * Mesh side orientation : by default, `FRONTSIDE`
  25477. */
  25478. get: function () {
  25479. return Mesh._DEFAULTSIDE;
  25480. },
  25481. enumerable: true,
  25482. configurable: true
  25483. });
  25484. Object.defineProperty(Mesh, "NO_CAP", {
  25485. /**
  25486. * Mesh cap setting : no cap
  25487. */
  25488. get: function () {
  25489. return Mesh._NO_CAP;
  25490. },
  25491. enumerable: true,
  25492. configurable: true
  25493. });
  25494. Object.defineProperty(Mesh, "CAP_START", {
  25495. /**
  25496. * Mesh cap setting : one cap at the beginning of the mesh
  25497. */
  25498. get: function () {
  25499. return Mesh._CAP_START;
  25500. },
  25501. enumerable: true,
  25502. configurable: true
  25503. });
  25504. Object.defineProperty(Mesh, "CAP_END", {
  25505. /**
  25506. * Mesh cap setting : one cap at the end of the mesh
  25507. */
  25508. get: function () {
  25509. return Mesh._CAP_END;
  25510. },
  25511. enumerable: true,
  25512. configurable: true
  25513. });
  25514. Object.defineProperty(Mesh, "CAP_ALL", {
  25515. /**
  25516. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  25517. */
  25518. get: function () {
  25519. return Mesh._CAP_ALL;
  25520. },
  25521. enumerable: true,
  25522. configurable: true
  25523. });
  25524. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  25525. set: function (callback) {
  25526. if (this._onBeforeDrawObserver) {
  25527. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  25528. }
  25529. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  25530. },
  25531. enumerable: true,
  25532. configurable: true
  25533. });
  25534. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  25535. get: function () {
  25536. return this._morphTargetManager;
  25537. },
  25538. set: function (value) {
  25539. if (this._morphTargetManager === value) {
  25540. return;
  25541. }
  25542. this._morphTargetManager = value;
  25543. this._syncGeometryWithMorphTargetManager();
  25544. },
  25545. enumerable: true,
  25546. configurable: true
  25547. });
  25548. Object.defineProperty(Mesh.prototype, "source", {
  25549. get: function () {
  25550. return this._source;
  25551. },
  25552. enumerable: true,
  25553. configurable: true
  25554. });
  25555. Object.defineProperty(Mesh.prototype, "isUnIndexed", {
  25556. get: function () {
  25557. return this._unIndexed;
  25558. },
  25559. set: function (value) {
  25560. if (this._unIndexed !== value) {
  25561. this._unIndexed = value;
  25562. this._markSubMeshesAsAttributesDirty();
  25563. }
  25564. },
  25565. enumerable: true,
  25566. configurable: true
  25567. });
  25568. // Methods
  25569. /**
  25570. * Returns the string "Mesh".
  25571. */
  25572. Mesh.prototype.getClassName = function () {
  25573. return "Mesh";
  25574. };
  25575. /**
  25576. * Returns a string.
  25577. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  25578. */
  25579. Mesh.prototype.toString = function (fullDetails) {
  25580. var ret = _super.prototype.toString.call(this, fullDetails);
  25581. ret += ", n vertices: " + this.getTotalVertices();
  25582. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  25583. if (this.animations) {
  25584. for (var i = 0; i < this.animations.length; i++) {
  25585. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  25586. }
  25587. }
  25588. if (fullDetails) {
  25589. if (this._geometry) {
  25590. var ib = this.getIndices();
  25591. var vb = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  25592. if (vb && ib) {
  25593. ret += ", flat shading: " + (vb.length / 3 === ib.length ? "YES" : "NO");
  25594. }
  25595. }
  25596. else {
  25597. ret += ", flat shading: UNKNOWN";
  25598. }
  25599. }
  25600. return ret;
  25601. };
  25602. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  25603. /**
  25604. * True if the mesh has some Levels Of Details (LOD).
  25605. * Returns a boolean.
  25606. */
  25607. get: function () {
  25608. return this._LODLevels.length > 0;
  25609. },
  25610. enumerable: true,
  25611. configurable: true
  25612. });
  25613. /**
  25614. * Gets the list of {BABYLON.MeshLODLevel} associated with the current mesh
  25615. * @returns an array of {BABYLON.MeshLODLevel}
  25616. */
  25617. Mesh.prototype.getLODLevels = function () {
  25618. return this._LODLevels;
  25619. };
  25620. Mesh.prototype._sortLODLevels = function () {
  25621. this._LODLevels.sort(function (a, b) {
  25622. if (a.distance < b.distance) {
  25623. return 1;
  25624. }
  25625. if (a.distance > b.distance) {
  25626. return -1;
  25627. }
  25628. return 0;
  25629. });
  25630. };
  25631. /**
  25632. * Add a mesh as LOD level triggered at the given distance.
  25633. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  25634. * @param {number} distance The distance from the center of the object to show this level
  25635. * @param {Mesh} mesh The mesh to be added as LOD level
  25636. * @return {Mesh} This mesh (for chaining)
  25637. */
  25638. Mesh.prototype.addLODLevel = function (distance, mesh) {
  25639. if (mesh && mesh._masterMesh) {
  25640. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  25641. return this;
  25642. }
  25643. var level = new BABYLON.MeshLODLevel(distance, mesh);
  25644. this._LODLevels.push(level);
  25645. if (mesh) {
  25646. mesh._masterMesh = this;
  25647. }
  25648. this._sortLODLevels();
  25649. return this;
  25650. };
  25651. /**
  25652. * Returns the LOD level mesh at the passed distance or null if not found.
  25653. * It is related to the method `addLODLevel(distance, mesh)`.
  25654. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  25655. * Returns an object Mesh or `null`.
  25656. */
  25657. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  25658. for (var index = 0; index < this._LODLevels.length; index++) {
  25659. var level = this._LODLevels[index];
  25660. if (level.distance === distance) {
  25661. return level.mesh;
  25662. }
  25663. }
  25664. return null;
  25665. };
  25666. /**
  25667. * Remove a mesh from the LOD array
  25668. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  25669. * @param {Mesh} mesh The mesh to be removed.
  25670. * @return {Mesh} This mesh (for chaining)
  25671. */
  25672. Mesh.prototype.removeLODLevel = function (mesh) {
  25673. for (var index = 0; index < this._LODLevels.length; index++) {
  25674. if (this._LODLevels[index].mesh === mesh) {
  25675. this._LODLevels.splice(index, 1);
  25676. if (mesh) {
  25677. mesh._masterMesh = null;
  25678. }
  25679. }
  25680. }
  25681. this._sortLODLevels();
  25682. return this;
  25683. };
  25684. /**
  25685. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  25686. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  25687. */
  25688. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  25689. if (!this._LODLevels || this._LODLevels.length === 0) {
  25690. return this;
  25691. }
  25692. var bSphere;
  25693. if (boundingSphere) {
  25694. bSphere = boundingSphere;
  25695. }
  25696. else {
  25697. var boundingInfo = this.getBoundingInfo();
  25698. bSphere = boundingInfo.boundingSphere;
  25699. }
  25700. var distanceToCamera = bSphere.centerWorld.subtract(camera.globalPosition).length();
  25701. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  25702. if (this.onLODLevelSelection) {
  25703. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  25704. }
  25705. return this;
  25706. }
  25707. for (var index = 0; index < this._LODLevels.length; index++) {
  25708. var level = this._LODLevels[index];
  25709. if (level.distance < distanceToCamera) {
  25710. if (level.mesh) {
  25711. level.mesh._preActivate();
  25712. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  25713. }
  25714. if (this.onLODLevelSelection) {
  25715. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  25716. }
  25717. return level.mesh;
  25718. }
  25719. }
  25720. if (this.onLODLevelSelection) {
  25721. this.onLODLevelSelection(distanceToCamera, this, this);
  25722. }
  25723. return this;
  25724. };
  25725. Object.defineProperty(Mesh.prototype, "geometry", {
  25726. /**
  25727. * Returns the mesh internal Geometry object.
  25728. */
  25729. get: function () {
  25730. return this._geometry;
  25731. },
  25732. enumerable: true,
  25733. configurable: true
  25734. });
  25735. /**
  25736. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  25737. */
  25738. Mesh.prototype.getTotalVertices = function () {
  25739. if (this._geometry === null || this._geometry === undefined) {
  25740. return 0;
  25741. }
  25742. return this._geometry.getTotalVertices();
  25743. };
  25744. /**
  25745. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  25746. * 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.
  25747. * You can force the copy with forceCopy === true
  25748. * Returns null if the mesh has no geometry or no vertex buffer.
  25749. * Possible `kind` values :
  25750. * - BABYLON.VertexBuffer.PositionKind
  25751. * - BABYLON.VertexBuffer.UVKind
  25752. * - BABYLON.VertexBuffer.UV2Kind
  25753. * - BABYLON.VertexBuffer.UV3Kind
  25754. * - BABYLON.VertexBuffer.UV4Kind
  25755. * - BABYLON.VertexBuffer.UV5Kind
  25756. * - BABYLON.VertexBuffer.UV6Kind
  25757. * - BABYLON.VertexBuffer.ColorKind
  25758. * - BABYLON.VertexBuffer.MatricesIndicesKind
  25759. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  25760. * - BABYLON.VertexBuffer.MatricesWeightsKind
  25761. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  25762. */
  25763. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  25764. if (!this._geometry) {
  25765. return null;
  25766. }
  25767. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  25768. };
  25769. /**
  25770. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  25771. * Returns `null` if the mesh has no geometry.
  25772. * Possible `kind` values :
  25773. * - BABYLON.VertexBuffer.PositionKind
  25774. * - BABYLON.VertexBuffer.UVKind
  25775. * - BABYLON.VertexBuffer.UV2Kind
  25776. * - BABYLON.VertexBuffer.UV3Kind
  25777. * - BABYLON.VertexBuffer.UV4Kind
  25778. * - BABYLON.VertexBuffer.UV5Kind
  25779. * - BABYLON.VertexBuffer.UV6Kind
  25780. * - BABYLON.VertexBuffer.ColorKind
  25781. * - BABYLON.VertexBuffer.MatricesIndicesKind
  25782. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  25783. * - BABYLON.VertexBuffer.MatricesWeightsKind
  25784. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  25785. */
  25786. Mesh.prototype.getVertexBuffer = function (kind) {
  25787. if (!this._geometry) {
  25788. return null;
  25789. }
  25790. return this._geometry.getVertexBuffer(kind);
  25791. };
  25792. /**
  25793. * Returns a boolean depending on the existence of the Vertex Data for the requested `kind`.
  25794. * Possible `kind` values :
  25795. * - BABYLON.VertexBuffer.PositionKind
  25796. * - BABYLON.VertexBuffer.UVKind
  25797. * - BABYLON.VertexBuffer.UV2Kind
  25798. * - BABYLON.VertexBuffer.UV3Kind
  25799. * - BABYLON.VertexBuffer.UV4Kind
  25800. * - BABYLON.VertexBuffer.UV5Kind
  25801. * - BABYLON.VertexBuffer.UV6Kind
  25802. * - BABYLON.VertexBuffer.ColorKind
  25803. * - BABYLON.VertexBuffer.MatricesIndicesKind
  25804. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  25805. * - BABYLON.VertexBuffer.MatricesWeightsKind
  25806. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  25807. */
  25808. Mesh.prototype.isVerticesDataPresent = function (kind) {
  25809. if (!this._geometry) {
  25810. if (this._delayInfo) {
  25811. return this._delayInfo.indexOf(kind) !== -1;
  25812. }
  25813. return false;
  25814. }
  25815. return this._geometry.isVerticesDataPresent(kind);
  25816. };
  25817. /**
  25818. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  25819. * Possible `kind` values :
  25820. * - BABYLON.VertexBuffer.PositionKind
  25821. * - BABYLON.VertexBuffer.UVKind
  25822. * - BABYLON.VertexBuffer.UV2Kind
  25823. * - BABYLON.VertexBuffer.UV3Kind
  25824. * - BABYLON.VertexBuffer.UV4Kind
  25825. * - BABYLON.VertexBuffer.UV5Kind
  25826. * - BABYLON.VertexBuffer.UV6Kind
  25827. * - BABYLON.VertexBuffer.ColorKind
  25828. * - BABYLON.VertexBuffer.MatricesIndicesKind
  25829. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  25830. * - BABYLON.VertexBuffer.MatricesWeightsKind
  25831. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  25832. */
  25833. Mesh.prototype.isVertexBufferUpdatable = function (kind) {
  25834. if (!this._geometry) {
  25835. if (this._delayInfo) {
  25836. return this._delayInfo.indexOf(kind) !== -1;
  25837. }
  25838. return false;
  25839. }
  25840. return this._geometry.isVertexBufferUpdatable(kind);
  25841. };
  25842. /**
  25843. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  25844. * Possible `kind` values :
  25845. * - BABYLON.VertexBuffer.PositionKind
  25846. * - BABYLON.VertexBuffer.UVKind
  25847. * - BABYLON.VertexBuffer.UV2Kind
  25848. * - BABYLON.VertexBuffer.UV3Kind
  25849. * - BABYLON.VertexBuffer.UV4Kind
  25850. * - BABYLON.VertexBuffer.UV5Kind
  25851. * - BABYLON.VertexBuffer.UV6Kind
  25852. * - BABYLON.VertexBuffer.ColorKind
  25853. * - BABYLON.VertexBuffer.MatricesIndicesKind
  25854. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  25855. * - BABYLON.VertexBuffer.MatricesWeightsKind
  25856. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  25857. */
  25858. Mesh.prototype.getVerticesDataKinds = function () {
  25859. if (!this._geometry) {
  25860. var result = new Array();
  25861. if (this._delayInfo) {
  25862. this._delayInfo.forEach(function (kind, index, array) {
  25863. result.push(kind);
  25864. });
  25865. }
  25866. return result;
  25867. }
  25868. return this._geometry.getVerticesDataKinds();
  25869. };
  25870. /**
  25871. * Returns a positive integer : the total number of indices in this mesh geometry.
  25872. * Returns zero if the mesh has no geometry.
  25873. */
  25874. Mesh.prototype.getTotalIndices = function () {
  25875. if (!this._geometry) {
  25876. return 0;
  25877. }
  25878. return this._geometry.getTotalIndices();
  25879. };
  25880. /**
  25881. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  25882. * 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.
  25883. * Returns an empty array if the mesh has no geometry.
  25884. */
  25885. Mesh.prototype.getIndices = function (copyWhenShared) {
  25886. if (!this._geometry) {
  25887. return [];
  25888. }
  25889. return this._geometry.getIndices(copyWhenShared);
  25890. };
  25891. Object.defineProperty(Mesh.prototype, "isBlocked", {
  25892. get: function () {
  25893. return this._masterMesh !== null && this._masterMesh !== undefined;
  25894. },
  25895. enumerable: true,
  25896. configurable: true
  25897. });
  25898. /**
  25899. * Determine if the current mesh is ready to be rendered
  25900. * @param forceInstanceSupport will check if the mesh will be ready when used with instances (false by default)
  25901. * @returns true if all associated assets are ready (material, textures, shaders)
  25902. */
  25903. Mesh.prototype.isReady = function (forceInstanceSupport) {
  25904. if (forceInstanceSupport === void 0) { forceInstanceSupport = false; }
  25905. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  25906. return false;
  25907. }
  25908. if (!_super.prototype.isReady.call(this)) {
  25909. return false;
  25910. }
  25911. if (!this.subMeshes || this.subMeshes.length === 0) {
  25912. return true;
  25913. }
  25914. var engine = this.getEngine();
  25915. var scene = this.getScene();
  25916. var hardwareInstancedRendering = forceInstanceSupport || engine.getCaps().instancedArrays && this.instances.length > 0;
  25917. this.computeWorldMatrix();
  25918. var mat = this.material || scene.defaultMaterial;
  25919. if (mat) {
  25920. if (mat.storeEffectOnSubMeshes) {
  25921. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  25922. var subMesh = _a[_i];
  25923. var effectiveMaterial = subMesh.getMaterial();
  25924. if (effectiveMaterial) {
  25925. if (!effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  25926. return false;
  25927. }
  25928. }
  25929. }
  25930. }
  25931. else {
  25932. if (!mat.isReady(this, hardwareInstancedRendering)) {
  25933. return false;
  25934. }
  25935. }
  25936. }
  25937. // Shadows
  25938. for (var _b = 0, _c = this._lightSources; _b < _c.length; _b++) {
  25939. var light = _c[_b];
  25940. var generator = light.getShadowGenerator();
  25941. if (generator) {
  25942. for (var _d = 0, _e = this.subMeshes; _d < _e.length; _d++) {
  25943. var subMesh = _e[_d];
  25944. if (!generator.isReady(subMesh, hardwareInstancedRendering)) {
  25945. return false;
  25946. }
  25947. }
  25948. }
  25949. }
  25950. // LOD
  25951. for (var _f = 0, _g = this._LODLevels; _f < _g.length; _f++) {
  25952. var lod = _g[_f];
  25953. if (lod.mesh && !lod.mesh.isReady(hardwareInstancedRendering)) {
  25954. return false;
  25955. }
  25956. }
  25957. return true;
  25958. };
  25959. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  25960. /**
  25961. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  25962. * This property is pertinent only for updatable parametric shapes.
  25963. */
  25964. get: function () {
  25965. return this._areNormalsFrozen;
  25966. },
  25967. enumerable: true,
  25968. configurable: true
  25969. });
  25970. /**
  25971. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  25972. * It has no effect at all on other shapes.
  25973. * It prevents the mesh normals from being recomputed on next `positions` array update.
  25974. * Returns the Mesh.
  25975. */
  25976. Mesh.prototype.freezeNormals = function () {
  25977. this._areNormalsFrozen = true;
  25978. return this;
  25979. };
  25980. /**
  25981. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  25982. * It has no effect at all on other shapes.
  25983. * It reactivates the mesh normals computation if it was previously frozen.
  25984. * Returns the Mesh.
  25985. */
  25986. Mesh.prototype.unfreezeNormals = function () {
  25987. this._areNormalsFrozen = false;
  25988. return this;
  25989. };
  25990. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  25991. /**
  25992. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  25993. */
  25994. set: function (count) {
  25995. this._overridenInstanceCount = count;
  25996. },
  25997. enumerable: true,
  25998. configurable: true
  25999. });
  26000. // Methods
  26001. Mesh.prototype._preActivate = function () {
  26002. var sceneRenderId = this.getScene().getRenderId();
  26003. if (this._preActivateId === sceneRenderId) {
  26004. return this;
  26005. }
  26006. this._preActivateId = sceneRenderId;
  26007. this._visibleInstances = null;
  26008. return this;
  26009. };
  26010. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  26011. if (this._visibleInstances) {
  26012. this._visibleInstances.intermediateDefaultRenderId = renderId;
  26013. }
  26014. return this;
  26015. };
  26016. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  26017. if (!this._visibleInstances) {
  26018. this._visibleInstances = {};
  26019. this._visibleInstances.defaultRenderId = renderId;
  26020. this._visibleInstances.selfDefaultRenderId = this._renderId;
  26021. }
  26022. if (!this._visibleInstances[renderId]) {
  26023. this._visibleInstances[renderId] = new Array();
  26024. }
  26025. this._visibleInstances[renderId].push(instance);
  26026. return this;
  26027. };
  26028. /**
  26029. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  26030. * This means the mesh underlying bounding box and sphere are recomputed.
  26031. * Returns the Mesh.
  26032. */
  26033. Mesh.prototype.refreshBoundingInfo = function () {
  26034. return this._refreshBoundingInfo(false);
  26035. };
  26036. Mesh.prototype._refreshBoundingInfo = function (applySkeleton) {
  26037. if (this._boundingInfo && this._boundingInfo.isLocked) {
  26038. return this;
  26039. }
  26040. var data = this._getPositionData(applySkeleton);
  26041. if (data) {
  26042. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  26043. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  26044. }
  26045. if (this.subMeshes) {
  26046. for (var index = 0; index < this.subMeshes.length; index++) {
  26047. this.subMeshes[index].refreshBoundingInfo();
  26048. }
  26049. }
  26050. this._updateBoundingInfo();
  26051. return this;
  26052. };
  26053. Mesh.prototype._getPositionData = function (applySkeleton) {
  26054. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  26055. if (data && applySkeleton && this.skeleton) {
  26056. data = BABYLON.Tools.Slice(data);
  26057. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  26058. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  26059. if (matricesWeightsData && matricesIndicesData) {
  26060. var needExtras = this.numBoneInfluencers > 4;
  26061. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  26062. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  26063. var skeletonMatrices = this.skeleton.getTransformMatrices(this);
  26064. var tempVector = BABYLON.Tmp.Vector3[0];
  26065. var finalMatrix = BABYLON.Tmp.Matrix[0];
  26066. var tempMatrix = BABYLON.Tmp.Matrix[1];
  26067. var matWeightIdx = 0;
  26068. for (var index = 0; index < data.length; index += 3, matWeightIdx += 4) {
  26069. finalMatrix.reset();
  26070. var inf;
  26071. var weight;
  26072. for (inf = 0; inf < 4; inf++) {
  26073. weight = matricesWeightsData[matWeightIdx + inf];
  26074. if (weight <= 0)
  26075. break;
  26076. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[matWeightIdx + inf] * 16, weight, tempMatrix);
  26077. finalMatrix.addToSelf(tempMatrix);
  26078. }
  26079. if (needExtras) {
  26080. for (inf = 0; inf < 4; inf++) {
  26081. weight = matricesWeightsExtraData[matWeightIdx + inf];
  26082. if (weight <= 0)
  26083. break;
  26084. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesExtraData[matWeightIdx + inf] * 16, weight, tempMatrix);
  26085. finalMatrix.addToSelf(tempMatrix);
  26086. }
  26087. }
  26088. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(data[index], data[index + 1], data[index + 2], finalMatrix, tempVector);
  26089. tempVector.toArray(data, index);
  26090. }
  26091. }
  26092. }
  26093. return data;
  26094. };
  26095. Mesh.prototype._createGlobalSubMesh = function (force) {
  26096. var totalVertices = this.getTotalVertices();
  26097. if (!totalVertices || !this.getIndices()) {
  26098. return null;
  26099. }
  26100. // Check if we need to recreate the submeshes
  26101. if (this.subMeshes && this.subMeshes.length > 0) {
  26102. var ib = this.getIndices();
  26103. if (!ib) {
  26104. return null;
  26105. }
  26106. var totalIndices = ib.length;
  26107. var needToRecreate = false;
  26108. if (force) {
  26109. needToRecreate = true;
  26110. }
  26111. else {
  26112. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  26113. var submesh = _a[_i];
  26114. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  26115. needToRecreate = true;
  26116. break;
  26117. }
  26118. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  26119. needToRecreate = true;
  26120. break;
  26121. }
  26122. }
  26123. }
  26124. if (!needToRecreate) {
  26125. return this.subMeshes[0];
  26126. }
  26127. }
  26128. this.releaseSubMeshes();
  26129. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  26130. };
  26131. Mesh.prototype.subdivide = function (count) {
  26132. if (count < 1) {
  26133. return;
  26134. }
  26135. var totalIndices = this.getTotalIndices();
  26136. var subdivisionSize = (totalIndices / count) | 0;
  26137. var offset = 0;
  26138. // Ensure that subdivisionSize is a multiple of 3
  26139. while (subdivisionSize % 3 !== 0) {
  26140. subdivisionSize++;
  26141. }
  26142. this.releaseSubMeshes();
  26143. for (var index = 0; index < count; index++) {
  26144. if (offset >= totalIndices) {
  26145. break;
  26146. }
  26147. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  26148. offset += subdivisionSize;
  26149. }
  26150. this.synchronizeInstances();
  26151. };
  26152. /**
  26153. * Sets the vertex data of the mesh geometry for the requested `kind`.
  26154. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  26155. * The `data` are either a numeric array either a Float32Array.
  26156. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  26157. * 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).
  26158. * Note that a new underlying VertexBuffer object is created each call.
  26159. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  26160. *
  26161. * Possible `kind` values :
  26162. * - BABYLON.VertexBuffer.PositionKind
  26163. * - BABYLON.VertexBuffer.UVKind
  26164. * - BABYLON.VertexBuffer.UV2Kind
  26165. * - BABYLON.VertexBuffer.UV3Kind
  26166. * - BABYLON.VertexBuffer.UV4Kind
  26167. * - BABYLON.VertexBuffer.UV5Kind
  26168. * - BABYLON.VertexBuffer.UV6Kind
  26169. * - BABYLON.VertexBuffer.ColorKind
  26170. * - BABYLON.VertexBuffer.MatricesIndicesKind
  26171. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  26172. * - BABYLON.VertexBuffer.MatricesWeightsKind
  26173. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  26174. *
  26175. * Returns the Mesh.
  26176. */
  26177. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  26178. if (updatable === void 0) { updatable = false; }
  26179. if (!this._geometry) {
  26180. var vertexData = new BABYLON.VertexData();
  26181. vertexData.set(data, kind);
  26182. var scene = this.getScene();
  26183. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  26184. }
  26185. else {
  26186. this._geometry.setVerticesData(kind, data, updatable, stride);
  26187. }
  26188. return this;
  26189. };
  26190. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  26191. if (updatable === void 0) { updatable = true; }
  26192. var vb = this.getVertexBuffer(kind);
  26193. if (!vb || vb.isUpdatable() === updatable) {
  26194. return;
  26195. }
  26196. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  26197. };
  26198. /**
  26199. * Sets the mesh VertexBuffer.
  26200. * Returns the Mesh.
  26201. */
  26202. Mesh.prototype.setVerticesBuffer = function (buffer) {
  26203. if (!this._geometry) {
  26204. this._geometry = BABYLON.Geometry.CreateGeometryForMesh(this);
  26205. }
  26206. this._geometry.setVerticesBuffer(buffer);
  26207. return this;
  26208. };
  26209. /**
  26210. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  26211. * If the mesh has no geometry, it is simply returned as it is.
  26212. * The `data` are either a numeric array either a Float32Array.
  26213. * No new underlying VertexBuffer object is created.
  26214. * 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.
  26215. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  26216. *
  26217. * Possible `kind` values :
  26218. * - BABYLON.VertexBuffer.PositionKind
  26219. * - BABYLON.VertexBuffer.UVKind
  26220. * - BABYLON.VertexBuffer.UV2Kind
  26221. * - BABYLON.VertexBuffer.UV3Kind
  26222. * - BABYLON.VertexBuffer.UV4Kind
  26223. * - BABYLON.VertexBuffer.UV5Kind
  26224. * - BABYLON.VertexBuffer.UV6Kind
  26225. * - BABYLON.VertexBuffer.ColorKind
  26226. * - BABYLON.VertexBuffer.MatricesIndicesKind
  26227. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  26228. * - BABYLON.VertexBuffer.MatricesWeightsKind
  26229. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  26230. *
  26231. * Returns the Mesh.
  26232. */
  26233. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  26234. if (!this._geometry) {
  26235. return this;
  26236. }
  26237. if (!makeItUnique) {
  26238. this._geometry.updateVerticesData(kind, data, updateExtends);
  26239. }
  26240. else {
  26241. this.makeGeometryUnique();
  26242. this.updateVerticesData(kind, data, updateExtends, false);
  26243. }
  26244. return this;
  26245. };
  26246. /**
  26247. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  26248. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  26249. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  26250. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  26251. * Returns the Mesh.
  26252. */
  26253. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  26254. if (computeNormals === void 0) { computeNormals = true; }
  26255. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  26256. if (!positions) {
  26257. return this;
  26258. }
  26259. positionFunction(positions);
  26260. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  26261. if (computeNormals) {
  26262. var indices = this.getIndices();
  26263. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  26264. if (!normals) {
  26265. return this;
  26266. }
  26267. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  26268. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  26269. }
  26270. return this;
  26271. };
  26272. /**
  26273. * Creates a un-shared specific occurence of the geometry for the mesh.
  26274. * Returns the Mesh.
  26275. */
  26276. Mesh.prototype.makeGeometryUnique = function () {
  26277. if (!this._geometry) {
  26278. return this;
  26279. }
  26280. var oldGeometry = this._geometry;
  26281. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  26282. oldGeometry.releaseForMesh(this, true);
  26283. geometry.applyToMesh(this);
  26284. return this;
  26285. };
  26286. /**
  26287. * Sets the mesh indices.
  26288. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  26289. * Type is Uint16Array by default unless the mesh has more than 65536 vertices.
  26290. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  26291. * This method creates a new index buffer each call.
  26292. * Returns the Mesh.
  26293. */
  26294. Mesh.prototype.setIndices = function (indices, totalVertices, updatable) {
  26295. if (totalVertices === void 0) { totalVertices = null; }
  26296. if (updatable === void 0) { updatable = false; }
  26297. if (!this._geometry) {
  26298. var vertexData = new BABYLON.VertexData();
  26299. vertexData.indices = indices;
  26300. var scene = this.getScene();
  26301. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  26302. }
  26303. else {
  26304. this._geometry.setIndices(indices, totalVertices, updatable);
  26305. }
  26306. return this;
  26307. };
  26308. /**
  26309. * Update the current index buffer
  26310. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  26311. * Returns the Mesh.
  26312. */
  26313. Mesh.prototype.updateIndices = function (indices, offset) {
  26314. if (!this._geometry) {
  26315. return this;
  26316. }
  26317. this._geometry.updateIndices(indices, offset);
  26318. return this;
  26319. };
  26320. /**
  26321. * Invert the geometry to move from a right handed system to a left handed one.
  26322. * Returns the Mesh.
  26323. */
  26324. Mesh.prototype.toLeftHanded = function () {
  26325. if (!this._geometry) {
  26326. return this;
  26327. }
  26328. this._geometry.toLeftHanded();
  26329. return this;
  26330. };
  26331. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  26332. if (!this._geometry) {
  26333. return this;
  26334. }
  26335. var engine = this.getScene().getEngine();
  26336. // Wireframe
  26337. var indexToBind;
  26338. if (this._unIndexed) {
  26339. indexToBind = null;
  26340. }
  26341. else {
  26342. switch (fillMode) {
  26343. case BABYLON.Material.PointFillMode:
  26344. indexToBind = null;
  26345. break;
  26346. case BABYLON.Material.WireFrameFillMode:
  26347. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  26348. break;
  26349. default:
  26350. case BABYLON.Material.TriangleFillMode:
  26351. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  26352. break;
  26353. }
  26354. }
  26355. // VBOs
  26356. this._geometry._bind(effect, indexToBind);
  26357. return this;
  26358. };
  26359. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount, alternate) {
  26360. if (alternate === void 0) { alternate = false; }
  26361. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  26362. return this;
  26363. }
  26364. this.onBeforeDrawObservable.notifyObservers(this);
  26365. var scene = this.getScene();
  26366. var engine = scene.getEngine();
  26367. if (this._unIndexed || fillMode == BABYLON.Material.PointFillMode) {
  26368. // or triangles as points
  26369. engine.drawArraysType(fillMode, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  26370. }
  26371. else if (fillMode == BABYLON.Material.WireFrameFillMode) {
  26372. // Triangles as wireframe
  26373. engine.drawElementsType(fillMode, 0, subMesh.linesIndexCount, instancesCount);
  26374. }
  26375. else {
  26376. engine.drawElementsType(fillMode, subMesh.indexStart, subMesh.indexCount, instancesCount);
  26377. }
  26378. if (scene._isAlternateRenderingEnabled && !alternate) {
  26379. var effect = subMesh.effect || this._effectiveMaterial.getEffect();
  26380. if (!effect || !scene.activeCamera) {
  26381. return this;
  26382. }
  26383. scene._switchToAlternateCameraConfiguration(true);
  26384. this._effectiveMaterial.bindView(effect);
  26385. this._effectiveMaterial.bindViewProjection(effect);
  26386. engine.setViewport(scene.activeCamera._alternateCamera.viewport);
  26387. this._draw(subMesh, fillMode, instancesCount, true);
  26388. engine.setViewport(scene.activeCamera.viewport);
  26389. scene._switchToAlternateCameraConfiguration(false);
  26390. this._effectiveMaterial.bindView(effect);
  26391. this._effectiveMaterial.bindViewProjection(effect);
  26392. }
  26393. return this;
  26394. };
  26395. /**
  26396. * Registers for this mesh a javascript function called just before the rendering process.
  26397. * This function is passed the current mesh.
  26398. * Return the Mesh.
  26399. */
  26400. Mesh.prototype.registerBeforeRender = function (func) {
  26401. this.onBeforeRenderObservable.add(func);
  26402. return this;
  26403. };
  26404. /**
  26405. * Disposes a previously registered javascript function called before the rendering.
  26406. * This function is passed the current mesh.
  26407. * Returns the Mesh.
  26408. */
  26409. Mesh.prototype.unregisterBeforeRender = function (func) {
  26410. this.onBeforeRenderObservable.removeCallback(func);
  26411. return this;
  26412. };
  26413. /**
  26414. * Registers for this mesh a javascript function called just after the rendering is complete.
  26415. * This function is passed the current mesh.
  26416. * Returns the Mesh.
  26417. */
  26418. Mesh.prototype.registerAfterRender = function (func) {
  26419. this.onAfterRenderObservable.add(func);
  26420. return this;
  26421. };
  26422. /**
  26423. * Disposes a previously registered javascript function called after the rendering.
  26424. * This function is passed the current mesh.
  26425. * Return the Mesh.
  26426. */
  26427. Mesh.prototype.unregisterAfterRender = function (func) {
  26428. this.onAfterRenderObservable.removeCallback(func);
  26429. return this;
  26430. };
  26431. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  26432. var scene = this.getScene();
  26433. this._batchCache.mustReturn = false;
  26434. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  26435. this._batchCache.visibleInstances[subMeshId] = null;
  26436. if (this._visibleInstances) {
  26437. var currentRenderId = scene.getRenderId();
  26438. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  26439. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  26440. var selfRenderId = this._renderId;
  26441. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  26442. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  26443. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  26444. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  26445. }
  26446. var visibleInstancesForSubMesh = this._batchCache.visibleInstances[subMeshId];
  26447. if (visibleInstancesForSubMesh && visibleInstancesForSubMesh.length) {
  26448. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  26449. this._batchCache.mustReturn = true;
  26450. return this._batchCache;
  26451. }
  26452. if (currentRenderId !== selfRenderId) {
  26453. this._batchCache.renderSelf[subMeshId] = false;
  26454. }
  26455. }
  26456. this._renderIdForInstances[subMeshId] = currentRenderId;
  26457. }
  26458. return this._batchCache;
  26459. };
  26460. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  26461. var visibleInstances = batch.visibleInstances[subMesh._id];
  26462. if (!visibleInstances) {
  26463. return this;
  26464. }
  26465. var matricesCount = visibleInstances.length + 1;
  26466. var bufferSize = matricesCount * 16 * 4;
  26467. var currentInstancesBufferSize = this._instancesBufferSize;
  26468. var instancesBuffer = this._instancesBuffer;
  26469. while (this._instancesBufferSize < bufferSize) {
  26470. this._instancesBufferSize *= 2;
  26471. }
  26472. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  26473. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  26474. }
  26475. var offset = 0;
  26476. var instancesCount = 0;
  26477. var world = this.getWorldMatrix();
  26478. if (batch.renderSelf[subMesh._id]) {
  26479. world.copyToArray(this._instancesData, offset);
  26480. offset += 16;
  26481. instancesCount++;
  26482. }
  26483. if (visibleInstances) {
  26484. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  26485. var instance = visibleInstances[instanceIndex];
  26486. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  26487. offset += 16;
  26488. instancesCount++;
  26489. }
  26490. }
  26491. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  26492. if (instancesBuffer) {
  26493. instancesBuffer.dispose();
  26494. }
  26495. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  26496. this._instancesBuffer = instancesBuffer;
  26497. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  26498. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  26499. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  26500. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  26501. }
  26502. else {
  26503. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  26504. }
  26505. this._bind(subMesh, effect, fillMode);
  26506. this._draw(subMesh, fillMode, instancesCount);
  26507. engine.unbindInstanceAttributes();
  26508. return this;
  26509. };
  26510. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  26511. var scene = this.getScene();
  26512. var engine = scene.getEngine();
  26513. if (hardwareInstancedRendering) {
  26514. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  26515. }
  26516. else {
  26517. if (batch.renderSelf[subMesh._id]) {
  26518. // Draw
  26519. if (onBeforeDraw) {
  26520. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  26521. }
  26522. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  26523. }
  26524. var visibleInstancesForSubMesh = batch.visibleInstances[subMesh._id];
  26525. if (visibleInstancesForSubMesh) {
  26526. for (var instanceIndex = 0; instanceIndex < visibleInstancesForSubMesh.length; instanceIndex++) {
  26527. var instance = visibleInstancesForSubMesh[instanceIndex];
  26528. // World
  26529. var world = instance.getWorldMatrix();
  26530. if (onBeforeDraw) {
  26531. onBeforeDraw(true, world, effectiveMaterial);
  26532. }
  26533. // Draw
  26534. this._draw(subMesh, fillMode);
  26535. }
  26536. }
  26537. }
  26538. return this;
  26539. };
  26540. /**
  26541. * Triggers the draw call for the mesh.
  26542. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  26543. * Returns the Mesh.
  26544. */
  26545. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  26546. this.checkOcclusionQuery();
  26547. if (this._isOccluded) {
  26548. return this;
  26549. }
  26550. var scene = this.getScene();
  26551. // Managing instances
  26552. var batch = this._getInstancesRenderList(subMesh._id);
  26553. if (batch.mustReturn) {
  26554. return this;
  26555. }
  26556. // Checking geometry state
  26557. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  26558. return this;
  26559. }
  26560. this.onBeforeRenderObservable.notifyObservers(this);
  26561. var engine = scene.getEngine();
  26562. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  26563. // Material
  26564. var material = subMesh.getMaterial();
  26565. if (!material) {
  26566. return this;
  26567. }
  26568. this._effectiveMaterial = material;
  26569. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  26570. if (!this._effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  26571. return this;
  26572. }
  26573. }
  26574. else if (!this._effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  26575. return this;
  26576. }
  26577. // Alpha mode
  26578. if (enableAlphaMode) {
  26579. engine.setAlphaMode(this._effectiveMaterial.alphaMode);
  26580. }
  26581. // Outline - step 1
  26582. var savedDepthWrite = engine.getDepthWrite();
  26583. if (this.renderOutline) {
  26584. engine.setDepthWrite(false);
  26585. scene.getOutlineRenderer().render(subMesh, batch);
  26586. engine.setDepthWrite(savedDepthWrite);
  26587. }
  26588. var effect;
  26589. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  26590. effect = subMesh.effect;
  26591. }
  26592. else {
  26593. effect = this._effectiveMaterial.getEffect();
  26594. }
  26595. if (!effect) {
  26596. return this;
  26597. }
  26598. var sideOrientation = this.overrideMaterialSideOrientation;
  26599. if (sideOrientation == null) {
  26600. sideOrientation = this._effectiveMaterial.sideOrientation;
  26601. if (this._getWorldMatrixDeterminant() < 0) {
  26602. sideOrientation = (sideOrientation === BABYLON.Material.ClockWiseSideOrientation ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation);
  26603. }
  26604. }
  26605. var reverse = this._effectiveMaterial._preBind(effect, sideOrientation);
  26606. if (this._effectiveMaterial.forceDepthWrite) {
  26607. engine.setDepthWrite(true);
  26608. }
  26609. // Bind
  26610. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : this._effectiveMaterial.fillMode);
  26611. if (!hardwareInstancedRendering) {
  26612. this._bind(subMesh, effect, fillMode);
  26613. }
  26614. var world = this.getWorldMatrix();
  26615. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  26616. this._effectiveMaterial.bindForSubMesh(world, this, subMesh);
  26617. }
  26618. else {
  26619. this._effectiveMaterial.bind(world, this);
  26620. }
  26621. if (!this._effectiveMaterial.backFaceCulling && this._effectiveMaterial.separateCullingPass) {
  26622. engine.setState(true, this._effectiveMaterial.zOffset, false, !reverse);
  26623. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  26624. engine.setState(true, this._effectiveMaterial.zOffset, false, reverse);
  26625. }
  26626. // Draw
  26627. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  26628. // Unbind
  26629. this._effectiveMaterial.unbind();
  26630. // Outline - step 2
  26631. if (this.renderOutline && savedDepthWrite) {
  26632. engine.setDepthWrite(true);
  26633. engine.setColorWrite(false);
  26634. scene.getOutlineRenderer().render(subMesh, batch);
  26635. engine.setColorWrite(true);
  26636. }
  26637. // Overlay
  26638. if (this.renderOverlay) {
  26639. var currentMode = engine.getAlphaMode();
  26640. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  26641. scene.getOutlineRenderer().render(subMesh, batch, true);
  26642. engine.setAlphaMode(currentMode);
  26643. }
  26644. this.onAfterRenderObservable.notifyObservers(this);
  26645. return this;
  26646. };
  26647. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  26648. if (isInstance && effectiveMaterial) {
  26649. effectiveMaterial.bindOnlyWorldMatrix(world);
  26650. }
  26651. };
  26652. /**
  26653. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  26654. */
  26655. Mesh.prototype.getEmittedParticleSystems = function () {
  26656. var results = new Array();
  26657. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  26658. var particleSystem = this.getScene().particleSystems[index];
  26659. if (particleSystem.emitter === this) {
  26660. results.push(particleSystem);
  26661. }
  26662. }
  26663. return results;
  26664. };
  26665. /**
  26666. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  26667. */
  26668. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  26669. var results = new Array();
  26670. var descendants = this.getDescendants();
  26671. descendants.push(this);
  26672. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  26673. var particleSystem = this.getScene().particleSystems[index];
  26674. var emitter = particleSystem.emitter;
  26675. if (emitter.position && descendants.indexOf(emitter) !== -1) {
  26676. results.push(particleSystem);
  26677. }
  26678. }
  26679. return results;
  26680. };
  26681. Mesh.prototype._checkDelayState = function () {
  26682. var scene = this.getScene();
  26683. if (this._geometry) {
  26684. this._geometry.load(scene);
  26685. }
  26686. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  26687. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  26688. this._queueLoad(scene);
  26689. }
  26690. return this;
  26691. };
  26692. Mesh.prototype._queueLoad = function (scene) {
  26693. var _this = this;
  26694. scene._addPendingData(this);
  26695. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  26696. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  26697. if (data instanceof ArrayBuffer) {
  26698. _this._delayLoadingFunction(data, _this);
  26699. }
  26700. else {
  26701. _this._delayLoadingFunction(JSON.parse(data), _this);
  26702. }
  26703. _this.instances.forEach(function (instance) {
  26704. instance._syncSubMeshes();
  26705. });
  26706. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  26707. scene._removePendingData(_this);
  26708. }, function () { }, scene.database, getBinaryData);
  26709. return this;
  26710. };
  26711. /**
  26712. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  26713. */
  26714. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  26715. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  26716. return false;
  26717. }
  26718. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  26719. return false;
  26720. }
  26721. this._checkDelayState();
  26722. return true;
  26723. };
  26724. /**
  26725. * Sets the mesh material by the material or multiMaterial `id` property.
  26726. * The material `id` is a string identifying the material or the multiMaterial.
  26727. * This method returns the Mesh.
  26728. */
  26729. Mesh.prototype.setMaterialByID = function (id) {
  26730. var materials = this.getScene().materials;
  26731. var index;
  26732. for (index = materials.length - 1; index > -1; index--) {
  26733. if (materials[index].id === id) {
  26734. this.material = materials[index];
  26735. return this;
  26736. }
  26737. }
  26738. // Multi
  26739. var multiMaterials = this.getScene().multiMaterials;
  26740. for (index = multiMaterials.length - 1; index > -1; index--) {
  26741. if (multiMaterials[index].id === id) {
  26742. this.material = multiMaterials[index];
  26743. return this;
  26744. }
  26745. }
  26746. return this;
  26747. };
  26748. /**
  26749. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  26750. */
  26751. Mesh.prototype.getAnimatables = function () {
  26752. var results = new Array();
  26753. if (this.material) {
  26754. results.push(this.material);
  26755. }
  26756. if (this.skeleton) {
  26757. results.push(this.skeleton);
  26758. }
  26759. return results;
  26760. };
  26761. /**
  26762. * Modifies the mesh geometry according to the passed transformation matrix.
  26763. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  26764. * The mesh normals are modified accordingly the same transformation.
  26765. * tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  26766. * Note that, under the hood, this method sets a new VertexBuffer each call.
  26767. * Returns the Mesh.
  26768. */
  26769. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  26770. // Position
  26771. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  26772. return this;
  26773. }
  26774. var submeshes = this.subMeshes.splice(0);
  26775. this._resetPointsArrayCache();
  26776. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  26777. var temp = new Array();
  26778. var index;
  26779. for (index = 0; index < data.length; index += 3) {
  26780. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  26781. }
  26782. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  26783. // Normals
  26784. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  26785. return this;
  26786. }
  26787. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  26788. temp = [];
  26789. for (index = 0; index < data.length; index += 3) {
  26790. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  26791. }
  26792. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  26793. // flip faces?
  26794. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  26795. this.flipFaces();
  26796. }
  26797. // Restore submeshes
  26798. this.releaseSubMeshes();
  26799. this.subMeshes = submeshes;
  26800. return this;
  26801. };
  26802. /**
  26803. * Modifies the mesh geometry according to its own current World Matrix.
  26804. * The mesh World Matrix is then reset.
  26805. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  26806. * tuto : tuto : http://doc.babylonjs.com/resources/baking_transformations
  26807. * Note that, under the hood, this method sets a new VertexBuffer each call.
  26808. * Returns the Mesh.
  26809. */
  26810. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  26811. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  26812. this.scaling.copyFromFloats(1, 1, 1);
  26813. this.position.copyFromFloats(0, 0, 0);
  26814. this.rotation.copyFromFloats(0, 0, 0);
  26815. //only if quaternion is already set
  26816. if (this.rotationQuaternion) {
  26817. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  26818. }
  26819. this._worldMatrix = BABYLON.Matrix.Identity();
  26820. return this;
  26821. };
  26822. Object.defineProperty(Mesh.prototype, "_positions", {
  26823. // Cache
  26824. get: function () {
  26825. if (this._geometry) {
  26826. return this._geometry._positions;
  26827. }
  26828. return null;
  26829. },
  26830. enumerable: true,
  26831. configurable: true
  26832. });
  26833. Mesh.prototype._resetPointsArrayCache = function () {
  26834. if (this._geometry) {
  26835. this._geometry._resetPointsArrayCache();
  26836. }
  26837. return this;
  26838. };
  26839. Mesh.prototype._generatePointsArray = function () {
  26840. if (this._geometry) {
  26841. return this._geometry._generatePointsArray();
  26842. }
  26843. return false;
  26844. };
  26845. /**
  26846. * Returns a new Mesh object generated from the current mesh properties.
  26847. * This method must not get confused with createInstance().
  26848. * The parameter `name` is a string, the name given to the new mesh.
  26849. * The optional parameter `newParent` can be any Node object (default `null`).
  26850. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  26851. * 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.
  26852. */
  26853. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  26854. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  26855. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  26856. };
  26857. /**
  26858. * Disposes the Mesh.
  26859. * By default, all the mesh children are also disposed unless the parameter `doNotRecurse` is set to `true`.
  26860. * Returns nothing.
  26861. */
  26862. Mesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  26863. var _this = this;
  26864. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  26865. this.morphTargetManager = null;
  26866. if (this._geometry) {
  26867. this._geometry.releaseForMesh(this, true);
  26868. }
  26869. // Sources
  26870. var meshes = this.getScene().meshes;
  26871. meshes.forEach(function (abstractMesh) {
  26872. var mesh = abstractMesh;
  26873. if (mesh._source && mesh._source === _this) {
  26874. mesh._source = null;
  26875. }
  26876. });
  26877. this._source = null;
  26878. // Instances
  26879. if (this._instancesBuffer) {
  26880. this._instancesBuffer.dispose();
  26881. this._instancesBuffer = null;
  26882. }
  26883. while (this.instances.length) {
  26884. this.instances[0].dispose();
  26885. }
  26886. // Highlight layers.
  26887. var highlightLayers = this.getScene().highlightLayers;
  26888. for (var i = 0; i < highlightLayers.length; i++) {
  26889. var highlightLayer = highlightLayers[i];
  26890. if (highlightLayer) {
  26891. highlightLayer.removeMesh(this);
  26892. highlightLayer.removeExcludedMesh(this);
  26893. }
  26894. }
  26895. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  26896. };
  26897. /**
  26898. * Modifies the mesh geometry according to a displacement map.
  26899. * 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.
  26900. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  26901. * This method returns nothing.
  26902. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  26903. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  26904. * 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.
  26905. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  26906. * The parameter `uvScale` is an optional vector2 used to scale UV.
  26907. *
  26908. * Returns the Mesh.
  26909. */
  26910. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale) {
  26911. var _this = this;
  26912. var scene = this.getScene();
  26913. var onload = function (img) {
  26914. // Getting height map data
  26915. var canvas = document.createElement("canvas");
  26916. var context = canvas.getContext("2d");
  26917. var heightMapWidth = img.width;
  26918. var heightMapHeight = img.height;
  26919. canvas.width = heightMapWidth;
  26920. canvas.height = heightMapHeight;
  26921. context.drawImage(img, 0, 0);
  26922. // Create VertexData from map data
  26923. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  26924. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  26925. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale);
  26926. //execute success callback, if set
  26927. if (onSuccess) {
  26928. onSuccess(_this);
  26929. }
  26930. };
  26931. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  26932. return this;
  26933. };
  26934. /**
  26935. * Modifies the mesh geometry according to a displacementMap buffer.
  26936. * 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.
  26937. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  26938. * This method returns nothing.
  26939. * 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.
  26940. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  26941. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  26942. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  26943. * The parameter `uvScale` is an optional vector2 used to scale UV.
  26944. *
  26945. * Returns the Mesh.
  26946. */
  26947. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale) {
  26948. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  26949. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  26950. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  26951. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  26952. return this;
  26953. }
  26954. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  26955. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  26956. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  26957. var position = BABYLON.Vector3.Zero();
  26958. var normal = BABYLON.Vector3.Zero();
  26959. var uv = BABYLON.Vector2.Zero();
  26960. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  26961. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  26962. for (var index = 0; index < positions.length; index += 3) {
  26963. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  26964. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  26965. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  26966. // Compute height
  26967. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  26968. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  26969. var pos = (u + v * heightMapWidth) * 4;
  26970. var r = buffer[pos] / 255.0;
  26971. var g = buffer[pos + 1] / 255.0;
  26972. var b = buffer[pos + 2] / 255.0;
  26973. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  26974. normal.normalize();
  26975. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  26976. position = position.add(normal);
  26977. position.toArray(positions, index);
  26978. }
  26979. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  26980. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  26981. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  26982. return this;
  26983. };
  26984. /**
  26985. * Modify the mesh to get a flat shading rendering.
  26986. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  26987. * This method returns the Mesh.
  26988. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  26989. */
  26990. Mesh.prototype.convertToFlatShadedMesh = function () {
  26991. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  26992. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  26993. var kinds = this.getVerticesDataKinds();
  26994. var vbs = {};
  26995. var data = {};
  26996. var newdata = {};
  26997. var updatableNormals = false;
  26998. var kindIndex;
  26999. var kind;
  27000. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  27001. kind = kinds[kindIndex];
  27002. var vertexBuffer = this.getVertexBuffer(kind);
  27003. if (kind === BABYLON.VertexBuffer.NormalKind) {
  27004. updatableNormals = vertexBuffer.isUpdatable();
  27005. kinds.splice(kindIndex, 1);
  27006. kindIndex--;
  27007. continue;
  27008. }
  27009. vbs[kind] = vertexBuffer;
  27010. data[kind] = vbs[kind].getData();
  27011. newdata[kind] = [];
  27012. }
  27013. // Save previous submeshes
  27014. var previousSubmeshes = this.subMeshes.slice(0);
  27015. var indices = this.getIndices();
  27016. var totalIndices = this.getTotalIndices();
  27017. // Generating unique vertices per face
  27018. var index;
  27019. for (index = 0; index < totalIndices; index++) {
  27020. var vertexIndex = indices[index];
  27021. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  27022. kind = kinds[kindIndex];
  27023. var stride = vbs[kind].getStrideSize();
  27024. for (var offset = 0; offset < stride; offset++) {
  27025. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  27026. }
  27027. }
  27028. }
  27029. // Updating faces & normal
  27030. var normals = [];
  27031. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  27032. for (index = 0; index < totalIndices; index += 3) {
  27033. indices[index] = index;
  27034. indices[index + 1] = index + 1;
  27035. indices[index + 2] = index + 2;
  27036. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  27037. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  27038. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  27039. var p1p2 = p1.subtract(p2);
  27040. var p3p2 = p3.subtract(p2);
  27041. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  27042. // Store same normals for every vertex
  27043. for (var localIndex = 0; localIndex < 3; localIndex++) {
  27044. normals.push(normal.x);
  27045. normals.push(normal.y);
  27046. normals.push(normal.z);
  27047. }
  27048. }
  27049. this.setIndices(indices);
  27050. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  27051. // Updating vertex buffers
  27052. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  27053. kind = kinds[kindIndex];
  27054. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  27055. }
  27056. // Updating submeshes
  27057. this.releaseSubMeshes();
  27058. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  27059. var previousOne = previousSubmeshes[submeshIndex];
  27060. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  27061. }
  27062. this.synchronizeInstances();
  27063. return this;
  27064. };
  27065. /**
  27066. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  27067. * In other words, more vertices, no more indices and a single bigger VBO.
  27068. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  27069. * Returns the Mesh.
  27070. */
  27071. Mesh.prototype.convertToUnIndexedMesh = function () {
  27072. /// <summary>Remove indices by unfolding faces into buffers</summary>
  27073. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  27074. var kinds = this.getVerticesDataKinds();
  27075. var vbs = {};
  27076. var data = {};
  27077. var newdata = {};
  27078. var kindIndex;
  27079. var kind;
  27080. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  27081. kind = kinds[kindIndex];
  27082. var vertexBuffer = this.getVertexBuffer(kind);
  27083. vbs[kind] = vertexBuffer;
  27084. data[kind] = vbs[kind].getData();
  27085. newdata[kind] = [];
  27086. }
  27087. // Save previous submeshes
  27088. var previousSubmeshes = this.subMeshes.slice(0);
  27089. var indices = this.getIndices();
  27090. var totalIndices = this.getTotalIndices();
  27091. // Generating unique vertices per face
  27092. var index;
  27093. for (index = 0; index < totalIndices; index++) {
  27094. var vertexIndex = indices[index];
  27095. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  27096. kind = kinds[kindIndex];
  27097. var stride = vbs[kind].getStrideSize();
  27098. for (var offset = 0; offset < stride; offset++) {
  27099. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  27100. }
  27101. }
  27102. }
  27103. // Updating indices
  27104. for (index = 0; index < totalIndices; index += 3) {
  27105. indices[index] = index;
  27106. indices[index + 1] = index + 1;
  27107. indices[index + 2] = index + 2;
  27108. }
  27109. this.setIndices(indices);
  27110. // Updating vertex buffers
  27111. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  27112. kind = kinds[kindIndex];
  27113. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  27114. }
  27115. // Updating submeshes
  27116. this.releaseSubMeshes();
  27117. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  27118. var previousOne = previousSubmeshes[submeshIndex];
  27119. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  27120. }
  27121. this._unIndexed = true;
  27122. this.synchronizeInstances();
  27123. return this;
  27124. };
  27125. /**
  27126. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  27127. * This method returns the Mesh.
  27128. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  27129. */
  27130. Mesh.prototype.flipFaces = function (flipNormals) {
  27131. if (flipNormals === void 0) { flipNormals = false; }
  27132. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  27133. var i;
  27134. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) && vertex_data.normals) {
  27135. for (i = 0; i < vertex_data.normals.length; i++) {
  27136. vertex_data.normals[i] *= -1;
  27137. }
  27138. }
  27139. if (vertex_data.indices) {
  27140. var temp;
  27141. for (i = 0; i < vertex_data.indices.length; i += 3) {
  27142. // reassign indices
  27143. temp = vertex_data.indices[i + 1];
  27144. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  27145. vertex_data.indices[i + 2] = temp;
  27146. }
  27147. }
  27148. vertex_data.applyToMesh(this);
  27149. return this;
  27150. };
  27151. // Instances
  27152. /**
  27153. * Creates a new InstancedMesh object from the mesh model.
  27154. * An instance shares the same properties and the same material than its model.
  27155. * Only these properties of each instance can then be set individually :
  27156. * - position
  27157. * - rotation
  27158. * - rotationQuaternion
  27159. * - setPivotMatrix
  27160. * - scaling
  27161. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  27162. * Warning : this method is not supported for Line mesh and LineSystem
  27163. */
  27164. Mesh.prototype.createInstance = function (name) {
  27165. return new BABYLON.InstancedMesh(name, this);
  27166. };
  27167. /**
  27168. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  27169. * After this call, all the mesh instances have the same submeshes than the current mesh.
  27170. * This method returns the Mesh.
  27171. */
  27172. Mesh.prototype.synchronizeInstances = function () {
  27173. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  27174. var instance = this.instances[instanceIndex];
  27175. instance._syncSubMeshes();
  27176. }
  27177. return this;
  27178. };
  27179. /**
  27180. * Simplify the mesh according to the given array of settings.
  27181. * Function will return immediately and will simplify async. It returns the Mesh.
  27182. * @param settings a collection of simplification settings.
  27183. * @param parallelProcessing should all levels calculate parallel or one after the other.
  27184. * @param type the type of simplification to run.
  27185. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  27186. */
  27187. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  27188. if (parallelProcessing === void 0) { parallelProcessing = true; }
  27189. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  27190. this.getScene().simplificationQueue.addTask({
  27191. settings: settings,
  27192. parallelProcessing: parallelProcessing,
  27193. mesh: this,
  27194. simplificationType: simplificationType,
  27195. successCallback: successCallback
  27196. });
  27197. return this;
  27198. };
  27199. /**
  27200. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  27201. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  27202. * This should be used together with the simplification to avoid disappearing triangles.
  27203. * Returns the Mesh.
  27204. * @param successCallback an optional success callback to be called after the optimization finished.
  27205. */
  27206. Mesh.prototype.optimizeIndices = function (successCallback) {
  27207. var _this = this;
  27208. var indices = this.getIndices();
  27209. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  27210. if (!positions || !indices) {
  27211. return this;
  27212. }
  27213. var vectorPositions = new Array();
  27214. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  27215. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  27216. }
  27217. var dupes = new Array();
  27218. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  27219. var realPos = vectorPositions.length - 1 - iteration;
  27220. var testedPosition = vectorPositions[realPos];
  27221. for (var j = 0; j < realPos; ++j) {
  27222. var againstPosition = vectorPositions[j];
  27223. if (testedPosition.equals(againstPosition)) {
  27224. dupes[realPos] = j;
  27225. break;
  27226. }
  27227. }
  27228. }, function () {
  27229. for (var i = 0; i < indices.length; ++i) {
  27230. indices[i] = dupes[indices[i]] || indices[i];
  27231. }
  27232. //indices are now reordered
  27233. var originalSubMeshes = _this.subMeshes.slice(0);
  27234. _this.setIndices(indices);
  27235. _this.subMeshes = originalSubMeshes;
  27236. if (successCallback) {
  27237. successCallback(_this);
  27238. }
  27239. });
  27240. return this;
  27241. };
  27242. Mesh.prototype.serialize = function (serializationObject) {
  27243. serializationObject.name = this.name;
  27244. serializationObject.id = this.id;
  27245. serializationObject.type = this.getClassName();
  27246. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  27247. serializationObject.tags = BABYLON.Tags.GetTags(this);
  27248. }
  27249. serializationObject.position = this.position.asArray();
  27250. if (this.rotationQuaternion) {
  27251. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  27252. }
  27253. else if (this.rotation) {
  27254. serializationObject.rotation = this.rotation.asArray();
  27255. }
  27256. serializationObject.scaling = this.scaling.asArray();
  27257. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  27258. serializationObject.isEnabled = this.isEnabled(false);
  27259. serializationObject.isVisible = this.isVisible;
  27260. serializationObject.infiniteDistance = this.infiniteDistance;
  27261. serializationObject.pickable = this.isPickable;
  27262. serializationObject.receiveShadows = this.receiveShadows;
  27263. serializationObject.billboardMode = this.billboardMode;
  27264. serializationObject.visibility = this.visibility;
  27265. serializationObject.checkCollisions = this.checkCollisions;
  27266. serializationObject.isBlocker = this.isBlocker;
  27267. // Parent
  27268. if (this.parent) {
  27269. serializationObject.parentId = this.parent.id;
  27270. }
  27271. // Geometry
  27272. serializationObject.isUnIndexed = this.isUnIndexed;
  27273. var geometry = this._geometry;
  27274. if (geometry) {
  27275. var geometryId = geometry.id;
  27276. serializationObject.geometryId = geometryId;
  27277. // SubMeshes
  27278. serializationObject.subMeshes = [];
  27279. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  27280. var subMesh = this.subMeshes[subIndex];
  27281. serializationObject.subMeshes.push({
  27282. materialIndex: subMesh.materialIndex,
  27283. verticesStart: subMesh.verticesStart,
  27284. verticesCount: subMesh.verticesCount,
  27285. indexStart: subMesh.indexStart,
  27286. indexCount: subMesh.indexCount
  27287. });
  27288. }
  27289. }
  27290. // Material
  27291. if (this.material) {
  27292. serializationObject.materialId = this.material.id;
  27293. }
  27294. else {
  27295. this.material = null;
  27296. }
  27297. // Morph targets
  27298. if (this.morphTargetManager) {
  27299. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  27300. }
  27301. // Skeleton
  27302. if (this.skeleton) {
  27303. serializationObject.skeletonId = this.skeleton.id;
  27304. }
  27305. // Physics
  27306. //TODO implement correct serialization for physics impostors.
  27307. var impostor = this.getPhysicsImpostor();
  27308. if (impostor) {
  27309. serializationObject.physicsMass = impostor.getParam("mass");
  27310. serializationObject.physicsFriction = impostor.getParam("friction");
  27311. serializationObject.physicsRestitution = impostor.getParam("mass");
  27312. serializationObject.physicsImpostor = impostor.type;
  27313. }
  27314. // Metadata
  27315. if (this.metadata) {
  27316. serializationObject.metadata = this.metadata;
  27317. }
  27318. // Instances
  27319. serializationObject.instances = [];
  27320. for (var index = 0; index < this.instances.length; index++) {
  27321. var instance = this.instances[index];
  27322. var serializationInstance = {
  27323. name: instance.name,
  27324. id: instance.id,
  27325. position: instance.position.asArray(),
  27326. scaling: instance.scaling.asArray()
  27327. };
  27328. if (instance.rotationQuaternion) {
  27329. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  27330. }
  27331. else if (instance.rotation) {
  27332. serializationInstance.rotation = instance.rotation.asArray();
  27333. }
  27334. serializationObject.instances.push(serializationInstance);
  27335. // Animations
  27336. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  27337. serializationInstance.ranges = instance.serializeAnimationRanges();
  27338. }
  27339. //
  27340. // Animations
  27341. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  27342. serializationObject.ranges = this.serializeAnimationRanges();
  27343. // Layer mask
  27344. serializationObject.layerMask = this.layerMask;
  27345. // Alpha
  27346. serializationObject.alphaIndex = this.alphaIndex;
  27347. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  27348. // Overlay
  27349. serializationObject.overlayAlpha = this.overlayAlpha;
  27350. serializationObject.overlayColor = this.overlayColor.asArray();
  27351. serializationObject.renderOverlay = this.renderOverlay;
  27352. // Fog
  27353. serializationObject.applyFog = this.applyFog;
  27354. // Action Manager
  27355. if (this.actionManager) {
  27356. serializationObject.actions = this.actionManager.serialize(this.name);
  27357. }
  27358. };
  27359. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  27360. if (!this.geometry) {
  27361. return;
  27362. }
  27363. this._markSubMeshesAsAttributesDirty();
  27364. var morphTargetManager = this._morphTargetManager;
  27365. if (morphTargetManager && morphTargetManager.vertexCount) {
  27366. if (morphTargetManager.vertexCount !== this.getTotalVertices()) {
  27367. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  27368. this.morphTargetManager = null;
  27369. return;
  27370. }
  27371. for (var index = 0; index < morphTargetManager.numInfluencers; index++) {
  27372. var morphTarget = morphTargetManager.getActiveTarget(index);
  27373. var positions = morphTarget.getPositions();
  27374. if (!positions) {
  27375. BABYLON.Tools.Error("Invalid morph target. Target must have positions.");
  27376. return;
  27377. }
  27378. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, positions, false, 3);
  27379. var normals = morphTarget.getNormals();
  27380. if (normals) {
  27381. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, normals, false, 3);
  27382. }
  27383. var tangents = morphTarget.getTangents();
  27384. if (tangents) {
  27385. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, tangents, false, 3);
  27386. }
  27387. }
  27388. }
  27389. else {
  27390. var index = 0;
  27391. // Positions
  27392. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  27393. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  27394. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  27395. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  27396. }
  27397. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  27398. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  27399. }
  27400. index++;
  27401. }
  27402. }
  27403. };
  27404. // Statics
  27405. /**
  27406. * Returns a new Mesh object parsed from the source provided.
  27407. * The parameter `parsedMesh` is the source.
  27408. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  27409. */
  27410. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  27411. var mesh;
  27412. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  27413. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  27414. }
  27415. else {
  27416. mesh = new Mesh(parsedMesh.name, scene);
  27417. }
  27418. mesh.id = parsedMesh.id;
  27419. if (BABYLON.Tags) {
  27420. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  27421. }
  27422. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  27423. if (parsedMesh.metadata !== undefined) {
  27424. mesh.metadata = parsedMesh.metadata;
  27425. }
  27426. if (parsedMesh.rotationQuaternion) {
  27427. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  27428. }
  27429. else if (parsedMesh.rotation) {
  27430. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  27431. }
  27432. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  27433. if (parsedMesh.localMatrix) {
  27434. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  27435. }
  27436. else if (parsedMesh.pivotMatrix) {
  27437. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  27438. }
  27439. mesh.setEnabled(parsedMesh.isEnabled);
  27440. mesh.isVisible = parsedMesh.isVisible;
  27441. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  27442. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  27443. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  27444. if (parsedMesh.applyFog !== undefined) {
  27445. mesh.applyFog = parsedMesh.applyFog;
  27446. }
  27447. if (parsedMesh.pickable !== undefined) {
  27448. mesh.isPickable = parsedMesh.pickable;
  27449. }
  27450. if (parsedMesh.alphaIndex !== undefined) {
  27451. mesh.alphaIndex = parsedMesh.alphaIndex;
  27452. }
  27453. mesh.receiveShadows = parsedMesh.receiveShadows;
  27454. mesh.billboardMode = parsedMesh.billboardMode;
  27455. if (parsedMesh.visibility !== undefined) {
  27456. mesh.visibility = parsedMesh.visibility;
  27457. }
  27458. mesh.checkCollisions = parsedMesh.checkCollisions;
  27459. if (parsedMesh.isBlocker !== undefined) {
  27460. mesh.isBlocker = parsedMesh.isBlocker;
  27461. }
  27462. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  27463. // freezeWorldMatrix
  27464. if (parsedMesh.freezeWorldMatrix) {
  27465. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  27466. }
  27467. // Parent
  27468. if (parsedMesh.parentId) {
  27469. mesh._waitingParentId = parsedMesh.parentId;
  27470. }
  27471. // Actions
  27472. if (parsedMesh.actions !== undefined) {
  27473. mesh._waitingActions = parsedMesh.actions;
  27474. }
  27475. // Overlay
  27476. if (parsedMesh.overlayAlpha !== undefined) {
  27477. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  27478. }
  27479. if (parsedMesh.overlayColor !== undefined) {
  27480. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  27481. }
  27482. if (parsedMesh.renderOverlay !== undefined) {
  27483. mesh.renderOverlay = parsedMesh.renderOverlay;
  27484. }
  27485. // Geometry
  27486. mesh.isUnIndexed = !!parsedMesh.isUnIndexed;
  27487. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  27488. if (parsedMesh.delayLoadingFile) {
  27489. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  27490. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  27491. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  27492. if (parsedMesh._binaryInfo) {
  27493. mesh._binaryInfo = parsedMesh._binaryInfo;
  27494. }
  27495. mesh._delayInfo = [];
  27496. if (parsedMesh.hasUVs) {
  27497. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  27498. }
  27499. if (parsedMesh.hasUVs2) {
  27500. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  27501. }
  27502. if (parsedMesh.hasUVs3) {
  27503. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  27504. }
  27505. if (parsedMesh.hasUVs4) {
  27506. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  27507. }
  27508. if (parsedMesh.hasUVs5) {
  27509. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  27510. }
  27511. if (parsedMesh.hasUVs6) {
  27512. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  27513. }
  27514. if (parsedMesh.hasColors) {
  27515. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  27516. }
  27517. if (parsedMesh.hasMatricesIndices) {
  27518. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  27519. }
  27520. if (parsedMesh.hasMatricesWeights) {
  27521. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  27522. }
  27523. mesh._delayLoadingFunction = BABYLON.Geometry._ImportGeometry;
  27524. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  27525. mesh._checkDelayState();
  27526. }
  27527. }
  27528. else {
  27529. BABYLON.Geometry._ImportGeometry(parsedMesh, mesh);
  27530. }
  27531. // Material
  27532. if (parsedMesh.materialId) {
  27533. mesh.setMaterialByID(parsedMesh.materialId);
  27534. }
  27535. else {
  27536. mesh.material = null;
  27537. }
  27538. // Morph targets
  27539. if (parsedMesh.morphTargetManagerId > -1) {
  27540. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  27541. }
  27542. // Skeleton
  27543. if (parsedMesh.skeletonId > -1) {
  27544. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  27545. if (parsedMesh.numBoneInfluencers) {
  27546. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  27547. }
  27548. }
  27549. // Animations
  27550. if (parsedMesh.animations) {
  27551. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  27552. var parsedAnimation = parsedMesh.animations[animationIndex];
  27553. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  27554. }
  27555. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  27556. }
  27557. if (parsedMesh.autoAnimate) {
  27558. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  27559. }
  27560. // Layer Mask
  27561. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  27562. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  27563. }
  27564. else {
  27565. mesh.layerMask = 0x0FFFFFFF;
  27566. }
  27567. // Physics
  27568. if (parsedMesh.physicsImpostor) {
  27569. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  27570. mass: parsedMesh.physicsMass,
  27571. friction: parsedMesh.physicsFriction,
  27572. restitution: parsedMesh.physicsRestitution
  27573. }, scene);
  27574. }
  27575. // Instances
  27576. if (parsedMesh.instances) {
  27577. for (var index = 0; index < parsedMesh.instances.length; index++) {
  27578. var parsedInstance = parsedMesh.instances[index];
  27579. var instance = mesh.createInstance(parsedInstance.name);
  27580. if (parsedInstance.id) {
  27581. instance.id = parsedInstance.id;
  27582. }
  27583. if (BABYLON.Tags) {
  27584. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  27585. }
  27586. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  27587. if (parsedInstance.parentId) {
  27588. instance._waitingParentId = parsedInstance.parentId;
  27589. }
  27590. if (parsedInstance.rotationQuaternion) {
  27591. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  27592. }
  27593. else if (parsedInstance.rotation) {
  27594. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  27595. }
  27596. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  27597. instance.checkCollisions = mesh.checkCollisions;
  27598. if (parsedMesh.animations) {
  27599. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  27600. parsedAnimation = parsedMesh.animations[animationIndex];
  27601. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  27602. }
  27603. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  27604. }
  27605. }
  27606. }
  27607. return mesh;
  27608. };
  27609. /**
  27610. * Creates a ribbon mesh.
  27611. * Please consider using the same method from the MeshBuilder class instead.
  27612. * 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.
  27613. *
  27614. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  27615. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  27616. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  27617. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  27618. * 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.
  27619. * 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.
  27620. * 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
  27621. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  27622. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  27623. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27624. */
  27625. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  27626. if (closeArray === void 0) { closeArray = false; }
  27627. if (updatable === void 0) { updatable = false; }
  27628. return BABYLON.MeshBuilder.CreateRibbon(name, {
  27629. pathArray: pathArray,
  27630. closeArray: closeArray,
  27631. closePath: closePath,
  27632. offset: offset,
  27633. updatable: updatable,
  27634. sideOrientation: sideOrientation,
  27635. instance: instance
  27636. }, scene);
  27637. };
  27638. /**
  27639. * Creates a plane polygonal mesh. By default, this is a disc.
  27640. * Please consider using the same method from the MeshBuilder class instead.
  27641. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  27642. * 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.
  27643. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  27644. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  27645. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27646. */
  27647. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  27648. if (scene === void 0) { scene = null; }
  27649. var options = {
  27650. radius: radius,
  27651. tessellation: tessellation,
  27652. sideOrientation: sideOrientation,
  27653. updatable: updatable
  27654. };
  27655. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  27656. };
  27657. /**
  27658. * Creates a box mesh.
  27659. * Please consider using the same method from the MeshBuilder class instead.
  27660. * The parameter `size` sets the size (float) of each box side (default 1).
  27661. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  27662. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  27663. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27664. */
  27665. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  27666. if (scene === void 0) { scene = null; }
  27667. var options = {
  27668. size: size,
  27669. sideOrientation: sideOrientation,
  27670. updatable: updatable
  27671. };
  27672. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  27673. };
  27674. /**
  27675. * Creates a sphere mesh.
  27676. * Please consider using the same method from the MeshBuilder class instead.
  27677. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  27678. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  27679. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  27680. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  27681. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27682. */
  27683. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  27684. var options = {
  27685. segments: segments,
  27686. diameterX: diameter,
  27687. diameterY: diameter,
  27688. diameterZ: diameter,
  27689. sideOrientation: sideOrientation,
  27690. updatable: updatable
  27691. };
  27692. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  27693. };
  27694. /**
  27695. * Creates a cylinder or a cone mesh.
  27696. * Please consider using the same method from the MeshBuilder class instead.
  27697. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  27698. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  27699. * 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.
  27700. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  27701. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  27702. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  27703. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  27704. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27705. */
  27706. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  27707. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  27708. if (scene !== undefined) {
  27709. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  27710. updatable = scene;
  27711. }
  27712. scene = subdivisions;
  27713. subdivisions = 1;
  27714. }
  27715. var options = {
  27716. height: height,
  27717. diameterTop: diameterTop,
  27718. diameterBottom: diameterBottom,
  27719. tessellation: tessellation,
  27720. subdivisions: subdivisions,
  27721. sideOrientation: sideOrientation,
  27722. updatable: updatable
  27723. };
  27724. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  27725. };
  27726. // Torus (Code from SharpDX.org)
  27727. /**
  27728. * Creates a torus mesh.
  27729. * Please consider using the same method from the MeshBuilder class instead.
  27730. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  27731. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  27732. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  27733. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  27734. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  27735. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27736. */
  27737. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  27738. var options = {
  27739. diameter: diameter,
  27740. thickness: thickness,
  27741. tessellation: tessellation,
  27742. sideOrientation: sideOrientation,
  27743. updatable: updatable
  27744. };
  27745. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  27746. };
  27747. /**
  27748. * Creates a torus knot mesh.
  27749. * Please consider using the same method from the MeshBuilder class instead.
  27750. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  27751. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  27752. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  27753. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  27754. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  27755. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  27756. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27757. */
  27758. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  27759. var options = {
  27760. radius: radius,
  27761. tube: tube,
  27762. radialSegments: radialSegments,
  27763. tubularSegments: tubularSegments,
  27764. p: p,
  27765. q: q,
  27766. sideOrientation: sideOrientation,
  27767. updatable: updatable
  27768. };
  27769. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  27770. };
  27771. /**
  27772. * Creates a line mesh.
  27773. * Please consider using the same method from the MeshBuilder class instead.
  27774. * 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.
  27775. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  27776. * The parameter `points` is an array successive Vector3.
  27777. * 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
  27778. * When updating an instance, remember that only point positions can change, not the number of points.
  27779. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27780. */
  27781. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  27782. if (scene === void 0) { scene = null; }
  27783. if (updatable === void 0) { updatable = false; }
  27784. if (instance === void 0) { instance = null; }
  27785. var options = {
  27786. points: points,
  27787. updatable: updatable,
  27788. instance: instance
  27789. };
  27790. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  27791. };
  27792. /**
  27793. * Creates a dashed line mesh.
  27794. * Please consider using the same method from the MeshBuilder class instead.
  27795. * 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.
  27796. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  27797. * The parameter `points` is an array successive Vector3.
  27798. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  27799. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  27800. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  27801. * 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
  27802. * When updating an instance, remember that only point positions can change, not the number of points.
  27803. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27804. */
  27805. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  27806. if (scene === void 0) { scene = null; }
  27807. var options = {
  27808. points: points,
  27809. dashSize: dashSize,
  27810. gapSize: gapSize,
  27811. dashNb: dashNb,
  27812. updatable: updatable,
  27813. instance: instance
  27814. };
  27815. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  27816. };
  27817. /**
  27818. * Creates a polygon mesh.
  27819. * Please consider using the same method from the MeshBuilder class instead.
  27820. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  27821. * 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.
  27822. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  27823. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27824. * Remember you can only change the shape positions, not their number when updating a polygon.
  27825. */
  27826. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  27827. var options = {
  27828. shape: shape,
  27829. holes: holes,
  27830. updatable: updatable,
  27831. sideOrientation: sideOrientation
  27832. };
  27833. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  27834. };
  27835. /**
  27836. * Creates an extruded polygon mesh, with depth in the Y direction.
  27837. * Please consider using the same method from the MeshBuilder class instead.
  27838. */
  27839. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  27840. var options = {
  27841. shape: shape,
  27842. holes: holes,
  27843. depth: depth,
  27844. updatable: updatable,
  27845. sideOrientation: sideOrientation
  27846. };
  27847. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  27848. };
  27849. /**
  27850. * Creates an extruded shape mesh.
  27851. * 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.
  27852. * Please consider using the same method from the MeshBuilder class instead.
  27853. *
  27854. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  27855. * 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
  27856. * extruded along the Z axis.
  27857. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  27858. * 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.
  27859. * The parameter `scale` (float, default 1) is the value to scale the shape.
  27860. * 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
  27861. * 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
  27862. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  27863. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  27864. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  27865. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27866. */
  27867. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  27868. if (scene === void 0) { scene = null; }
  27869. var options = {
  27870. shape: shape,
  27871. path: path,
  27872. scale: scale,
  27873. rotation: rotation,
  27874. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  27875. sideOrientation: sideOrientation,
  27876. instance: instance,
  27877. updatable: updatable
  27878. };
  27879. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  27880. };
  27881. /**
  27882. * Creates an custom extruded shape mesh.
  27883. * 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.
  27884. * Please consider using the same method from the MeshBuilder class instead.
  27885. *
  27886. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  27887. * 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
  27888. * extruded along the Z axis.
  27889. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  27890. * 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
  27891. * and the distance of this point from the begining of the path :
  27892. * ```javascript
  27893. * var rotationFunction = function(i, distance) {
  27894. * // do things
  27895. * return rotationValue; }
  27896. * ```
  27897. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  27898. * 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
  27899. * and the distance of this point from the begining of the path :
  27900. * ```javascript
  27901. * var scaleFunction = function(i, distance) {
  27902. * // do things
  27903. * return scaleValue;}
  27904. * ```
  27905. * It must returns a float value that will be the scale value applied to the shape on each path point.
  27906. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  27907. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  27908. * 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
  27909. * 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
  27910. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  27911. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  27912. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  27913. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27914. */
  27915. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  27916. var options = {
  27917. shape: shape,
  27918. path: path,
  27919. scaleFunction: scaleFunction,
  27920. rotationFunction: rotationFunction,
  27921. ribbonCloseArray: ribbonCloseArray,
  27922. ribbonClosePath: ribbonClosePath,
  27923. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  27924. sideOrientation: sideOrientation,
  27925. instance: instance,
  27926. updatable: updatable
  27927. };
  27928. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  27929. };
  27930. /**
  27931. * Creates lathe mesh.
  27932. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  27933. * Please consider using the same method from the MeshBuilder class instead.
  27934. * 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
  27935. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  27936. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  27937. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  27938. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  27939. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  27940. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27941. */
  27942. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  27943. var options = {
  27944. shape: shape,
  27945. radius: radius,
  27946. tessellation: tessellation,
  27947. sideOrientation: sideOrientation,
  27948. updatable: updatable
  27949. };
  27950. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  27951. };
  27952. /**
  27953. * Creates a plane mesh.
  27954. * Please consider using the same method from the MeshBuilder class instead.
  27955. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  27956. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  27957. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  27958. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27959. */
  27960. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  27961. var options = {
  27962. size: size,
  27963. width: size,
  27964. height: size,
  27965. sideOrientation: sideOrientation,
  27966. updatable: updatable
  27967. };
  27968. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  27969. };
  27970. /**
  27971. * Creates a ground mesh.
  27972. * Please consider using the same method from the MeshBuilder class instead.
  27973. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  27974. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  27975. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27976. */
  27977. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  27978. var options = {
  27979. width: width,
  27980. height: height,
  27981. subdivisions: subdivisions,
  27982. updatable: updatable
  27983. };
  27984. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  27985. };
  27986. /**
  27987. * Creates a tiled ground mesh.
  27988. * Please consider using the same method from the MeshBuilder class instead.
  27989. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  27990. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  27991. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  27992. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  27993. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  27994. * numbers of subdivisions on the ground width and height of each tile.
  27995. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27996. */
  27997. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  27998. var options = {
  27999. xmin: xmin,
  28000. zmin: zmin,
  28001. xmax: xmax,
  28002. zmax: zmax,
  28003. subdivisions: subdivisions,
  28004. precision: precision,
  28005. updatable: updatable
  28006. };
  28007. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  28008. };
  28009. /**
  28010. * Creates a ground mesh from a height map.
  28011. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  28012. * Please consider using the same method from the MeshBuilder class instead.
  28013. * The parameter `url` sets the URL of the height map image resource.
  28014. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  28015. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  28016. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  28017. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  28018. * 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).
  28019. * This function is passed the newly built mesh :
  28020. * ```javascript
  28021. * function(mesh) { // do things
  28022. * return; }
  28023. * ```
  28024. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28025. */
  28026. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  28027. var options = {
  28028. width: width,
  28029. height: height,
  28030. subdivisions: subdivisions,
  28031. minHeight: minHeight,
  28032. maxHeight: maxHeight,
  28033. updatable: updatable,
  28034. onReady: onReady
  28035. };
  28036. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  28037. };
  28038. /**
  28039. * Creates a tube mesh.
  28040. * 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.
  28041. * Please consider using the same method from the MeshBuilder class instead.
  28042. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  28043. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  28044. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  28045. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  28046. * 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.
  28047. * It must return a radius value (positive float) :
  28048. * ```javascript
  28049. * var radiusFunction = function(i, distance) {
  28050. * // do things
  28051. * return radius; }
  28052. * ```
  28053. * 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
  28054. * 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
  28055. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  28056. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  28057. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28058. */
  28059. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  28060. var options = {
  28061. path: path,
  28062. radius: radius,
  28063. tessellation: tessellation,
  28064. radiusFunction: radiusFunction,
  28065. arc: 1,
  28066. cap: cap,
  28067. updatable: updatable,
  28068. sideOrientation: sideOrientation,
  28069. instance: instance
  28070. };
  28071. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  28072. };
  28073. /**
  28074. * Creates a polyhedron mesh.
  28075. * Please consider using the same method from the MeshBuilder class instead.
  28076. * 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
  28077. * to choose the wanted type.
  28078. * The parameter `size` (positive float, default 1) sets the polygon size.
  28079. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  28080. * 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`.
  28081. * 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
  28082. * 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)`).
  28083. * 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
  28084. * 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.
  28085. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  28086. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  28087. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28088. */
  28089. Mesh.CreatePolyhedron = function (name, options, scene) {
  28090. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  28091. };
  28092. /**
  28093. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  28094. * Please consider using the same method from the MeshBuilder class instead.
  28095. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  28096. * 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`).
  28097. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  28098. * 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.
  28099. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  28100. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  28101. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  28102. */
  28103. Mesh.CreateIcoSphere = function (name, options, scene) {
  28104. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  28105. };
  28106. /**
  28107. * Creates a decal mesh.
  28108. * Please consider using the same method from the MeshBuilder class instead.
  28109. * 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.
  28110. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  28111. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  28112. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  28113. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  28114. */
  28115. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  28116. var options = {
  28117. position: position,
  28118. normal: normal,
  28119. size: size,
  28120. angle: angle
  28121. };
  28122. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  28123. };
  28124. // Skeletons
  28125. /**
  28126. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  28127. */
  28128. Mesh.prototype.setPositionsForCPUSkinning = function () {
  28129. if (!this._sourcePositions) {
  28130. var source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28131. if (!source) {
  28132. return this._sourcePositions;
  28133. }
  28134. this._sourcePositions = new Float32Array(source);
  28135. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  28136. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  28137. }
  28138. }
  28139. return this._sourcePositions;
  28140. };
  28141. /**
  28142. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  28143. */
  28144. Mesh.prototype.setNormalsForCPUSkinning = function () {
  28145. if (!this._sourceNormals) {
  28146. var source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  28147. if (!source) {
  28148. return this._sourceNormals;
  28149. }
  28150. this._sourceNormals = new Float32Array(source);
  28151. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  28152. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  28153. }
  28154. }
  28155. return this._sourceNormals;
  28156. };
  28157. /**
  28158. * Updates the vertex buffer by applying transformation from the bones.
  28159. * Returns the Mesh.
  28160. *
  28161. * @param {skeleton} skeleton to apply
  28162. */
  28163. Mesh.prototype.applySkeleton = function (skeleton) {
  28164. if (!this.geometry) {
  28165. return this;
  28166. }
  28167. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  28168. return this;
  28169. }
  28170. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  28171. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  28172. return this;
  28173. }
  28174. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  28175. return this;
  28176. }
  28177. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  28178. return this;
  28179. }
  28180. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  28181. return this;
  28182. }
  28183. if (!this._sourcePositions) {
  28184. var submeshes = this.subMeshes.slice();
  28185. this.setPositionsForCPUSkinning();
  28186. this.subMeshes = submeshes;
  28187. }
  28188. if (!this._sourceNormals) {
  28189. this.setNormalsForCPUSkinning();
  28190. }
  28191. // positionsData checks for not being Float32Array will only pass at most once
  28192. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28193. if (!positionsData) {
  28194. return this;
  28195. }
  28196. if (!(positionsData instanceof Float32Array)) {
  28197. positionsData = new Float32Array(positionsData);
  28198. }
  28199. // normalsData checks for not being Float32Array will only pass at most once
  28200. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  28201. if (!normalsData) {
  28202. return this;
  28203. }
  28204. if (!(normalsData instanceof Float32Array)) {
  28205. normalsData = new Float32Array(normalsData);
  28206. }
  28207. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  28208. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  28209. if (!matricesWeightsData || !matricesIndicesData) {
  28210. return this;
  28211. }
  28212. var needExtras = this.numBoneInfluencers > 4;
  28213. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  28214. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  28215. var skeletonMatrices = skeleton.getTransformMatrices(this);
  28216. var tempVector3 = BABYLON.Vector3.Zero();
  28217. var finalMatrix = new BABYLON.Matrix();
  28218. var tempMatrix = new BABYLON.Matrix();
  28219. var matWeightIdx = 0;
  28220. var inf;
  28221. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  28222. var weight;
  28223. for (inf = 0; inf < 4; inf++) {
  28224. weight = matricesWeightsData[matWeightIdx + inf];
  28225. if (weight > 0) {
  28226. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[matWeightIdx + inf] * 16, weight, tempMatrix);
  28227. finalMatrix.addToSelf(tempMatrix);
  28228. }
  28229. else
  28230. break;
  28231. }
  28232. if (needExtras) {
  28233. for (inf = 0; inf < 4; inf++) {
  28234. weight = matricesWeightsExtraData[matWeightIdx + inf];
  28235. if (weight > 0) {
  28236. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesExtraData[matWeightIdx + inf] * 16, weight, tempMatrix);
  28237. finalMatrix.addToSelf(tempMatrix);
  28238. }
  28239. else
  28240. break;
  28241. }
  28242. }
  28243. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  28244. tempVector3.toArray(positionsData, index);
  28245. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  28246. tempVector3.toArray(normalsData, index);
  28247. finalMatrix.reset();
  28248. }
  28249. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  28250. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  28251. return this;
  28252. };
  28253. // Tools
  28254. /**
  28255. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  28256. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  28257. */
  28258. Mesh.MinMax = function (meshes) {
  28259. var minVector = null;
  28260. var maxVector = null;
  28261. meshes.forEach(function (mesh, index, array) {
  28262. var boundingInfo = mesh.getBoundingInfo();
  28263. var boundingBox = boundingInfo.boundingBox;
  28264. if (!minVector || !maxVector) {
  28265. minVector = boundingBox.minimumWorld;
  28266. maxVector = boundingBox.maximumWorld;
  28267. }
  28268. else {
  28269. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  28270. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  28271. }
  28272. });
  28273. if (!minVector || !maxVector) {
  28274. return {
  28275. min: BABYLON.Vector3.Zero(),
  28276. max: BABYLON.Vector3.Zero()
  28277. };
  28278. }
  28279. return {
  28280. min: minVector,
  28281. max: maxVector
  28282. };
  28283. };
  28284. /**
  28285. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  28286. */
  28287. Mesh.Center = function (meshesOrMinMaxVector) {
  28288. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  28289. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  28290. };
  28291. /**
  28292. * Merge the array of meshes into a single mesh for performance reasons.
  28293. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  28294. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  28295. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  28296. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  28297. * @param {boolean} subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  28298. */
  28299. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  28300. if (disposeSource === void 0) { disposeSource = true; }
  28301. var index;
  28302. if (!allow32BitsIndices) {
  28303. var totalVertices = 0;
  28304. // Counting vertices
  28305. for (index = 0; index < meshes.length; index++) {
  28306. if (meshes[index]) {
  28307. totalVertices += meshes[index].getTotalVertices();
  28308. if (totalVertices > 65536) {
  28309. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  28310. return null;
  28311. }
  28312. }
  28313. }
  28314. }
  28315. // Merge
  28316. var vertexData = null;
  28317. var otherVertexData;
  28318. var indiceArray = new Array();
  28319. var source = null;
  28320. for (index = 0; index < meshes.length; index++) {
  28321. if (meshes[index]) {
  28322. meshes[index].computeWorldMatrix(true);
  28323. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  28324. otherVertexData.transform(meshes[index].getWorldMatrix());
  28325. if (vertexData) {
  28326. vertexData.merge(otherVertexData);
  28327. }
  28328. else {
  28329. vertexData = otherVertexData;
  28330. source = meshes[index];
  28331. }
  28332. if (subdivideWithSubMeshes) {
  28333. indiceArray.push(meshes[index].getTotalIndices());
  28334. }
  28335. }
  28336. }
  28337. source = source;
  28338. if (!meshSubclass) {
  28339. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  28340. }
  28341. vertexData.applyToMesh(meshSubclass);
  28342. // Setting properties
  28343. meshSubclass.material = source.material;
  28344. meshSubclass.checkCollisions = source.checkCollisions;
  28345. // Cleaning
  28346. if (disposeSource) {
  28347. for (index = 0; index < meshes.length; index++) {
  28348. if (meshes[index]) {
  28349. meshes[index].dispose();
  28350. }
  28351. }
  28352. }
  28353. // Subdivide
  28354. if (subdivideWithSubMeshes) {
  28355. //-- Suppresions du submesh global
  28356. meshSubclass.releaseSubMeshes();
  28357. index = 0;
  28358. var offset = 0;
  28359. //-- aplique la subdivision en fonction du tableau d'indices
  28360. while (index < indiceArray.length) {
  28361. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  28362. offset += indiceArray[index];
  28363. index++;
  28364. }
  28365. }
  28366. return meshSubclass;
  28367. };
  28368. // Consts
  28369. Mesh._FRONTSIDE = 0;
  28370. Mesh._BACKSIDE = 1;
  28371. Mesh._DOUBLESIDE = 2;
  28372. Mesh._DEFAULTSIDE = 0;
  28373. Mesh._NO_CAP = 0;
  28374. Mesh._CAP_START = 1;
  28375. Mesh._CAP_END = 2;
  28376. Mesh._CAP_ALL = 3;
  28377. return Mesh;
  28378. }(BABYLON.AbstractMesh));
  28379. BABYLON.Mesh = Mesh;
  28380. })(BABYLON || (BABYLON = {}));
  28381. //# sourceMappingURL=babylon.mesh.js.map
  28382. var BABYLON;
  28383. (function (BABYLON) {
  28384. var BaseSubMesh = /** @class */ (function () {
  28385. function BaseSubMesh() {
  28386. }
  28387. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  28388. get: function () {
  28389. return this._materialEffect;
  28390. },
  28391. enumerable: true,
  28392. configurable: true
  28393. });
  28394. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  28395. if (defines === void 0) { defines = null; }
  28396. if (this._materialEffect === effect) {
  28397. if (!effect) {
  28398. this._materialDefines = null;
  28399. }
  28400. return;
  28401. }
  28402. this._materialDefines = defines;
  28403. this._materialEffect = effect;
  28404. };
  28405. return BaseSubMesh;
  28406. }());
  28407. BABYLON.BaseSubMesh = BaseSubMesh;
  28408. var SubMesh = /** @class */ (function (_super) {
  28409. __extends(SubMesh, _super);
  28410. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  28411. if (createBoundingBox === void 0) { createBoundingBox = true; }
  28412. var _this = _super.call(this) || this;
  28413. _this.materialIndex = materialIndex;
  28414. _this.verticesStart = verticesStart;
  28415. _this.verticesCount = verticesCount;
  28416. _this.indexStart = indexStart;
  28417. _this.indexCount = indexCount;
  28418. _this._renderId = 0;
  28419. _this._mesh = mesh;
  28420. _this._renderingMesh = renderingMesh || mesh;
  28421. mesh.subMeshes.push(_this);
  28422. _this._trianglePlanes = [];
  28423. _this._id = mesh.subMeshes.length - 1;
  28424. if (createBoundingBox) {
  28425. _this.refreshBoundingInfo();
  28426. mesh.computeWorldMatrix(true);
  28427. }
  28428. return _this;
  28429. }
  28430. SubMesh.AddToMesh = function (materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  28431. if (createBoundingBox === void 0) { createBoundingBox = true; }
  28432. return new SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox);
  28433. };
  28434. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  28435. get: function () {
  28436. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  28437. },
  28438. enumerable: true,
  28439. configurable: true
  28440. });
  28441. /**
  28442. * Returns the submesh BoudingInfo object.
  28443. */
  28444. SubMesh.prototype.getBoundingInfo = function () {
  28445. if (this.IsGlobal) {
  28446. return this._mesh.getBoundingInfo();
  28447. }
  28448. return this._boundingInfo;
  28449. };
  28450. /**
  28451. * Sets the submesh BoundingInfo.
  28452. * Return the SubMesh.
  28453. */
  28454. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  28455. this._boundingInfo = boundingInfo;
  28456. return this;
  28457. };
  28458. /**
  28459. * Returns the mesh of the current submesh.
  28460. */
  28461. SubMesh.prototype.getMesh = function () {
  28462. return this._mesh;
  28463. };
  28464. /**
  28465. * Returns the rendering mesh of the submesh.
  28466. */
  28467. SubMesh.prototype.getRenderingMesh = function () {
  28468. return this._renderingMesh;
  28469. };
  28470. /**
  28471. * Returns the submesh material.
  28472. */
  28473. SubMesh.prototype.getMaterial = function () {
  28474. var rootMaterial = this._renderingMesh.material;
  28475. if (rootMaterial === null || rootMaterial === undefined) {
  28476. return this._mesh.getScene().defaultMaterial;
  28477. }
  28478. else if (rootMaterial.getSubMaterial) {
  28479. var multiMaterial = rootMaterial;
  28480. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  28481. if (this._currentMaterial !== effectiveMaterial) {
  28482. this._currentMaterial = effectiveMaterial;
  28483. this._materialDefines = null;
  28484. }
  28485. return effectiveMaterial;
  28486. }
  28487. return rootMaterial;
  28488. };
  28489. // Methods
  28490. /**
  28491. * Sets a new updated BoundingInfo object to the submesh.
  28492. * Returns the SubMesh.
  28493. */
  28494. SubMesh.prototype.refreshBoundingInfo = function () {
  28495. this._lastColliderWorldVertices = null;
  28496. if (this.IsGlobal || !this._renderingMesh || !this._renderingMesh.geometry) {
  28497. return this;
  28498. }
  28499. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28500. if (!data) {
  28501. this._boundingInfo = this._mesh.getBoundingInfo();
  28502. return this;
  28503. }
  28504. var indices = this._renderingMesh.getIndices();
  28505. var extend;
  28506. //is this the only submesh?
  28507. if (this.indexStart === 0 && this.indexCount === indices.length) {
  28508. var boundingInfo = this._renderingMesh.getBoundingInfo();
  28509. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  28510. extend = { minimum: boundingInfo.minimum.clone(), maximum: boundingInfo.maximum.clone() };
  28511. }
  28512. else {
  28513. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  28514. }
  28515. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  28516. return this;
  28517. };
  28518. SubMesh.prototype._checkCollision = function (collider) {
  28519. var boundingInfo = this._renderingMesh.getBoundingInfo();
  28520. return boundingInfo._checkCollision(collider);
  28521. };
  28522. /**
  28523. * Updates the submesh BoundingInfo.
  28524. * Returns the Submesh.
  28525. */
  28526. SubMesh.prototype.updateBoundingInfo = function (world) {
  28527. var boundingInfo = this.getBoundingInfo();
  28528. if (!boundingInfo) {
  28529. this.refreshBoundingInfo();
  28530. boundingInfo = this.getBoundingInfo();
  28531. }
  28532. boundingInfo.update(world);
  28533. return this;
  28534. };
  28535. /**
  28536. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  28537. * Boolean returned.
  28538. */
  28539. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  28540. var boundingInfo = this.getBoundingInfo();
  28541. if (!boundingInfo) {
  28542. return false;
  28543. }
  28544. return boundingInfo.isInFrustum(frustumPlanes);
  28545. };
  28546. /**
  28547. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  28548. * Boolean returned.
  28549. */
  28550. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  28551. var boundingInfo = this.getBoundingInfo();
  28552. if (!boundingInfo) {
  28553. return false;
  28554. }
  28555. return boundingInfo.isCompletelyInFrustum(frustumPlanes);
  28556. };
  28557. /**
  28558. * Renders the submesh.
  28559. * Returns it.
  28560. */
  28561. SubMesh.prototype.render = function (enableAlphaMode) {
  28562. this._renderingMesh.render(this, enableAlphaMode);
  28563. return this;
  28564. };
  28565. /**
  28566. * Returns a new Index Buffer.
  28567. * Type returned : WebGLBuffer.
  28568. */
  28569. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  28570. if (!this._linesIndexBuffer) {
  28571. var linesIndices = [];
  28572. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  28573. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  28574. }
  28575. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  28576. this.linesIndexCount = linesIndices.length;
  28577. }
  28578. return this._linesIndexBuffer;
  28579. };
  28580. /**
  28581. * True is the passed Ray intersects the submesh bounding box.
  28582. * Boolean returned.
  28583. */
  28584. SubMesh.prototype.canIntersects = function (ray) {
  28585. var boundingInfo = this.getBoundingInfo();
  28586. if (!boundingInfo) {
  28587. return false;
  28588. }
  28589. return ray.intersectsBox(boundingInfo.boundingBox);
  28590. };
  28591. /**
  28592. * Returns an object IntersectionInfo.
  28593. */
  28594. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  28595. var intersectInfo = null;
  28596. // LineMesh first as it's also a Mesh...
  28597. if (BABYLON.LinesMesh && this._mesh instanceof BABYLON.LinesMesh) {
  28598. var lineMesh = this._mesh;
  28599. // Line test
  28600. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  28601. var p0 = positions[indices[index]];
  28602. var p1 = positions[indices[index + 1]];
  28603. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  28604. if (length < 0) {
  28605. continue;
  28606. }
  28607. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  28608. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  28609. if (fastCheck) {
  28610. break;
  28611. }
  28612. }
  28613. }
  28614. }
  28615. else {
  28616. // Triangles test
  28617. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  28618. var p0 = positions[indices[index]];
  28619. var p1 = positions[indices[index + 1]];
  28620. var p2 = positions[indices[index + 2]];
  28621. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  28622. if (currentIntersectInfo) {
  28623. if (currentIntersectInfo.distance < 0) {
  28624. continue;
  28625. }
  28626. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  28627. intersectInfo = currentIntersectInfo;
  28628. intersectInfo.faceId = index / 3;
  28629. if (fastCheck) {
  28630. break;
  28631. }
  28632. }
  28633. }
  28634. }
  28635. }
  28636. return intersectInfo;
  28637. };
  28638. SubMesh.prototype._rebuild = function () {
  28639. if (this._linesIndexBuffer) {
  28640. this._linesIndexBuffer = null;
  28641. }
  28642. };
  28643. // Clone
  28644. /**
  28645. * Creates a new Submesh from the passed Mesh.
  28646. */
  28647. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  28648. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  28649. if (!this.IsGlobal) {
  28650. var boundingInfo = this.getBoundingInfo();
  28651. if (!boundingInfo) {
  28652. return result;
  28653. }
  28654. result._boundingInfo = new BABYLON.BoundingInfo(boundingInfo.minimum, boundingInfo.maximum);
  28655. }
  28656. return result;
  28657. };
  28658. // Dispose
  28659. /**
  28660. * Disposes the Submesh.
  28661. * Returns nothing.
  28662. */
  28663. SubMesh.prototype.dispose = function () {
  28664. if (this._linesIndexBuffer) {
  28665. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  28666. this._linesIndexBuffer = null;
  28667. }
  28668. // Remove from mesh
  28669. var index = this._mesh.subMeshes.indexOf(this);
  28670. this._mesh.subMeshes.splice(index, 1);
  28671. };
  28672. // Statics
  28673. /**
  28674. * Creates a new Submesh from the passed parameters :
  28675. * - materialIndex (integer) : the index of the main mesh material.
  28676. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  28677. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  28678. * - mesh (Mesh) : the main mesh to create the submesh from.
  28679. * - renderingMesh (optional Mesh) : rendering mesh.
  28680. */
  28681. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  28682. var minVertexIndex = Number.MAX_VALUE;
  28683. var maxVertexIndex = -Number.MAX_VALUE;
  28684. renderingMesh = (renderingMesh || mesh);
  28685. var indices = renderingMesh.getIndices();
  28686. for (var index = startIndex; index < startIndex + indexCount; index++) {
  28687. var vertexIndex = indices[index];
  28688. if (vertexIndex < minVertexIndex)
  28689. minVertexIndex = vertexIndex;
  28690. if (vertexIndex > maxVertexIndex)
  28691. maxVertexIndex = vertexIndex;
  28692. }
  28693. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  28694. };
  28695. return SubMesh;
  28696. }(BaseSubMesh));
  28697. BABYLON.SubMesh = SubMesh;
  28698. })(BABYLON || (BABYLON = {}));
  28699. //# sourceMappingURL=babylon.subMesh.js.map
  28700. var __assign = (this && this.__assign) || Object.assign || function(t) {
  28701. for (var s, i = 1, n = arguments.length; i < n; i++) {
  28702. s = arguments[i];
  28703. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  28704. t[p] = s[p];
  28705. }
  28706. return t;
  28707. };
  28708. var BABYLON;
  28709. (function (BABYLON) {
  28710. var MaterialDefines = /** @class */ (function () {
  28711. function MaterialDefines() {
  28712. this._isDirty = true;
  28713. this._areLightsDirty = true;
  28714. this._areAttributesDirty = true;
  28715. this._areTexturesDirty = true;
  28716. this._areFresnelDirty = true;
  28717. this._areMiscDirty = true;
  28718. this._areImageProcessingDirty = true;
  28719. this._normals = false;
  28720. this._uvs = false;
  28721. this._needNormals = false;
  28722. this._needUVs = false;
  28723. }
  28724. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  28725. get: function () {
  28726. return this._isDirty;
  28727. },
  28728. enumerable: true,
  28729. configurable: true
  28730. });
  28731. MaterialDefines.prototype.markAsProcessed = function () {
  28732. this._isDirty = false;
  28733. this._areAttributesDirty = false;
  28734. this._areTexturesDirty = false;
  28735. this._areFresnelDirty = false;
  28736. this._areLightsDirty = false;
  28737. this._areMiscDirty = false;
  28738. this._areImageProcessingDirty = false;
  28739. };
  28740. MaterialDefines.prototype.markAsUnprocessed = function () {
  28741. this._isDirty = true;
  28742. };
  28743. MaterialDefines.prototype.markAllAsDirty = function () {
  28744. this._areTexturesDirty = true;
  28745. this._areAttributesDirty = true;
  28746. this._areLightsDirty = true;
  28747. this._areFresnelDirty = true;
  28748. this._areMiscDirty = true;
  28749. this._areImageProcessingDirty = true;
  28750. this._isDirty = true;
  28751. };
  28752. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  28753. this._areImageProcessingDirty = true;
  28754. this._isDirty = true;
  28755. };
  28756. MaterialDefines.prototype.markAsLightDirty = function () {
  28757. this._areLightsDirty = true;
  28758. this._isDirty = true;
  28759. };
  28760. MaterialDefines.prototype.markAsAttributesDirty = function () {
  28761. this._areAttributesDirty = true;
  28762. this._isDirty = true;
  28763. };
  28764. MaterialDefines.prototype.markAsTexturesDirty = function () {
  28765. this._areTexturesDirty = true;
  28766. this._isDirty = true;
  28767. };
  28768. MaterialDefines.prototype.markAsFresnelDirty = function () {
  28769. this._areFresnelDirty = true;
  28770. this._isDirty = true;
  28771. };
  28772. MaterialDefines.prototype.markAsMiscDirty = function () {
  28773. this._areMiscDirty = true;
  28774. this._isDirty = true;
  28775. };
  28776. MaterialDefines.prototype.rebuild = function () {
  28777. if (this._keys) {
  28778. delete this._keys;
  28779. }
  28780. this._keys = [];
  28781. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  28782. var key = _a[_i];
  28783. if (key[0] === "_") {
  28784. continue;
  28785. }
  28786. this._keys.push(key);
  28787. }
  28788. };
  28789. MaterialDefines.prototype.isEqual = function (other) {
  28790. if (this._keys.length !== other._keys.length) {
  28791. return false;
  28792. }
  28793. for (var index = 0; index < this._keys.length; index++) {
  28794. var prop = this._keys[index];
  28795. if (this[prop] !== other[prop]) {
  28796. return false;
  28797. }
  28798. }
  28799. return true;
  28800. };
  28801. MaterialDefines.prototype.cloneTo = function (other) {
  28802. if (this._keys.length !== other._keys.length) {
  28803. other._keys = this._keys.slice(0);
  28804. }
  28805. for (var index = 0; index < this._keys.length; index++) {
  28806. var prop = this._keys[index];
  28807. other[prop] = this[prop];
  28808. }
  28809. };
  28810. MaterialDefines.prototype.reset = function () {
  28811. for (var index = 0; index < this._keys.length; index++) {
  28812. var prop = this._keys[index];
  28813. if (typeof (this[prop]) === "number") {
  28814. this[prop] = 0;
  28815. }
  28816. else {
  28817. this[prop] = false;
  28818. }
  28819. }
  28820. };
  28821. MaterialDefines.prototype.toString = function () {
  28822. var result = "";
  28823. for (var index = 0; index < this._keys.length; index++) {
  28824. var prop = this._keys[index];
  28825. var value = this[prop];
  28826. if (typeof (value) === "number") {
  28827. result += "#define " + prop + " " + this[prop] + "\n";
  28828. }
  28829. else if (value) {
  28830. result += "#define " + prop + "\n";
  28831. }
  28832. }
  28833. return result;
  28834. };
  28835. return MaterialDefines;
  28836. }());
  28837. BABYLON.MaterialDefines = MaterialDefines;
  28838. var Material = /** @class */ (function () {
  28839. function Material(name, scene, doNotAdd) {
  28840. this.checkReadyOnEveryCall = false;
  28841. this.checkReadyOnlyOnce = false;
  28842. this.state = "";
  28843. this._alpha = 1.0;
  28844. this._backFaceCulling = true;
  28845. this.doNotSerialize = false;
  28846. this.storeEffectOnSubMeshes = false;
  28847. /**
  28848. * An event triggered when the material is disposed.
  28849. * @type {BABYLON.Observable}
  28850. */
  28851. this.onDisposeObservable = new BABYLON.Observable();
  28852. /**
  28853. * An event triggered when the material is bound.
  28854. * @type {BABYLON.Observable}
  28855. */
  28856. this.onBindObservable = new BABYLON.Observable();
  28857. /**
  28858. * An event triggered when the material is unbound.
  28859. * @type {BABYLON.Observable}
  28860. */
  28861. this.onUnBindObservable = new BABYLON.Observable();
  28862. this._alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  28863. this._needDepthPrePass = false;
  28864. this.disableDepthWrite = false;
  28865. this.forceDepthWrite = false;
  28866. this.separateCullingPass = false;
  28867. this._fogEnabled = true;
  28868. this.pointSize = 1.0;
  28869. this.zOffset = 0;
  28870. this._wasPreviouslyReady = false;
  28871. this._fillMode = Material.TriangleFillMode;
  28872. this.name = name;
  28873. this.id = name || BABYLON.Tools.RandomId();
  28874. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  28875. if (this._scene.useRightHandedSystem) {
  28876. this.sideOrientation = Material.ClockWiseSideOrientation;
  28877. }
  28878. else {
  28879. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  28880. }
  28881. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  28882. this._useUBO = this.getScene().getEngine().supportsUniformBuffers;
  28883. if (!doNotAdd) {
  28884. this._scene.materials.push(this);
  28885. }
  28886. }
  28887. Object.defineProperty(Material, "TriangleFillMode", {
  28888. get: function () {
  28889. return Material._TriangleFillMode;
  28890. },
  28891. enumerable: true,
  28892. configurable: true
  28893. });
  28894. Object.defineProperty(Material, "WireFrameFillMode", {
  28895. get: function () {
  28896. return Material._WireFrameFillMode;
  28897. },
  28898. enumerable: true,
  28899. configurable: true
  28900. });
  28901. Object.defineProperty(Material, "PointFillMode", {
  28902. get: function () {
  28903. return Material._PointFillMode;
  28904. },
  28905. enumerable: true,
  28906. configurable: true
  28907. });
  28908. Object.defineProperty(Material, "PointListDrawMode", {
  28909. get: function () {
  28910. return Material._PointListDrawMode;
  28911. },
  28912. enumerable: true,
  28913. configurable: true
  28914. });
  28915. Object.defineProperty(Material, "LineListDrawMode", {
  28916. get: function () {
  28917. return Material._LineListDrawMode;
  28918. },
  28919. enumerable: true,
  28920. configurable: true
  28921. });
  28922. Object.defineProperty(Material, "LineLoopDrawMode", {
  28923. get: function () {
  28924. return Material._LineLoopDrawMode;
  28925. },
  28926. enumerable: true,
  28927. configurable: true
  28928. });
  28929. Object.defineProperty(Material, "LineStripDrawMode", {
  28930. get: function () {
  28931. return Material._LineStripDrawMode;
  28932. },
  28933. enumerable: true,
  28934. configurable: true
  28935. });
  28936. Object.defineProperty(Material, "TriangleStripDrawMode", {
  28937. get: function () {
  28938. return Material._TriangleStripDrawMode;
  28939. },
  28940. enumerable: true,
  28941. configurable: true
  28942. });
  28943. Object.defineProperty(Material, "TriangleFanDrawMode", {
  28944. get: function () {
  28945. return Material._TriangleFanDrawMode;
  28946. },
  28947. enumerable: true,
  28948. configurable: true
  28949. });
  28950. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  28951. get: function () {
  28952. return Material._ClockWiseSideOrientation;
  28953. },
  28954. enumerable: true,
  28955. configurable: true
  28956. });
  28957. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  28958. get: function () {
  28959. return Material._CounterClockWiseSideOrientation;
  28960. },
  28961. enumerable: true,
  28962. configurable: true
  28963. });
  28964. Object.defineProperty(Material, "TextureDirtyFlag", {
  28965. get: function () {
  28966. return Material._TextureDirtyFlag;
  28967. },
  28968. enumerable: true,
  28969. configurable: true
  28970. });
  28971. Object.defineProperty(Material, "LightDirtyFlag", {
  28972. get: function () {
  28973. return Material._LightDirtyFlag;
  28974. },
  28975. enumerable: true,
  28976. configurable: true
  28977. });
  28978. Object.defineProperty(Material, "FresnelDirtyFlag", {
  28979. get: function () {
  28980. return Material._FresnelDirtyFlag;
  28981. },
  28982. enumerable: true,
  28983. configurable: true
  28984. });
  28985. Object.defineProperty(Material, "AttributesDirtyFlag", {
  28986. get: function () {
  28987. return Material._AttributesDirtyFlag;
  28988. },
  28989. enumerable: true,
  28990. configurable: true
  28991. });
  28992. Object.defineProperty(Material, "MiscDirtyFlag", {
  28993. get: function () {
  28994. return Material._MiscDirtyFlag;
  28995. },
  28996. enumerable: true,
  28997. configurable: true
  28998. });
  28999. Object.defineProperty(Material.prototype, "alpha", {
  29000. get: function () {
  29001. return this._alpha;
  29002. },
  29003. set: function (value) {
  29004. if (this._alpha === value) {
  29005. return;
  29006. }
  29007. this._alpha = value;
  29008. this.markAsDirty(Material.MiscDirtyFlag);
  29009. },
  29010. enumerable: true,
  29011. configurable: true
  29012. });
  29013. Object.defineProperty(Material.prototype, "backFaceCulling", {
  29014. get: function () {
  29015. return this._backFaceCulling;
  29016. },
  29017. set: function (value) {
  29018. if (this._backFaceCulling === value) {
  29019. return;
  29020. }
  29021. this._backFaceCulling = value;
  29022. this.markAsDirty(Material.TextureDirtyFlag);
  29023. },
  29024. enumerable: true,
  29025. configurable: true
  29026. });
  29027. Object.defineProperty(Material.prototype, "onDispose", {
  29028. set: function (callback) {
  29029. if (this._onDisposeObserver) {
  29030. this.onDisposeObservable.remove(this._onDisposeObserver);
  29031. }
  29032. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  29033. },
  29034. enumerable: true,
  29035. configurable: true
  29036. });
  29037. Object.defineProperty(Material.prototype, "onBind", {
  29038. set: function (callback) {
  29039. if (this._onBindObserver) {
  29040. this.onBindObservable.remove(this._onBindObserver);
  29041. }
  29042. this._onBindObserver = this.onBindObservable.add(callback);
  29043. },
  29044. enumerable: true,
  29045. configurable: true
  29046. });
  29047. Object.defineProperty(Material.prototype, "alphaMode", {
  29048. get: function () {
  29049. return this._alphaMode;
  29050. },
  29051. set: function (value) {
  29052. if (this._alphaMode === value) {
  29053. return;
  29054. }
  29055. this._alphaMode = value;
  29056. this.markAsDirty(Material.TextureDirtyFlag);
  29057. },
  29058. enumerable: true,
  29059. configurable: true
  29060. });
  29061. Object.defineProperty(Material.prototype, "needDepthPrePass", {
  29062. get: function () {
  29063. return this._needDepthPrePass;
  29064. },
  29065. set: function (value) {
  29066. if (this._needDepthPrePass === value) {
  29067. return;
  29068. }
  29069. this._needDepthPrePass = value;
  29070. if (this._needDepthPrePass) {
  29071. this.checkReadyOnEveryCall = true;
  29072. }
  29073. },
  29074. enumerable: true,
  29075. configurable: true
  29076. });
  29077. Object.defineProperty(Material.prototype, "fogEnabled", {
  29078. get: function () {
  29079. return this._fogEnabled;
  29080. },
  29081. set: function (value) {
  29082. if (this._fogEnabled === value) {
  29083. return;
  29084. }
  29085. this._fogEnabled = value;
  29086. this.markAsDirty(Material.MiscDirtyFlag);
  29087. },
  29088. enumerable: true,
  29089. configurable: true
  29090. });
  29091. Object.defineProperty(Material.prototype, "wireframe", {
  29092. get: function () {
  29093. return this._fillMode === Material.WireFrameFillMode;
  29094. },
  29095. set: function (value) {
  29096. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  29097. },
  29098. enumerable: true,
  29099. configurable: true
  29100. });
  29101. Object.defineProperty(Material.prototype, "pointsCloud", {
  29102. get: function () {
  29103. return this._fillMode === Material.PointFillMode;
  29104. },
  29105. set: function (value) {
  29106. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  29107. },
  29108. enumerable: true,
  29109. configurable: true
  29110. });
  29111. Object.defineProperty(Material.prototype, "fillMode", {
  29112. get: function () {
  29113. return this._fillMode;
  29114. },
  29115. set: function (value) {
  29116. if (this._fillMode === value) {
  29117. return;
  29118. }
  29119. this._fillMode = value;
  29120. this.markAsDirty(Material.MiscDirtyFlag);
  29121. },
  29122. enumerable: true,
  29123. configurable: true
  29124. });
  29125. /**
  29126. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  29127. * subclasses should override adding information pertainent to themselves
  29128. */
  29129. Material.prototype.toString = function (fullDetails) {
  29130. var ret = "Name: " + this.name;
  29131. if (fullDetails) {
  29132. }
  29133. return ret;
  29134. };
  29135. /**
  29136. * Child classes can use it to update shaders
  29137. */
  29138. Material.prototype.getClassName = function () {
  29139. return "Material";
  29140. };
  29141. Object.defineProperty(Material.prototype, "isFrozen", {
  29142. get: function () {
  29143. return this.checkReadyOnlyOnce;
  29144. },
  29145. enumerable: true,
  29146. configurable: true
  29147. });
  29148. Material.prototype.freeze = function () {
  29149. this.checkReadyOnlyOnce = true;
  29150. };
  29151. Material.prototype.unfreeze = function () {
  29152. this.checkReadyOnlyOnce = false;
  29153. };
  29154. Material.prototype.isReady = function (mesh, useInstances) {
  29155. return true;
  29156. };
  29157. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  29158. return false;
  29159. };
  29160. Material.prototype.getEffect = function () {
  29161. return this._effect;
  29162. };
  29163. Material.prototype.getScene = function () {
  29164. return this._scene;
  29165. };
  29166. Material.prototype.needAlphaBlending = function () {
  29167. return (this.alpha < 1.0);
  29168. };
  29169. Material.prototype.needAlphaBlendingForMesh = function (mesh) {
  29170. return this.needAlphaBlending() || (mesh.visibility < 1.0) || mesh.hasVertexAlpha;
  29171. };
  29172. Material.prototype.needAlphaTesting = function () {
  29173. return false;
  29174. };
  29175. Material.prototype.getAlphaTestTexture = function () {
  29176. return null;
  29177. };
  29178. Material.prototype.markDirty = function () {
  29179. this._wasPreviouslyReady = false;
  29180. };
  29181. Material.prototype._preBind = function (effect, overrideOrientation) {
  29182. if (overrideOrientation === void 0) { overrideOrientation = null; }
  29183. var engine = this._scene.getEngine();
  29184. var orientation = (overrideOrientation == null) ? this.sideOrientation : overrideOrientation;
  29185. var reverse = orientation === Material.ClockWiseSideOrientation;
  29186. engine.enableEffect(effect ? effect : this._effect);
  29187. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  29188. return reverse;
  29189. };
  29190. Material.prototype.bind = function (world, mesh) {
  29191. };
  29192. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  29193. };
  29194. Material.prototype.bindOnlyWorldMatrix = function (world) {
  29195. };
  29196. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  29197. sceneUbo.bindToEffect(effect, "Scene");
  29198. };
  29199. Material.prototype.bindView = function (effect) {
  29200. if (!this._useUBO) {
  29201. effect.setMatrix("view", this.getScene().getViewMatrix());
  29202. }
  29203. else {
  29204. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  29205. }
  29206. };
  29207. Material.prototype.bindViewProjection = function (effect) {
  29208. if (!this._useUBO) {
  29209. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  29210. }
  29211. else {
  29212. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  29213. }
  29214. };
  29215. Material.prototype._shouldTurnAlphaTestOn = function (mesh) {
  29216. return (!this.needAlphaBlendingForMesh(mesh) && this.needAlphaTesting());
  29217. };
  29218. Material.prototype._afterBind = function (mesh) {
  29219. this._scene._cachedMaterial = this;
  29220. if (mesh) {
  29221. this._scene._cachedVisibility = mesh.visibility;
  29222. }
  29223. else {
  29224. this._scene._cachedVisibility = 1;
  29225. }
  29226. if (mesh) {
  29227. this.onBindObservable.notifyObservers(mesh);
  29228. }
  29229. if (this.disableDepthWrite) {
  29230. var engine = this._scene.getEngine();
  29231. this._cachedDepthWriteState = engine.getDepthWrite();
  29232. engine.setDepthWrite(false);
  29233. }
  29234. };
  29235. Material.prototype.unbind = function () {
  29236. this.onUnBindObservable.notifyObservers(this);
  29237. if (this.disableDepthWrite) {
  29238. var engine = this._scene.getEngine();
  29239. engine.setDepthWrite(this._cachedDepthWriteState);
  29240. }
  29241. };
  29242. Material.prototype.getActiveTextures = function () {
  29243. return [];
  29244. };
  29245. Material.prototype.hasTexture = function (texture) {
  29246. return false;
  29247. };
  29248. Material.prototype.clone = function (name) {
  29249. return null;
  29250. };
  29251. Material.prototype.getBindedMeshes = function () {
  29252. var result = new Array();
  29253. for (var index = 0; index < this._scene.meshes.length; index++) {
  29254. var mesh = this._scene.meshes[index];
  29255. if (mesh.material === this) {
  29256. result.push(mesh);
  29257. }
  29258. }
  29259. return result;
  29260. };
  29261. /**
  29262. * Force shader compilation including textures ready check
  29263. */
  29264. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  29265. var _this = this;
  29266. var localOptions = __assign({ clipPlane: false }, options);
  29267. var subMesh = new BABYLON.BaseSubMesh();
  29268. var scene = this.getScene();
  29269. var checkReady = function () {
  29270. if (!_this._scene || !_this._scene.getEngine()) {
  29271. return;
  29272. }
  29273. if (subMesh._materialDefines) {
  29274. subMesh._materialDefines._renderId = -1;
  29275. }
  29276. var clipPlaneState = scene.clipPlane;
  29277. if (localOptions.clipPlane) {
  29278. scene.clipPlane = new BABYLON.Plane(0, 0, 0, 1);
  29279. }
  29280. if (_this.storeEffectOnSubMeshes) {
  29281. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  29282. if (onCompiled) {
  29283. onCompiled(_this);
  29284. }
  29285. }
  29286. else {
  29287. setTimeout(checkReady, 16);
  29288. }
  29289. }
  29290. else {
  29291. if (_this.isReady(mesh)) {
  29292. if (onCompiled) {
  29293. onCompiled(_this);
  29294. }
  29295. }
  29296. else {
  29297. setTimeout(checkReady, 16);
  29298. }
  29299. }
  29300. if (options && options.clipPlane) {
  29301. scene.clipPlane = clipPlaneState;
  29302. }
  29303. };
  29304. checkReady();
  29305. };
  29306. Material.prototype.markAsDirty = function (flag) {
  29307. if (flag & Material.TextureDirtyFlag) {
  29308. this._markAllSubMeshesAsTexturesDirty();
  29309. }
  29310. if (flag & Material.LightDirtyFlag) {
  29311. this._markAllSubMeshesAsLightsDirty();
  29312. }
  29313. if (flag & Material.FresnelDirtyFlag) {
  29314. this._markAllSubMeshesAsFresnelDirty();
  29315. }
  29316. if (flag & Material.AttributesDirtyFlag) {
  29317. this._markAllSubMeshesAsAttributesDirty();
  29318. }
  29319. if (flag & Material.MiscDirtyFlag) {
  29320. this._markAllSubMeshesAsMiscDirty();
  29321. }
  29322. this.getScene().resetCachedMaterial();
  29323. };
  29324. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  29325. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  29326. var mesh = _a[_i];
  29327. if (!mesh.subMeshes) {
  29328. continue;
  29329. }
  29330. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  29331. var subMesh = _c[_b];
  29332. if (subMesh.getMaterial() !== this) {
  29333. continue;
  29334. }
  29335. if (!subMesh._materialDefines) {
  29336. continue;
  29337. }
  29338. func(subMesh._materialDefines);
  29339. }
  29340. }
  29341. };
  29342. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  29343. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });
  29344. };
  29345. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  29346. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  29347. };
  29348. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  29349. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  29350. };
  29351. Material.prototype._markAllSubMeshesAsFresnelAndMiscDirty = function () {
  29352. this._markAllSubMeshesAsDirty(function (defines) {
  29353. defines.markAsFresnelDirty();
  29354. defines.markAsMiscDirty();
  29355. });
  29356. };
  29357. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  29358. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  29359. };
  29360. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  29361. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  29362. };
  29363. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  29364. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  29365. };
  29366. Material.prototype._markAllSubMeshesAsTexturesAndMiscDirty = function () {
  29367. this._markAllSubMeshesAsDirty(function (defines) {
  29368. defines.markAsTexturesDirty();
  29369. defines.markAsMiscDirty();
  29370. });
  29371. };
  29372. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  29373. // Animations
  29374. this.getScene().stopAnimation(this);
  29375. // Remove from scene
  29376. var index = this._scene.materials.indexOf(this);
  29377. if (index >= 0) {
  29378. this._scene.materials.splice(index, 1);
  29379. }
  29380. // Remove from meshes
  29381. for (index = 0; index < this._scene.meshes.length; index++) {
  29382. var mesh = this._scene.meshes[index];
  29383. if (mesh.material === this) {
  29384. mesh.material = null;
  29385. if (mesh.geometry) {
  29386. var geometry = (mesh.geometry);
  29387. if (this.storeEffectOnSubMeshes) {
  29388. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  29389. var subMesh = _a[_i];
  29390. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  29391. if (forceDisposeEffect && subMesh._materialEffect) {
  29392. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  29393. }
  29394. }
  29395. }
  29396. else {
  29397. geometry._releaseVertexArrayObject(this._effect);
  29398. }
  29399. }
  29400. }
  29401. }
  29402. this._uniformBuffer.dispose();
  29403. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  29404. if (forceDisposeEffect && this._effect) {
  29405. if (!this.storeEffectOnSubMeshes) {
  29406. this._scene.getEngine()._releaseEffect(this._effect);
  29407. }
  29408. this._effect = null;
  29409. }
  29410. // Callback
  29411. this.onDisposeObservable.notifyObservers(this);
  29412. this.onDisposeObservable.clear();
  29413. this.onBindObservable.clear();
  29414. this.onUnBindObservable.clear();
  29415. };
  29416. Material.prototype.serialize = function () {
  29417. return BABYLON.SerializationHelper.Serialize(this);
  29418. };
  29419. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  29420. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  29421. multiMaterial.id = parsedMultiMaterial.id;
  29422. if (BABYLON.Tags) {
  29423. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  29424. }
  29425. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  29426. var subMatId = parsedMultiMaterial.materials[matIndex];
  29427. if (subMatId) {
  29428. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  29429. }
  29430. else {
  29431. multiMaterial.subMaterials.push(null);
  29432. }
  29433. }
  29434. return multiMaterial;
  29435. };
  29436. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  29437. if (!parsedMaterial.customType) {
  29438. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  29439. }
  29440. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  29441. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  29442. if (!BABYLON.LegacyPBRMaterial) {
  29443. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  29444. return;
  29445. }
  29446. }
  29447. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  29448. return materialType.Parse(parsedMaterial, scene, rootUrl);
  29449. ;
  29450. };
  29451. // Triangle views
  29452. Material._TriangleFillMode = 0;
  29453. Material._WireFrameFillMode = 1;
  29454. Material._PointFillMode = 2;
  29455. // Draw modes
  29456. Material._PointListDrawMode = 3;
  29457. Material._LineListDrawMode = 4;
  29458. Material._LineLoopDrawMode = 5;
  29459. Material._LineStripDrawMode = 6;
  29460. Material._TriangleStripDrawMode = 7;
  29461. Material._TriangleFanDrawMode = 8;
  29462. Material._ClockWiseSideOrientation = 0;
  29463. Material._CounterClockWiseSideOrientation = 1;
  29464. Material._TextureDirtyFlag = 1;
  29465. Material._LightDirtyFlag = 2;
  29466. Material._FresnelDirtyFlag = 4;
  29467. Material._AttributesDirtyFlag = 8;
  29468. Material._MiscDirtyFlag = 16;
  29469. __decorate([
  29470. BABYLON.serialize()
  29471. ], Material.prototype, "id", void 0);
  29472. __decorate([
  29473. BABYLON.serialize()
  29474. ], Material.prototype, "name", void 0);
  29475. __decorate([
  29476. BABYLON.serialize()
  29477. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  29478. __decorate([
  29479. BABYLON.serialize()
  29480. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  29481. __decorate([
  29482. BABYLON.serialize()
  29483. ], Material.prototype, "state", void 0);
  29484. __decorate([
  29485. BABYLON.serialize("alpha")
  29486. ], Material.prototype, "_alpha", void 0);
  29487. __decorate([
  29488. BABYLON.serialize("backFaceCulling")
  29489. ], Material.prototype, "_backFaceCulling", void 0);
  29490. __decorate([
  29491. BABYLON.serialize()
  29492. ], Material.prototype, "sideOrientation", void 0);
  29493. __decorate([
  29494. BABYLON.serialize("alphaMode")
  29495. ], Material.prototype, "_alphaMode", void 0);
  29496. __decorate([
  29497. BABYLON.serialize()
  29498. ], Material.prototype, "_needDepthPrePass", void 0);
  29499. __decorate([
  29500. BABYLON.serialize()
  29501. ], Material.prototype, "disableDepthWrite", void 0);
  29502. __decorate([
  29503. BABYLON.serialize()
  29504. ], Material.prototype, "forceDepthWrite", void 0);
  29505. __decorate([
  29506. BABYLON.serialize()
  29507. ], Material.prototype, "separateCullingPass", void 0);
  29508. __decorate([
  29509. BABYLON.serialize("fogEnabled")
  29510. ], Material.prototype, "_fogEnabled", void 0);
  29511. __decorate([
  29512. BABYLON.serialize()
  29513. ], Material.prototype, "pointSize", void 0);
  29514. __decorate([
  29515. BABYLON.serialize()
  29516. ], Material.prototype, "zOffset", void 0);
  29517. __decorate([
  29518. BABYLON.serialize()
  29519. ], Material.prototype, "wireframe", null);
  29520. __decorate([
  29521. BABYLON.serialize()
  29522. ], Material.prototype, "pointsCloud", null);
  29523. __decorate([
  29524. BABYLON.serialize()
  29525. ], Material.prototype, "fillMode", null);
  29526. return Material;
  29527. }());
  29528. BABYLON.Material = Material;
  29529. })(BABYLON || (BABYLON = {}));
  29530. //# sourceMappingURL=babylon.material.js.map
  29531. var BABYLON;
  29532. (function (BABYLON) {
  29533. var UniformBuffer = /** @class */ (function () {
  29534. /**
  29535. * Uniform buffer objects.
  29536. *
  29537. * Handles blocks of uniform on the GPU.
  29538. *
  29539. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  29540. *
  29541. * For more information, please refer to :
  29542. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  29543. */
  29544. function UniformBuffer(engine, data, dynamic) {
  29545. this._engine = engine;
  29546. this._noUBO = !engine.supportsUniformBuffers;
  29547. this._dynamic = dynamic;
  29548. this._data = data || [];
  29549. this._uniformLocations = {};
  29550. this._uniformSizes = {};
  29551. this._uniformLocationPointer = 0;
  29552. this._needSync = false;
  29553. if (this._noUBO) {
  29554. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  29555. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  29556. this.updateFloat = this._updateFloatForEffect;
  29557. this.updateFloat2 = this._updateFloat2ForEffect;
  29558. this.updateFloat3 = this._updateFloat3ForEffect;
  29559. this.updateFloat4 = this._updateFloat4ForEffect;
  29560. this.updateMatrix = this._updateMatrixForEffect;
  29561. this.updateVector3 = this._updateVector3ForEffect;
  29562. this.updateVector4 = this._updateVector4ForEffect;
  29563. this.updateColor3 = this._updateColor3ForEffect;
  29564. this.updateColor4 = this._updateColor4ForEffect;
  29565. }
  29566. else {
  29567. this._engine._uniformBuffers.push(this);
  29568. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  29569. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  29570. this.updateFloat = this._updateFloatForUniform;
  29571. this.updateFloat2 = this._updateFloat2ForUniform;
  29572. this.updateFloat3 = this._updateFloat3ForUniform;
  29573. this.updateFloat4 = this._updateFloat4ForUniform;
  29574. this.updateMatrix = this._updateMatrixForUniform;
  29575. this.updateVector3 = this._updateVector3ForUniform;
  29576. this.updateVector4 = this._updateVector4ForUniform;
  29577. this.updateColor3 = this._updateColor3ForUniform;
  29578. this.updateColor4 = this._updateColor4ForUniform;
  29579. }
  29580. }
  29581. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  29582. // Properties
  29583. /**
  29584. * Indicates if the buffer is using the WebGL2 UBO implementation,
  29585. * or just falling back on setUniformXXX calls.
  29586. */
  29587. get: function () {
  29588. return !this._noUBO;
  29589. },
  29590. enumerable: true,
  29591. configurable: true
  29592. });
  29593. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  29594. /**
  29595. * Indicates if the WebGL underlying uniform buffer is in sync
  29596. * with the javascript cache data.
  29597. */
  29598. get: function () {
  29599. return !this._needSync;
  29600. },
  29601. enumerable: true,
  29602. configurable: true
  29603. });
  29604. /**
  29605. * Indicates if the WebGL underlying uniform buffer is dynamic.
  29606. * Also, a dynamic UniformBuffer will disable cache verification and always
  29607. * update the underlying WebGL uniform buffer to the GPU.
  29608. */
  29609. UniformBuffer.prototype.isDynamic = function () {
  29610. return this._dynamic !== undefined;
  29611. };
  29612. /**
  29613. * The data cache on JS side.
  29614. */
  29615. UniformBuffer.prototype.getData = function () {
  29616. return this._bufferData;
  29617. };
  29618. /**
  29619. * The underlying WebGL Uniform buffer.
  29620. */
  29621. UniformBuffer.prototype.getBuffer = function () {
  29622. return this._buffer;
  29623. };
  29624. /**
  29625. * std140 layout specifies how to align data within an UBO structure.
  29626. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  29627. * for specs.
  29628. */
  29629. UniformBuffer.prototype._fillAlignment = function (size) {
  29630. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  29631. // and 4x4 matrices
  29632. // TODO : change if other types are used
  29633. var alignment;
  29634. if (size <= 2) {
  29635. alignment = size;
  29636. }
  29637. else {
  29638. alignment = 4;
  29639. }
  29640. if ((this._uniformLocationPointer % alignment) !== 0) {
  29641. var oldPointer = this._uniformLocationPointer;
  29642. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  29643. var diff = this._uniformLocationPointer - oldPointer;
  29644. for (var i = 0; i < diff; i++) {
  29645. this._data.push(0);
  29646. }
  29647. }
  29648. };
  29649. /**
  29650. * Adds an uniform in the buffer.
  29651. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  29652. * for the layout to be correct !
  29653. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  29654. * @param {number|number[]} size Data size, or data directly.
  29655. */
  29656. UniformBuffer.prototype.addUniform = function (name, size) {
  29657. if (this._noUBO) {
  29658. return;
  29659. }
  29660. if (this._uniformLocations[name] !== undefined) {
  29661. // Already existing uniform
  29662. return;
  29663. }
  29664. // This function must be called in the order of the shader layout !
  29665. // size can be the size of the uniform, or data directly
  29666. var data;
  29667. if (size instanceof Array) {
  29668. data = size;
  29669. size = data.length;
  29670. }
  29671. else {
  29672. size = size;
  29673. data = [];
  29674. // Fill with zeros
  29675. for (var i = 0; i < size; i++) {
  29676. data.push(0);
  29677. }
  29678. }
  29679. this._fillAlignment(size);
  29680. this._uniformSizes[name] = size;
  29681. this._uniformLocations[name] = this._uniformLocationPointer;
  29682. this._uniformLocationPointer += size;
  29683. for (var i = 0; i < size; i++) {
  29684. this._data.push(data[i]);
  29685. }
  29686. this._needSync = true;
  29687. };
  29688. /**
  29689. * Wrapper for addUniform.
  29690. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  29691. * @param {Matrix} mat A 4x4 matrix.
  29692. */
  29693. UniformBuffer.prototype.addMatrix = function (name, mat) {
  29694. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  29695. };
  29696. /**
  29697. * Wrapper for addUniform.
  29698. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  29699. * @param {number} x
  29700. * @param {number} y
  29701. */
  29702. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  29703. var temp = [x, y];
  29704. this.addUniform(name, temp);
  29705. };
  29706. /**
  29707. * Wrapper for addUniform.
  29708. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  29709. * @param {number} x
  29710. * @param {number} y
  29711. * @param {number} z
  29712. */
  29713. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  29714. var temp = [x, y, z];
  29715. this.addUniform(name, temp);
  29716. };
  29717. /**
  29718. * Wrapper for addUniform.
  29719. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  29720. * @param {Color3} color
  29721. */
  29722. UniformBuffer.prototype.addColor3 = function (name, color) {
  29723. var temp = new Array();
  29724. color.toArray(temp);
  29725. this.addUniform(name, temp);
  29726. };
  29727. /**
  29728. * Wrapper for addUniform.
  29729. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  29730. * @param {Color3} color
  29731. * @param {number} alpha
  29732. */
  29733. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  29734. var temp = new Array();
  29735. color.toArray(temp);
  29736. temp.push(alpha);
  29737. this.addUniform(name, temp);
  29738. };
  29739. /**
  29740. * Wrapper for addUniform.
  29741. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  29742. * @param {Vector3} vector
  29743. */
  29744. UniformBuffer.prototype.addVector3 = function (name, vector) {
  29745. var temp = new Array();
  29746. vector.toArray(temp);
  29747. this.addUniform(name, temp);
  29748. };
  29749. /**
  29750. * Wrapper for addUniform.
  29751. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  29752. */
  29753. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  29754. this.addUniform(name, 12);
  29755. };
  29756. /**
  29757. * Wrapper for addUniform.
  29758. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  29759. */
  29760. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  29761. this.addUniform(name, 8);
  29762. };
  29763. /**
  29764. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  29765. */
  29766. UniformBuffer.prototype.create = function () {
  29767. if (this._noUBO) {
  29768. return;
  29769. }
  29770. if (this._buffer) {
  29771. return; // nothing to do
  29772. }
  29773. // See spec, alignment must be filled as a vec4
  29774. this._fillAlignment(4);
  29775. this._bufferData = new Float32Array(this._data);
  29776. this._rebuild();
  29777. this._needSync = true;
  29778. };
  29779. UniformBuffer.prototype._rebuild = function () {
  29780. if (this._noUBO) {
  29781. return;
  29782. }
  29783. if (this._dynamic) {
  29784. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  29785. }
  29786. else {
  29787. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  29788. }
  29789. };
  29790. /**
  29791. * Updates the WebGL Uniform Buffer on the GPU.
  29792. * If the `dynamic` flag is set to true, no cache comparison is done.
  29793. * Otherwise, the buffer will be updated only if the cache differs.
  29794. */
  29795. UniformBuffer.prototype.update = function () {
  29796. if (!this._buffer) {
  29797. this.create();
  29798. return;
  29799. }
  29800. if (!this._dynamic && !this._needSync) {
  29801. return;
  29802. }
  29803. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  29804. this._needSync = false;
  29805. };
  29806. /**
  29807. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  29808. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  29809. * @param {number[]|Float32Array} data Flattened data
  29810. * @param {number} size Size of the data.
  29811. */
  29812. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  29813. var location = this._uniformLocations[uniformName];
  29814. if (location === undefined) {
  29815. if (this._buffer) {
  29816. // Cannot add an uniform if the buffer is already created
  29817. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  29818. return;
  29819. }
  29820. this.addUniform(uniformName, size);
  29821. location = this._uniformLocations[uniformName];
  29822. }
  29823. if (!this._buffer) {
  29824. this.create();
  29825. }
  29826. if (!this._dynamic) {
  29827. // Cache for static uniform buffers
  29828. var changed = false;
  29829. for (var i = 0; i < size; i++) {
  29830. if (this._bufferData[location + i] !== data[i]) {
  29831. changed = true;
  29832. this._bufferData[location + i] = data[i];
  29833. }
  29834. }
  29835. this._needSync = this._needSync || changed;
  29836. }
  29837. else {
  29838. // No cache for dynamic
  29839. for (var i = 0; i < size; i++) {
  29840. this._bufferData[location + i] = data[i];
  29841. }
  29842. }
  29843. };
  29844. // Update methods
  29845. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  29846. // To match std140, matrix must be realigned
  29847. for (var i = 0; i < 3; i++) {
  29848. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  29849. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  29850. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  29851. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  29852. }
  29853. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  29854. };
  29855. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  29856. this._currentEffect.setMatrix3x3(name, matrix);
  29857. };
  29858. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  29859. this._currentEffect.setMatrix2x2(name, matrix);
  29860. };
  29861. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  29862. // To match std140, matrix must be realigned
  29863. for (var i = 0; i < 2; i++) {
  29864. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  29865. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  29866. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  29867. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  29868. }
  29869. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  29870. };
  29871. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  29872. this._currentEffect.setFloat(name, x);
  29873. };
  29874. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  29875. UniformBuffer._tempBuffer[0] = x;
  29876. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  29877. };
  29878. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  29879. if (suffix === void 0) { suffix = ""; }
  29880. this._currentEffect.setFloat2(name + suffix, x, y);
  29881. };
  29882. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  29883. if (suffix === void 0) { suffix = ""; }
  29884. UniformBuffer._tempBuffer[0] = x;
  29885. UniformBuffer._tempBuffer[1] = y;
  29886. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  29887. };
  29888. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  29889. if (suffix === void 0) { suffix = ""; }
  29890. this._currentEffect.setFloat3(name + suffix, x, y, z);
  29891. };
  29892. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  29893. if (suffix === void 0) { suffix = ""; }
  29894. UniformBuffer._tempBuffer[0] = x;
  29895. UniformBuffer._tempBuffer[1] = y;
  29896. UniformBuffer._tempBuffer[2] = z;
  29897. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  29898. };
  29899. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  29900. if (suffix === void 0) { suffix = ""; }
  29901. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  29902. };
  29903. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  29904. if (suffix === void 0) { suffix = ""; }
  29905. UniformBuffer._tempBuffer[0] = x;
  29906. UniformBuffer._tempBuffer[1] = y;
  29907. UniformBuffer._tempBuffer[2] = z;
  29908. UniformBuffer._tempBuffer[3] = w;
  29909. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  29910. };
  29911. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  29912. this._currentEffect.setMatrix(name, mat);
  29913. };
  29914. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  29915. this.updateUniform(name, mat.toArray(), 16);
  29916. };
  29917. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  29918. this._currentEffect.setVector3(name, vector);
  29919. };
  29920. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  29921. vector.toArray(UniformBuffer._tempBuffer);
  29922. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  29923. };
  29924. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  29925. this._currentEffect.setVector4(name, vector);
  29926. };
  29927. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  29928. vector.toArray(UniformBuffer._tempBuffer);
  29929. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  29930. };
  29931. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  29932. if (suffix === void 0) { suffix = ""; }
  29933. this._currentEffect.setColor3(name + suffix, color);
  29934. };
  29935. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  29936. if (suffix === void 0) { suffix = ""; }
  29937. color.toArray(UniformBuffer._tempBuffer);
  29938. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  29939. };
  29940. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  29941. if (suffix === void 0) { suffix = ""; }
  29942. this._currentEffect.setColor4(name + suffix, color, alpha);
  29943. };
  29944. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  29945. if (suffix === void 0) { suffix = ""; }
  29946. color.toArray(UniformBuffer._tempBuffer);
  29947. UniformBuffer._tempBuffer[3] = alpha;
  29948. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  29949. };
  29950. /**
  29951. * Sets a sampler uniform on the effect.
  29952. * @param {string} name Name of the sampler.
  29953. * @param {Texture} texture
  29954. */
  29955. UniformBuffer.prototype.setTexture = function (name, texture) {
  29956. this._currentEffect.setTexture(name, texture);
  29957. };
  29958. /**
  29959. * Directly updates the value of the uniform in the cache AND on the GPU.
  29960. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  29961. * @param {number[]|Float32Array} data Flattened data
  29962. */
  29963. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  29964. this.updateUniform(uniformName, data, data.length);
  29965. this.update();
  29966. };
  29967. /**
  29968. * Binds this uniform buffer to an effect.
  29969. * @param {Effect} effect
  29970. * @param {string} name Name of the uniform block in the shader.
  29971. */
  29972. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  29973. this._currentEffect = effect;
  29974. if (this._noUBO || !this._buffer) {
  29975. return;
  29976. }
  29977. effect.bindUniformBuffer(this._buffer, name);
  29978. };
  29979. /**
  29980. * Disposes the uniform buffer.
  29981. */
  29982. UniformBuffer.prototype.dispose = function () {
  29983. if (this._noUBO) {
  29984. return;
  29985. }
  29986. var index = this._engine._uniformBuffers.indexOf(this);
  29987. if (index !== -1) {
  29988. this._engine._uniformBuffers.splice(index, 1);
  29989. }
  29990. if (!this._buffer) {
  29991. return;
  29992. }
  29993. if (this._engine._releaseBuffer(this._buffer)) {
  29994. this._buffer = null;
  29995. }
  29996. };
  29997. // Pool for avoiding memory leaks
  29998. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  29999. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  30000. return UniformBuffer;
  30001. }());
  30002. BABYLON.UniformBuffer = UniformBuffer;
  30003. })(BABYLON || (BABYLON = {}));
  30004. //# sourceMappingURL=babylon.uniformBuffer.js.map
  30005. var BABYLON;
  30006. (function (BABYLON) {
  30007. var VertexData = /** @class */ (function () {
  30008. function VertexData() {
  30009. }
  30010. VertexData.prototype.set = function (data, kind) {
  30011. switch (kind) {
  30012. case BABYLON.VertexBuffer.PositionKind:
  30013. this.positions = data;
  30014. break;
  30015. case BABYLON.VertexBuffer.NormalKind:
  30016. this.normals = data;
  30017. break;
  30018. case BABYLON.VertexBuffer.TangentKind:
  30019. this.tangents = data;
  30020. break;
  30021. case BABYLON.VertexBuffer.UVKind:
  30022. this.uvs = data;
  30023. break;
  30024. case BABYLON.VertexBuffer.UV2Kind:
  30025. this.uvs2 = data;
  30026. break;
  30027. case BABYLON.VertexBuffer.UV3Kind:
  30028. this.uvs3 = data;
  30029. break;
  30030. case BABYLON.VertexBuffer.UV4Kind:
  30031. this.uvs4 = data;
  30032. break;
  30033. case BABYLON.VertexBuffer.UV5Kind:
  30034. this.uvs5 = data;
  30035. break;
  30036. case BABYLON.VertexBuffer.UV6Kind:
  30037. this.uvs6 = data;
  30038. break;
  30039. case BABYLON.VertexBuffer.ColorKind:
  30040. this.colors = data;
  30041. break;
  30042. case BABYLON.VertexBuffer.MatricesIndicesKind:
  30043. this.matricesIndices = data;
  30044. break;
  30045. case BABYLON.VertexBuffer.MatricesWeightsKind:
  30046. this.matricesWeights = data;
  30047. break;
  30048. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  30049. this.matricesIndicesExtra = data;
  30050. break;
  30051. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  30052. this.matricesWeightsExtra = data;
  30053. break;
  30054. }
  30055. };
  30056. /**
  30057. * Associates the vertexData to the passed Mesh.
  30058. * Sets it as updatable or not (default `false`).
  30059. * Returns the VertexData.
  30060. */
  30061. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  30062. this._applyTo(mesh, updatable);
  30063. return this;
  30064. };
  30065. /**
  30066. * Associates the vertexData to the passed Geometry.
  30067. * Sets it as updatable or not (default `false`).
  30068. * Returns the VertexData.
  30069. */
  30070. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  30071. this._applyTo(geometry, updatable);
  30072. return this;
  30073. };
  30074. /**
  30075. * Updates the associated mesh.
  30076. * Returns the VertexData.
  30077. */
  30078. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  30079. this._update(mesh);
  30080. return this;
  30081. };
  30082. /**
  30083. * Updates the associated geometry.
  30084. * Returns the VertexData.
  30085. */
  30086. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  30087. this._update(geometry);
  30088. return this;
  30089. };
  30090. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  30091. if (updatable === void 0) { updatable = false; }
  30092. if (this.positions) {
  30093. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  30094. }
  30095. if (this.normals) {
  30096. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  30097. }
  30098. if (this.tangents) {
  30099. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  30100. }
  30101. if (this.uvs) {
  30102. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  30103. }
  30104. if (this.uvs2) {
  30105. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  30106. }
  30107. if (this.uvs3) {
  30108. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  30109. }
  30110. if (this.uvs4) {
  30111. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  30112. }
  30113. if (this.uvs5) {
  30114. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  30115. }
  30116. if (this.uvs6) {
  30117. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  30118. }
  30119. if (this.colors) {
  30120. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  30121. }
  30122. if (this.matricesIndices) {
  30123. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  30124. }
  30125. if (this.matricesWeights) {
  30126. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  30127. }
  30128. if (this.matricesIndicesExtra) {
  30129. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  30130. }
  30131. if (this.matricesWeightsExtra) {
  30132. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  30133. }
  30134. if (this.indices) {
  30135. meshOrGeometry.setIndices(this.indices, null, updatable);
  30136. }
  30137. return this;
  30138. };
  30139. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  30140. if (this.positions) {
  30141. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  30142. }
  30143. if (this.normals) {
  30144. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  30145. }
  30146. if (this.tangents) {
  30147. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  30148. }
  30149. if (this.uvs) {
  30150. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  30151. }
  30152. if (this.uvs2) {
  30153. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  30154. }
  30155. if (this.uvs3) {
  30156. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  30157. }
  30158. if (this.uvs4) {
  30159. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  30160. }
  30161. if (this.uvs5) {
  30162. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  30163. }
  30164. if (this.uvs6) {
  30165. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  30166. }
  30167. if (this.colors) {
  30168. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  30169. }
  30170. if (this.matricesIndices) {
  30171. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  30172. }
  30173. if (this.matricesWeights) {
  30174. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  30175. }
  30176. if (this.matricesIndicesExtra) {
  30177. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  30178. }
  30179. if (this.matricesWeightsExtra) {
  30180. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  30181. }
  30182. if (this.indices) {
  30183. meshOrGeometry.setIndices(this.indices, null);
  30184. }
  30185. return this;
  30186. };
  30187. /**
  30188. * Transforms each position and each normal of the vertexData according to the passed Matrix.
  30189. * Returns the VertexData.
  30190. */
  30191. VertexData.prototype.transform = function (matrix) {
  30192. var transformed = BABYLON.Vector3.Zero();
  30193. var index;
  30194. if (this.positions) {
  30195. var position = BABYLON.Vector3.Zero();
  30196. for (index = 0; index < this.positions.length; index += 3) {
  30197. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  30198. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  30199. this.positions[index] = transformed.x;
  30200. this.positions[index + 1] = transformed.y;
  30201. this.positions[index + 2] = transformed.z;
  30202. }
  30203. }
  30204. if (this.normals) {
  30205. var normal = BABYLON.Vector3.Zero();
  30206. for (index = 0; index < this.normals.length; index += 3) {
  30207. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  30208. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  30209. this.normals[index] = transformed.x;
  30210. this.normals[index + 1] = transformed.y;
  30211. this.normals[index + 2] = transformed.z;
  30212. }
  30213. }
  30214. if (this.tangents) {
  30215. var tangent = BABYLON.Vector4.Zero();
  30216. var tangentTransformed = BABYLON.Vector4.Zero();
  30217. for (index = 0; index < this.tangents.length; index += 4) {
  30218. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  30219. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  30220. this.tangents[index] = tangentTransformed.x;
  30221. this.tangents[index + 1] = tangentTransformed.y;
  30222. this.tangents[index + 2] = tangentTransformed.z;
  30223. this.tangents[index + 3] = tangentTransformed.w;
  30224. }
  30225. }
  30226. return this;
  30227. };
  30228. /**
  30229. * Merges the passed VertexData into the current one.
  30230. * Returns the modified VertexData.
  30231. */
  30232. VertexData.prototype.merge = function (other, options) {
  30233. options = options || {};
  30234. if (other.indices) {
  30235. if (!this.indices) {
  30236. this.indices = [];
  30237. }
  30238. var offset = this.positions ? this.positions.length / 3 : 0;
  30239. for (var index = 0; index < other.indices.length; index++) {
  30240. //TODO check type - if Int32Array | Uint32Array | Uint16Array!
  30241. this.indices.push(other.indices[index] + offset);
  30242. }
  30243. }
  30244. this.positions = this._mergeElement(this.positions, other.positions);
  30245. if (!this.positions) {
  30246. return this;
  30247. }
  30248. var count = this.positions.length / 3;
  30249. this.normals = this._mergeElement(this.normals, other.normals, count * 3);
  30250. this.tangents = this._mergeElement(this.tangents, other.tangents, count * (options.tangentLength || 4));
  30251. this.uvs = this._mergeElement(this.uvs, other.uvs, count * 2);
  30252. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2, count * 2);
  30253. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3, count * 2);
  30254. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4, count * 2);
  30255. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5, count * 2);
  30256. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6, count * 2);
  30257. this.colors = this._mergeElement(this.colors, other.colors, count * 4, 1);
  30258. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices, count * 4);
  30259. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights, count * 4);
  30260. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra, count * 4);
  30261. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra, count * 4);
  30262. return this;
  30263. };
  30264. VertexData.prototype._mergeElement = function (source, other, length, defaultValue) {
  30265. if (length === void 0) { length = 0; }
  30266. if (defaultValue === void 0) { defaultValue = 0; }
  30267. if (!other && !source) {
  30268. return null;
  30269. }
  30270. if (!other) {
  30271. var padding = new Float32Array(source.length);
  30272. padding.fill(defaultValue);
  30273. return this._mergeElement(source, padding, length);
  30274. }
  30275. if (!source) {
  30276. if (length === 0 || length === other.length) {
  30277. return other;
  30278. }
  30279. var padding = new Float32Array(length - other.length);
  30280. padding.fill(defaultValue);
  30281. return this._mergeElement(padding, other, length);
  30282. }
  30283. var len = other.length + source.length;
  30284. var isSrcTypedArray = source instanceof Float32Array;
  30285. var isOthTypedArray = other instanceof Float32Array;
  30286. // use non-loop method when the source is Float32Array
  30287. if (isSrcTypedArray) {
  30288. var ret32 = new Float32Array(len);
  30289. ret32.set(source);
  30290. ret32.set(other, source.length);
  30291. return ret32;
  30292. // source is number[], when other is also use concat
  30293. }
  30294. else if (!isOthTypedArray) {
  30295. return source.concat(other);
  30296. // source is a number[], but other is a Float32Array, loop required
  30297. }
  30298. else {
  30299. var ret = source.slice(0); // copy source to a separate array
  30300. for (var i = 0, len = other.length; i < len; i++) {
  30301. ret.push(other[i]);
  30302. }
  30303. return ret;
  30304. }
  30305. };
  30306. /**
  30307. * Serializes the VertexData.
  30308. * Returns a serialized object.
  30309. */
  30310. VertexData.prototype.serialize = function () {
  30311. var serializationObject = this.serialize();
  30312. if (this.positions) {
  30313. serializationObject.positions = this.positions;
  30314. }
  30315. if (this.normals) {
  30316. serializationObject.normals = this.normals;
  30317. }
  30318. if (this.tangents) {
  30319. serializationObject.tangents = this.tangents;
  30320. }
  30321. if (this.uvs) {
  30322. serializationObject.uvs = this.uvs;
  30323. }
  30324. if (this.uvs2) {
  30325. serializationObject.uvs2 = this.uvs2;
  30326. }
  30327. if (this.uvs3) {
  30328. serializationObject.uvs3 = this.uvs3;
  30329. }
  30330. if (this.uvs4) {
  30331. serializationObject.uvs4 = this.uvs4;
  30332. }
  30333. if (this.uvs5) {
  30334. serializationObject.uvs5 = this.uvs5;
  30335. }
  30336. if (this.uvs6) {
  30337. serializationObject.uvs6 = this.uvs6;
  30338. }
  30339. if (this.colors) {
  30340. serializationObject.colors = this.colors;
  30341. }
  30342. if (this.matricesIndices) {
  30343. serializationObject.matricesIndices = this.matricesIndices;
  30344. serializationObject.matricesIndices._isExpanded = true;
  30345. }
  30346. if (this.matricesWeights) {
  30347. serializationObject.matricesWeights = this.matricesWeights;
  30348. }
  30349. if (this.matricesIndicesExtra) {
  30350. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  30351. serializationObject.matricesIndicesExtra._isExpanded = true;
  30352. }
  30353. if (this.matricesWeightsExtra) {
  30354. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  30355. }
  30356. serializationObject.indices = this.indices;
  30357. return serializationObject;
  30358. };
  30359. // Statics
  30360. /**
  30361. * Returns the object VertexData associated to the passed mesh.
  30362. */
  30363. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  30364. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  30365. };
  30366. /**
  30367. * Returns the object VertexData associated to the passed geometry.
  30368. */
  30369. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  30370. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  30371. };
  30372. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  30373. var result = new VertexData();
  30374. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  30375. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  30376. }
  30377. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  30378. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  30379. }
  30380. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  30381. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  30382. }
  30383. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  30384. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  30385. }
  30386. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  30387. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  30388. }
  30389. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  30390. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  30391. }
  30392. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  30393. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  30394. }
  30395. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  30396. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  30397. }
  30398. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  30399. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  30400. }
  30401. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  30402. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  30403. }
  30404. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  30405. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  30406. }
  30407. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  30408. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  30409. }
  30410. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  30411. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  30412. }
  30413. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  30414. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  30415. }
  30416. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  30417. return result;
  30418. };
  30419. /**
  30420. * Creates the vertexData of the Ribbon.
  30421. */
  30422. VertexData.CreateRibbon = function (options) {
  30423. var pathArray = options.pathArray;
  30424. var closeArray = options.closeArray || false;
  30425. var closePath = options.closePath || false;
  30426. var invertUV = options.invertUV || false;
  30427. var defaultOffset = Math.floor(pathArray[0].length / 2);
  30428. var offset = options.offset || defaultOffset;
  30429. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  30430. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  30431. var customUV = options.uvs;
  30432. var customColors = options.colors;
  30433. var positions = [];
  30434. var indices = [];
  30435. var normals = [];
  30436. var uvs = [];
  30437. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  30438. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  30439. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  30440. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  30441. var minlg; // minimal length among all paths from pathArray
  30442. var lg = []; // array of path lengths : nb of vertex per path
  30443. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  30444. var p; // path iterator
  30445. var i; // point iterator
  30446. var j; // point iterator
  30447. // if single path in pathArray
  30448. if (pathArray.length < 2) {
  30449. var ar1 = [];
  30450. var ar2 = [];
  30451. for (i = 0; i < pathArray[0].length - offset; i++) {
  30452. ar1.push(pathArray[0][i]);
  30453. ar2.push(pathArray[0][i + offset]);
  30454. }
  30455. pathArray = [ar1, ar2];
  30456. }
  30457. // positions and horizontal distances (u)
  30458. var idc = 0;
  30459. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  30460. var path;
  30461. var l;
  30462. minlg = pathArray[0].length;
  30463. var vectlg;
  30464. var dist;
  30465. for (p = 0; p < pathArray.length; p++) {
  30466. uTotalDistance[p] = 0;
  30467. us[p] = [0];
  30468. path = pathArray[p];
  30469. l = path.length;
  30470. minlg = (minlg < l) ? minlg : l;
  30471. j = 0;
  30472. while (j < l) {
  30473. positions.push(path[j].x, path[j].y, path[j].z);
  30474. if (j > 0) {
  30475. vectlg = path[j].subtract(path[j - 1]).length();
  30476. dist = vectlg + uTotalDistance[p];
  30477. us[p].push(dist);
  30478. uTotalDistance[p] = dist;
  30479. }
  30480. j++;
  30481. }
  30482. if (closePath) {
  30483. j--;
  30484. positions.push(path[0].x, path[0].y, path[0].z);
  30485. vectlg = path[j].subtract(path[0]).length();
  30486. dist = vectlg + uTotalDistance[p];
  30487. us[p].push(dist);
  30488. uTotalDistance[p] = dist;
  30489. }
  30490. lg[p] = l + closePathCorr;
  30491. idx[p] = idc;
  30492. idc += (l + closePathCorr);
  30493. }
  30494. // vertical distances (v)
  30495. var path1;
  30496. var path2;
  30497. var vertex1 = null;
  30498. var vertex2 = null;
  30499. for (i = 0; i < minlg + closePathCorr; i++) {
  30500. vTotalDistance[i] = 0;
  30501. vs[i] = [0];
  30502. for (p = 0; p < pathArray.length - 1; p++) {
  30503. path1 = pathArray[p];
  30504. path2 = pathArray[p + 1];
  30505. if (i === minlg) {
  30506. vertex1 = path1[0];
  30507. vertex2 = path2[0];
  30508. }
  30509. else {
  30510. vertex1 = path1[i];
  30511. vertex2 = path2[i];
  30512. }
  30513. vectlg = vertex2.subtract(vertex1).length();
  30514. dist = vectlg + vTotalDistance[i];
  30515. vs[i].push(dist);
  30516. vTotalDistance[i] = dist;
  30517. }
  30518. if (closeArray && vertex2 && vertex1) {
  30519. path1 = pathArray[p];
  30520. path2 = pathArray[0];
  30521. if (i === minlg) {
  30522. vertex2 = path2[0];
  30523. }
  30524. vectlg = vertex2.subtract(vertex1).length();
  30525. dist = vectlg + vTotalDistance[i];
  30526. vTotalDistance[i] = dist;
  30527. }
  30528. }
  30529. // uvs
  30530. var u;
  30531. var v;
  30532. if (customUV) {
  30533. for (p = 0; p < customUV.length; p++) {
  30534. uvs.push(customUV[p].x, customUV[p].y);
  30535. }
  30536. }
  30537. else {
  30538. for (p = 0; p < pathArray.length; p++) {
  30539. for (i = 0; i < minlg + closePathCorr; i++) {
  30540. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  30541. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  30542. if (invertUV) {
  30543. uvs.push(v, u);
  30544. }
  30545. else {
  30546. uvs.push(u, v);
  30547. }
  30548. }
  30549. }
  30550. }
  30551. // indices
  30552. p = 0; // path index
  30553. var pi = 0; // positions array index
  30554. var l1 = lg[p] - 1; // path1 length
  30555. var l2 = lg[p + 1] - 1; // path2 length
  30556. var min = (l1 < l2) ? l1 : l2; // current path stop index
  30557. var shft = idx[1] - idx[0]; // shift
  30558. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  30559. while (pi <= min && p < path1nb) {
  30560. // 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
  30561. indices.push(pi, pi + shft, pi + 1);
  30562. indices.push(pi + shft + 1, pi + 1, pi + shft);
  30563. pi += 1;
  30564. if (pi === min) {
  30565. p++;
  30566. if (p === lg.length - 1) {
  30567. shft = idx[0] - idx[p];
  30568. l1 = lg[p] - 1;
  30569. l2 = lg[0] - 1;
  30570. }
  30571. else {
  30572. shft = idx[p + 1] - idx[p];
  30573. l1 = lg[p] - 1;
  30574. l2 = lg[p + 1] - 1;
  30575. }
  30576. pi = idx[p];
  30577. min = (l1 < l2) ? l1 + pi : l2 + pi;
  30578. }
  30579. }
  30580. // normals
  30581. VertexData.ComputeNormals(positions, indices, normals);
  30582. if (closePath) {
  30583. var indexFirst = 0;
  30584. var indexLast = 0;
  30585. for (p = 0; p < pathArray.length; p++) {
  30586. indexFirst = idx[p] * 3;
  30587. if (p + 1 < pathArray.length) {
  30588. indexLast = (idx[p + 1] - 1) * 3;
  30589. }
  30590. else {
  30591. indexLast = normals.length - 3;
  30592. }
  30593. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  30594. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  30595. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  30596. normals[indexLast] = normals[indexFirst];
  30597. normals[indexLast + 1] = normals[indexFirst + 1];
  30598. normals[indexLast + 2] = normals[indexFirst + 2];
  30599. }
  30600. }
  30601. // sides
  30602. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  30603. // Colors
  30604. var colors = null;
  30605. if (customColors) {
  30606. colors = new Float32Array(customColors.length * 4);
  30607. for (var c = 0; c < customColors.length; c++) {
  30608. colors[c * 4] = customColors[c].r;
  30609. colors[c * 4 + 1] = customColors[c].g;
  30610. colors[c * 4 + 2] = customColors[c].b;
  30611. colors[c * 4 + 3] = customColors[c].a;
  30612. }
  30613. }
  30614. // Result
  30615. var vertexData = new VertexData();
  30616. var positions32 = new Float32Array(positions);
  30617. var normals32 = new Float32Array(normals);
  30618. var uvs32 = new Float32Array(uvs);
  30619. vertexData.indices = indices;
  30620. vertexData.positions = positions32;
  30621. vertexData.normals = normals32;
  30622. vertexData.uvs = uvs32;
  30623. if (colors) {
  30624. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  30625. }
  30626. if (closePath) {
  30627. vertexData._idx = idx;
  30628. }
  30629. return vertexData;
  30630. };
  30631. /**
  30632. * Creates the VertexData of the Box.
  30633. */
  30634. VertexData.CreateBox = function (options) {
  30635. var normalsSource = [
  30636. new BABYLON.Vector3(0, 0, 1),
  30637. new BABYLON.Vector3(0, 0, -1),
  30638. new BABYLON.Vector3(1, 0, 0),
  30639. new BABYLON.Vector3(-1, 0, 0),
  30640. new BABYLON.Vector3(0, 1, 0),
  30641. new BABYLON.Vector3(0, -1, 0)
  30642. ];
  30643. var indices = [];
  30644. var positions = [];
  30645. var normals = [];
  30646. var uvs = [];
  30647. var width = options.width || options.size || 1;
  30648. var height = options.height || options.size || 1;
  30649. var depth = options.depth || options.size || 1;
  30650. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  30651. var faceUV = options.faceUV || new Array(6);
  30652. var faceColors = options.faceColors;
  30653. var colors = [];
  30654. // default face colors and UV if undefined
  30655. for (var f = 0; f < 6; f++) {
  30656. if (faceUV[f] === undefined) {
  30657. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  30658. }
  30659. if (faceColors && faceColors[f] === undefined) {
  30660. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  30661. }
  30662. }
  30663. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  30664. // Create each face in turn.
  30665. for (var index = 0; index < normalsSource.length; index++) {
  30666. var normal = normalsSource[index];
  30667. // Get two vectors perpendicular to the face normal and to each other.
  30668. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  30669. var side2 = BABYLON.Vector3.Cross(normal, side1);
  30670. // Six indices (two triangles) per face.
  30671. var verticesLength = positions.length / 3;
  30672. indices.push(verticesLength);
  30673. indices.push(verticesLength + 1);
  30674. indices.push(verticesLength + 2);
  30675. indices.push(verticesLength);
  30676. indices.push(verticesLength + 2);
  30677. indices.push(verticesLength + 3);
  30678. // Four vertices per face.
  30679. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  30680. positions.push(vertex.x, vertex.y, vertex.z);
  30681. normals.push(normal.x, normal.y, normal.z);
  30682. uvs.push(faceUV[index].z, faceUV[index].w);
  30683. if (faceColors) {
  30684. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  30685. }
  30686. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  30687. positions.push(vertex.x, vertex.y, vertex.z);
  30688. normals.push(normal.x, normal.y, normal.z);
  30689. uvs.push(faceUV[index].x, faceUV[index].w);
  30690. if (faceColors) {
  30691. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  30692. }
  30693. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  30694. positions.push(vertex.x, vertex.y, vertex.z);
  30695. normals.push(normal.x, normal.y, normal.z);
  30696. uvs.push(faceUV[index].x, faceUV[index].y);
  30697. if (faceColors) {
  30698. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  30699. }
  30700. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  30701. positions.push(vertex.x, vertex.y, vertex.z);
  30702. normals.push(normal.x, normal.y, normal.z);
  30703. uvs.push(faceUV[index].z, faceUV[index].y);
  30704. if (faceColors) {
  30705. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  30706. }
  30707. }
  30708. // sides
  30709. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  30710. // Result
  30711. var vertexData = new VertexData();
  30712. vertexData.indices = indices;
  30713. vertexData.positions = positions;
  30714. vertexData.normals = normals;
  30715. vertexData.uvs = uvs;
  30716. if (faceColors) {
  30717. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  30718. vertexData.colors = totalColors;
  30719. }
  30720. return vertexData;
  30721. };
  30722. /**
  30723. * Creates the VertexData of the Sphere.
  30724. */
  30725. VertexData.CreateSphere = function (options) {
  30726. var segments = options.segments || 32;
  30727. var diameterX = options.diameterX || options.diameter || 1;
  30728. var diameterY = options.diameterY || options.diameter || 1;
  30729. var diameterZ = options.diameterZ || options.diameter || 1;
  30730. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  30731. var slice = options.slice && (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  30732. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  30733. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  30734. var totalZRotationSteps = 2 + segments;
  30735. var totalYRotationSteps = 2 * totalZRotationSteps;
  30736. var indices = [];
  30737. var positions = [];
  30738. var normals = [];
  30739. var uvs = [];
  30740. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  30741. var normalizedZ = zRotationStep / totalZRotationSteps;
  30742. var angleZ = normalizedZ * Math.PI * slice;
  30743. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  30744. var normalizedY = yRotationStep / totalYRotationSteps;
  30745. var angleY = normalizedY * Math.PI * 2 * arc;
  30746. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  30747. var rotationY = BABYLON.Matrix.RotationY(angleY);
  30748. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  30749. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  30750. var vertex = complete.multiply(radius);
  30751. var normal = complete.divide(radius).normalize();
  30752. positions.push(vertex.x, vertex.y, vertex.z);
  30753. normals.push(normal.x, normal.y, normal.z);
  30754. uvs.push(normalizedY, normalizedZ);
  30755. }
  30756. if (zRotationStep > 0) {
  30757. var verticesCount = positions.length / 3;
  30758. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  30759. indices.push((firstIndex));
  30760. indices.push((firstIndex + 1));
  30761. indices.push(firstIndex + totalYRotationSteps + 1);
  30762. indices.push((firstIndex + totalYRotationSteps + 1));
  30763. indices.push((firstIndex + 1));
  30764. indices.push((firstIndex + totalYRotationSteps + 2));
  30765. }
  30766. }
  30767. }
  30768. // Sides
  30769. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  30770. // Result
  30771. var vertexData = new VertexData();
  30772. vertexData.indices = indices;
  30773. vertexData.positions = positions;
  30774. vertexData.normals = normals;
  30775. vertexData.uvs = uvs;
  30776. return vertexData;
  30777. };
  30778. /**
  30779. * Creates the VertexData of the Cylinder or Cone.
  30780. */
  30781. VertexData.CreateCylinder = function (options) {
  30782. var height = options.height || 2;
  30783. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  30784. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  30785. var tessellation = options.tessellation || 24;
  30786. var subdivisions = options.subdivisions || 1;
  30787. var hasRings = options.hasRings ? true : false;
  30788. var enclose = options.enclose ? true : false;
  30789. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  30790. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  30791. var faceUV = options.faceUV || new Array(3);
  30792. var faceColors = options.faceColors;
  30793. // default face colors and UV if undefined
  30794. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  30795. var ringNb = (hasRings) ? subdivisions : 1;
  30796. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  30797. var f;
  30798. for (f = 0; f < surfaceNb; f++) {
  30799. if (faceColors && faceColors[f] === undefined) {
  30800. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  30801. }
  30802. }
  30803. for (f = 0; f < surfaceNb; f++) {
  30804. if (faceUV && faceUV[f] === undefined) {
  30805. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  30806. }
  30807. }
  30808. var indices = new Array();
  30809. var positions = new Array();
  30810. var normals = new Array();
  30811. var uvs = new Array();
  30812. var colors = new Array();
  30813. var angle_step = Math.PI * 2 * arc / tessellation;
  30814. var angle;
  30815. var h;
  30816. var radius;
  30817. var tan = (diameterBottom - diameterTop) / 2 / height;
  30818. var ringVertex = BABYLON.Vector3.Zero();
  30819. var ringNormal = BABYLON.Vector3.Zero();
  30820. var ringFirstVertex = BABYLON.Vector3.Zero();
  30821. var ringFirstNormal = BABYLON.Vector3.Zero();
  30822. var quadNormal = BABYLON.Vector3.Zero();
  30823. var Y = BABYLON.Axis.Y;
  30824. // positions, normals, uvs
  30825. var i;
  30826. var j;
  30827. var r;
  30828. var ringIdx = 1;
  30829. var s = 1; // surface index
  30830. var cs = 0;
  30831. var v = 0;
  30832. for (i = 0; i <= subdivisions; i++) {
  30833. h = i / subdivisions;
  30834. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  30835. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  30836. for (r = 0; r < ringIdx; r++) {
  30837. if (hasRings) {
  30838. s += r;
  30839. }
  30840. if (enclose) {
  30841. s += 2 * r;
  30842. }
  30843. for (j = 0; j <= tessellation; j++) {
  30844. angle = j * angle_step;
  30845. // position
  30846. ringVertex.x = Math.cos(-angle) * radius;
  30847. ringVertex.y = -height / 2 + h * height;
  30848. ringVertex.z = Math.sin(-angle) * radius;
  30849. // normal
  30850. if (diameterTop === 0 && i === subdivisions) {
  30851. // if no top cap, reuse former normals
  30852. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  30853. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  30854. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  30855. }
  30856. else {
  30857. ringNormal.x = ringVertex.x;
  30858. ringNormal.z = ringVertex.z;
  30859. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  30860. ringNormal.normalize();
  30861. }
  30862. // keep first ring vertex values for enclose
  30863. if (j === 0) {
  30864. ringFirstVertex.copyFrom(ringVertex);
  30865. ringFirstNormal.copyFrom(ringNormal);
  30866. }
  30867. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  30868. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  30869. if (hasRings) {
  30870. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  30871. }
  30872. else {
  30873. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  30874. }
  30875. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  30876. if (faceColors) {
  30877. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  30878. }
  30879. }
  30880. // if enclose, add four vertices and their dedicated normals
  30881. if (arc !== 1 && enclose) {
  30882. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  30883. positions.push(0, ringVertex.y, 0);
  30884. positions.push(0, ringVertex.y, 0);
  30885. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  30886. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  30887. quadNormal.normalize();
  30888. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  30889. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  30890. quadNormal.normalize();
  30891. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  30892. if (hasRings) {
  30893. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  30894. }
  30895. else {
  30896. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  30897. }
  30898. uvs.push(faceUV[s + 1].x, v);
  30899. uvs.push(faceUV[s + 1].z, v);
  30900. if (hasRings) {
  30901. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  30902. }
  30903. else {
  30904. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  30905. }
  30906. uvs.push(faceUV[s + 2].x, v);
  30907. uvs.push(faceUV[s + 2].z, v);
  30908. if (faceColors) {
  30909. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  30910. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  30911. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  30912. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  30913. }
  30914. }
  30915. if (cs !== s) {
  30916. cs = s;
  30917. }
  30918. }
  30919. }
  30920. // indices
  30921. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  30922. var s;
  30923. i = 0;
  30924. for (s = 0; s < subdivisions; s++) {
  30925. var i0 = 0;
  30926. var i1 = 0;
  30927. var i2 = 0;
  30928. var i3 = 0;
  30929. for (j = 0; j < tessellation; j++) {
  30930. i0 = i * (e + 1) + j;
  30931. i1 = (i + 1) * (e + 1) + j;
  30932. i2 = i * (e + 1) + (j + 1);
  30933. i3 = (i + 1) * (e + 1) + (j + 1);
  30934. indices.push(i0, i1, i2);
  30935. indices.push(i3, i2, i1);
  30936. }
  30937. if (arc !== 1 && enclose) {
  30938. indices.push(i0 + 2, i1 + 2, i2 + 2);
  30939. indices.push(i3 + 2, i2 + 2, i1 + 2);
  30940. indices.push(i0 + 4, i1 + 4, i2 + 4);
  30941. indices.push(i3 + 4, i2 + 4, i1 + 4);
  30942. }
  30943. i = (hasRings) ? (i + 2) : (i + 1);
  30944. }
  30945. // Caps
  30946. var createCylinderCap = function (isTop) {
  30947. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  30948. if (radius === 0) {
  30949. return;
  30950. }
  30951. // Cap positions, normals & uvs
  30952. var angle;
  30953. var circleVector;
  30954. var i;
  30955. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  30956. var c = null;
  30957. if (faceColors) {
  30958. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  30959. }
  30960. // cap center
  30961. var vbase = positions.length / 3;
  30962. var offset = isTop ? height / 2 : -height / 2;
  30963. var center = new BABYLON.Vector3(0, offset, 0);
  30964. positions.push(center.x, center.y, center.z);
  30965. normals.push(0, isTop ? 1 : -1, 0);
  30966. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  30967. if (c) {
  30968. colors.push(c.r, c.g, c.b, c.a);
  30969. }
  30970. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  30971. for (i = 0; i <= tessellation; i++) {
  30972. angle = Math.PI * 2 * i * arc / tessellation;
  30973. var cos = Math.cos(-angle);
  30974. var sin = Math.sin(-angle);
  30975. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  30976. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  30977. positions.push(circleVector.x, circleVector.y, circleVector.z);
  30978. normals.push(0, isTop ? 1 : -1, 0);
  30979. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  30980. if (c) {
  30981. colors.push(c.r, c.g, c.b, c.a);
  30982. }
  30983. }
  30984. // Cap indices
  30985. for (i = 0; i < tessellation; i++) {
  30986. if (!isTop) {
  30987. indices.push(vbase);
  30988. indices.push(vbase + (i + 1));
  30989. indices.push(vbase + (i + 2));
  30990. }
  30991. else {
  30992. indices.push(vbase);
  30993. indices.push(vbase + (i + 2));
  30994. indices.push(vbase + (i + 1));
  30995. }
  30996. }
  30997. };
  30998. // add caps to geometry
  30999. createCylinderCap(false);
  31000. createCylinderCap(true);
  31001. // Sides
  31002. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  31003. var vertexData = new VertexData();
  31004. vertexData.indices = indices;
  31005. vertexData.positions = positions;
  31006. vertexData.normals = normals;
  31007. vertexData.uvs = uvs;
  31008. if (faceColors) {
  31009. vertexData.colors = colors;
  31010. }
  31011. return vertexData;
  31012. };
  31013. /**
  31014. * Creates the VertexData of the Torus.
  31015. */
  31016. VertexData.CreateTorus = function (options) {
  31017. var indices = [];
  31018. var positions = [];
  31019. var normals = [];
  31020. var uvs = [];
  31021. var diameter = options.diameter || 1;
  31022. var thickness = options.thickness || 0.5;
  31023. var tessellation = options.tessellation || 16;
  31024. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  31025. var stride = tessellation + 1;
  31026. for (var i = 0; i <= tessellation; i++) {
  31027. var u = i / tessellation;
  31028. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  31029. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  31030. for (var j = 0; j <= tessellation; j++) {
  31031. var v = 1 - j / tessellation;
  31032. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  31033. var dx = Math.cos(innerAngle);
  31034. var dy = Math.sin(innerAngle);
  31035. // Create a vertex.
  31036. var normal = new BABYLON.Vector3(dx, dy, 0);
  31037. var position = normal.scale(thickness / 2);
  31038. var textureCoordinate = new BABYLON.Vector2(u, v);
  31039. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  31040. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  31041. positions.push(position.x, position.y, position.z);
  31042. normals.push(normal.x, normal.y, normal.z);
  31043. uvs.push(textureCoordinate.x, textureCoordinate.y);
  31044. // And create indices for two triangles.
  31045. var nextI = (i + 1) % stride;
  31046. var nextJ = (j + 1) % stride;
  31047. indices.push(i * stride + j);
  31048. indices.push(i * stride + nextJ);
  31049. indices.push(nextI * stride + j);
  31050. indices.push(i * stride + nextJ);
  31051. indices.push(nextI * stride + nextJ);
  31052. indices.push(nextI * stride + j);
  31053. }
  31054. }
  31055. // Sides
  31056. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  31057. // Result
  31058. var vertexData = new VertexData();
  31059. vertexData.indices = indices;
  31060. vertexData.positions = positions;
  31061. vertexData.normals = normals;
  31062. vertexData.uvs = uvs;
  31063. return vertexData;
  31064. };
  31065. /**
  31066. * Creates the VertexData of the LineSystem.
  31067. */
  31068. VertexData.CreateLineSystem = function (options) {
  31069. var indices = [];
  31070. var positions = [];
  31071. var lines = options.lines;
  31072. var colors = options.colors;
  31073. var vertexColors = [];
  31074. var idx = 0;
  31075. for (var l = 0; l < lines.length; l++) {
  31076. var points = lines[l];
  31077. for (var index = 0; index < points.length; index++) {
  31078. positions.push(points[index].x, points[index].y, points[index].z);
  31079. if (colors) {
  31080. var color = colors[l];
  31081. vertexColors.push(color[index].r, color[index].g, color[index].b, color[index].a);
  31082. }
  31083. if (index > 0) {
  31084. indices.push(idx - 1);
  31085. indices.push(idx);
  31086. }
  31087. idx++;
  31088. }
  31089. }
  31090. var vertexData = new VertexData();
  31091. vertexData.indices = indices;
  31092. vertexData.positions = positions;
  31093. if (colors) {
  31094. vertexData.colors = vertexColors;
  31095. }
  31096. return vertexData;
  31097. };
  31098. /**
  31099. * Create the VertexData of the DashedLines.
  31100. */
  31101. VertexData.CreateDashedLines = function (options) {
  31102. var dashSize = options.dashSize || 3;
  31103. var gapSize = options.gapSize || 1;
  31104. var dashNb = options.dashNb || 200;
  31105. var points = options.points;
  31106. var positions = new Array();
  31107. var indices = new Array();
  31108. var curvect = BABYLON.Vector3.Zero();
  31109. var lg = 0;
  31110. var nb = 0;
  31111. var shft = 0;
  31112. var dashshft = 0;
  31113. var curshft = 0;
  31114. var idx = 0;
  31115. var i = 0;
  31116. for (i = 0; i < points.length - 1; i++) {
  31117. points[i + 1].subtractToRef(points[i], curvect);
  31118. lg += curvect.length();
  31119. }
  31120. shft = lg / dashNb;
  31121. dashshft = dashSize * shft / (dashSize + gapSize);
  31122. for (i = 0; i < points.length - 1; i++) {
  31123. points[i + 1].subtractToRef(points[i], curvect);
  31124. nb = Math.floor(curvect.length() / shft);
  31125. curvect.normalize();
  31126. for (var j = 0; j < nb; j++) {
  31127. curshft = shft * j;
  31128. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  31129. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  31130. indices.push(idx, idx + 1);
  31131. idx += 2;
  31132. }
  31133. }
  31134. // Result
  31135. var vertexData = new VertexData();
  31136. vertexData.positions = positions;
  31137. vertexData.indices = indices;
  31138. return vertexData;
  31139. };
  31140. /**
  31141. * Creates the VertexData of the Ground.
  31142. */
  31143. VertexData.CreateGround = function (options) {
  31144. var indices = [];
  31145. var positions = [];
  31146. var normals = [];
  31147. var uvs = [];
  31148. var row, col;
  31149. var width = options.width || 1;
  31150. var height = options.height || 1;
  31151. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  31152. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  31153. for (row = 0; row <= subdivisionsY; row++) {
  31154. for (col = 0; col <= subdivisionsX; col++) {
  31155. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  31156. var normal = new BABYLON.Vector3(0, 1.0, 0);
  31157. positions.push(position.x, position.y, position.z);
  31158. normals.push(normal.x, normal.y, normal.z);
  31159. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  31160. }
  31161. }
  31162. for (row = 0; row < subdivisionsY; row++) {
  31163. for (col = 0; col < subdivisionsX; col++) {
  31164. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  31165. indices.push(col + 1 + row * (subdivisionsX + 1));
  31166. indices.push(col + row * (subdivisionsX + 1));
  31167. indices.push(col + (row + 1) * (subdivisionsX + 1));
  31168. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  31169. indices.push(col + row * (subdivisionsX + 1));
  31170. }
  31171. }
  31172. // Result
  31173. var vertexData = new VertexData();
  31174. vertexData.indices = indices;
  31175. vertexData.positions = positions;
  31176. vertexData.normals = normals;
  31177. vertexData.uvs = uvs;
  31178. return vertexData;
  31179. };
  31180. /**
  31181. * Creates the VertexData of the TiledGround.
  31182. */
  31183. VertexData.CreateTiledGround = function (options) {
  31184. var xmin = (options.xmin !== undefined && options.xmin !== null) ? options.xmin : -1.0;
  31185. var zmin = (options.zmin !== undefined && options.zmin !== null) ? options.zmin : -1.0;
  31186. var xmax = (options.xmax !== undefined && options.xmax !== null) ? options.xmax : 1.0;
  31187. var zmax = (options.zmax !== undefined && options.zmax !== null) ? options.zmax : 1.0;
  31188. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  31189. var precision = options.precision || { w: 1, h: 1 };
  31190. var indices = new Array();
  31191. var positions = new Array();
  31192. var normals = new Array();
  31193. var uvs = new Array();
  31194. var row, col, tileRow, tileCol;
  31195. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  31196. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  31197. precision.w = (precision.w < 1) ? 1 : precision.w;
  31198. precision.h = (precision.h < 1) ? 1 : precision.h;
  31199. var tileSize = {
  31200. 'w': (xmax - xmin) / subdivisions.w,
  31201. 'h': (zmax - zmin) / subdivisions.h
  31202. };
  31203. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  31204. // Indices
  31205. var base = positions.length / 3;
  31206. var rowLength = precision.w + 1;
  31207. for (row = 0; row < precision.h; row++) {
  31208. for (col = 0; col < precision.w; col++) {
  31209. var square = [
  31210. base + col + row * rowLength,
  31211. base + (col + 1) + row * rowLength,
  31212. base + (col + 1) + (row + 1) * rowLength,
  31213. base + col + (row + 1) * rowLength
  31214. ];
  31215. indices.push(square[1]);
  31216. indices.push(square[2]);
  31217. indices.push(square[3]);
  31218. indices.push(square[0]);
  31219. indices.push(square[1]);
  31220. indices.push(square[3]);
  31221. }
  31222. }
  31223. // Position, normals and uvs
  31224. var position = BABYLON.Vector3.Zero();
  31225. var normal = new BABYLON.Vector3(0, 1.0, 0);
  31226. for (row = 0; row <= precision.h; row++) {
  31227. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  31228. for (col = 0; col <= precision.w; col++) {
  31229. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  31230. position.y = 0;
  31231. positions.push(position.x, position.y, position.z);
  31232. normals.push(normal.x, normal.y, normal.z);
  31233. uvs.push(col / precision.w, row / precision.h);
  31234. }
  31235. }
  31236. }
  31237. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  31238. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  31239. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  31240. }
  31241. }
  31242. // Result
  31243. var vertexData = new VertexData();
  31244. vertexData.indices = indices;
  31245. vertexData.positions = positions;
  31246. vertexData.normals = normals;
  31247. vertexData.uvs = uvs;
  31248. return vertexData;
  31249. };
  31250. /**
  31251. * Creates the VertexData of the Ground designed from a heightmap.
  31252. */
  31253. VertexData.CreateGroundFromHeightMap = function (options) {
  31254. var indices = [];
  31255. var positions = [];
  31256. var normals = [];
  31257. var uvs = [];
  31258. var row, col;
  31259. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  31260. // Vertices
  31261. for (row = 0; row <= options.subdivisions; row++) {
  31262. for (col = 0; col <= options.subdivisions; col++) {
  31263. 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));
  31264. // Compute height
  31265. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  31266. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  31267. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  31268. var r = options.buffer[pos] / 255.0;
  31269. var g = options.buffer[pos + 1] / 255.0;
  31270. var b = options.buffer[pos + 2] / 255.0;
  31271. var gradient = r * filter.r + g * filter.g + b * filter.b;
  31272. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  31273. // Add vertex
  31274. positions.push(position.x, position.y, position.z);
  31275. normals.push(0, 0, 0);
  31276. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  31277. }
  31278. }
  31279. // Indices
  31280. for (row = 0; row < options.subdivisions; row++) {
  31281. for (col = 0; col < options.subdivisions; col++) {
  31282. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  31283. indices.push(col + 1 + row * (options.subdivisions + 1));
  31284. indices.push(col + row * (options.subdivisions + 1));
  31285. indices.push(col + (row + 1) * (options.subdivisions + 1));
  31286. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  31287. indices.push(col + row * (options.subdivisions + 1));
  31288. }
  31289. }
  31290. // Normals
  31291. VertexData.ComputeNormals(positions, indices, normals);
  31292. // Result
  31293. var vertexData = new VertexData();
  31294. vertexData.indices = indices;
  31295. vertexData.positions = positions;
  31296. vertexData.normals = normals;
  31297. vertexData.uvs = uvs;
  31298. return vertexData;
  31299. };
  31300. /**
  31301. * Creates the VertexData of the Plane.
  31302. */
  31303. VertexData.CreatePlane = function (options) {
  31304. var indices = [];
  31305. var positions = [];
  31306. var normals = [];
  31307. var uvs = [];
  31308. var width = options.width || options.size || 1;
  31309. var height = options.height || options.size || 1;
  31310. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  31311. // Vertices
  31312. var halfWidth = width / 2.0;
  31313. var halfHeight = height / 2.0;
  31314. positions.push(-halfWidth, -halfHeight, 0);
  31315. normals.push(0, 0, -1.0);
  31316. uvs.push(0.0, 0.0);
  31317. positions.push(halfWidth, -halfHeight, 0);
  31318. normals.push(0, 0, -1.0);
  31319. uvs.push(1.0, 0.0);
  31320. positions.push(halfWidth, halfHeight, 0);
  31321. normals.push(0, 0, -1.0);
  31322. uvs.push(1.0, 1.0);
  31323. positions.push(-halfWidth, halfHeight, 0);
  31324. normals.push(0, 0, -1.0);
  31325. uvs.push(0.0, 1.0);
  31326. // Indices
  31327. indices.push(0);
  31328. indices.push(1);
  31329. indices.push(2);
  31330. indices.push(0);
  31331. indices.push(2);
  31332. indices.push(3);
  31333. // Sides
  31334. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  31335. // Result
  31336. var vertexData = new VertexData();
  31337. vertexData.indices = indices;
  31338. vertexData.positions = positions;
  31339. vertexData.normals = normals;
  31340. vertexData.uvs = uvs;
  31341. return vertexData;
  31342. };
  31343. /**
  31344. * Creates the VertexData of the Disc or regular Polygon.
  31345. */
  31346. VertexData.CreateDisc = function (options) {
  31347. var positions = new Array();
  31348. var indices = new Array();
  31349. var normals = new Array();
  31350. var uvs = new Array();
  31351. var radius = options.radius || 0.5;
  31352. var tessellation = options.tessellation || 64;
  31353. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  31354. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  31355. // positions and uvs
  31356. positions.push(0, 0, 0); // disc center first
  31357. uvs.push(0.5, 0.5);
  31358. var theta = Math.PI * 2 * arc;
  31359. var step = theta / tessellation;
  31360. for (var a = 0; a < theta; a += step) {
  31361. var x = Math.cos(a);
  31362. var y = Math.sin(a);
  31363. var u = (x + 1) / 2;
  31364. var v = (1 - y) / 2;
  31365. positions.push(radius * x, radius * y, 0);
  31366. uvs.push(u, v);
  31367. }
  31368. if (arc === 1) {
  31369. positions.push(positions[3], positions[4], positions[5]); // close the circle
  31370. uvs.push(uvs[2], uvs[3]);
  31371. }
  31372. //indices
  31373. var vertexNb = positions.length / 3;
  31374. for (var i = 1; i < vertexNb - 1; i++) {
  31375. indices.push(i + 1, 0, i);
  31376. }
  31377. // result
  31378. VertexData.ComputeNormals(positions, indices, normals);
  31379. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  31380. var vertexData = new VertexData();
  31381. vertexData.indices = indices;
  31382. vertexData.positions = positions;
  31383. vertexData.normals = normals;
  31384. vertexData.uvs = uvs;
  31385. return vertexData;
  31386. };
  31387. /**
  31388. * Re-creates the VertexData of the Polygon for sideOrientation.
  31389. */
  31390. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  31391. var faceUV = fUV || new Array(3);
  31392. var faceColors = fColors;
  31393. var colors = [];
  31394. // default face colors and UV if undefined
  31395. for (var f = 0; f < 3; f++) {
  31396. if (faceUV[f] === undefined) {
  31397. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  31398. }
  31399. if (faceColors && faceColors[f] === undefined) {
  31400. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  31401. }
  31402. }
  31403. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31404. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  31405. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  31406. var indices = polygon.getIndices();
  31407. // set face colours and textures
  31408. var idx = 0;
  31409. var face = 0;
  31410. for (var index = 0; index < normals.length; index += 3) {
  31411. //Edge Face no. 1
  31412. if (Math.abs(normals[index + 1]) < 0.001) {
  31413. face = 1;
  31414. }
  31415. //Top Face no. 0
  31416. if (Math.abs(normals[index + 1] - 1) < 0.001) {
  31417. face = 0;
  31418. }
  31419. //Bottom Face no. 2
  31420. if (Math.abs(normals[index + 1] + 1) < 0.001) {
  31421. face = 2;
  31422. }
  31423. idx = index / 3;
  31424. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  31425. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  31426. if (faceColors) {
  31427. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  31428. }
  31429. }
  31430. // sides
  31431. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  31432. // Result
  31433. var vertexData = new VertexData();
  31434. vertexData.indices = indices;
  31435. vertexData.positions = positions;
  31436. vertexData.normals = normals;
  31437. vertexData.uvs = uvs;
  31438. if (faceColors) {
  31439. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  31440. vertexData.colors = totalColors;
  31441. }
  31442. return vertexData;
  31443. };
  31444. /**
  31445. * Creates the VertexData of the IcoSphere.
  31446. */
  31447. VertexData.CreateIcoSphere = function (options) {
  31448. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  31449. var radius = options.radius || 1;
  31450. var flat = (options.flat === undefined) ? true : options.flat;
  31451. var subdivisions = options.subdivisions || 4;
  31452. var radiusX = options.radiusX || radius;
  31453. var radiusY = options.radiusY || radius;
  31454. var radiusZ = options.radiusZ || radius;
  31455. var t = (1 + Math.sqrt(5)) / 2;
  31456. // 12 vertex x,y,z
  31457. var ico_vertices = [
  31458. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  31459. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  31460. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  31461. ];
  31462. // index of 3 vertex makes a face of icopshere
  31463. var ico_indices = [
  31464. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  31465. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  31466. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  31467. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  31468. ];
  31469. // vertex for uv have aliased position, not for UV
  31470. var vertices_unalias_id = [
  31471. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  31472. // vertex alias
  31473. 0,
  31474. 2,
  31475. 3,
  31476. 3,
  31477. 3,
  31478. 4,
  31479. 7,
  31480. 8,
  31481. 9,
  31482. 9,
  31483. 10,
  31484. 11 // 23: B + 12
  31485. ];
  31486. // uv as integer step (not pixels !)
  31487. var ico_vertexuv = [
  31488. 5, 1, 3, 1, 6, 4, 0, 0,
  31489. 5, 3, 4, 2, 2, 2, 4, 0,
  31490. 2, 0, 1, 1, 6, 0, 6, 2,
  31491. // vertex alias (for same vertex on different faces)
  31492. 0, 4,
  31493. 3, 3,
  31494. 4, 4,
  31495. 3, 1,
  31496. 4, 2,
  31497. 4, 4,
  31498. 0, 2,
  31499. 1, 1,
  31500. 2, 2,
  31501. 3, 3,
  31502. 1, 3,
  31503. 2, 4 // 23: B + 12
  31504. ];
  31505. // Vertices[0, 1, ...9, A, B] : position on UV plane
  31506. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  31507. // First island of uv mapping
  31508. // v = 4h 3+ 2
  31509. // v = 3h 9+ 4
  31510. // v = 2h 9+ 5 B
  31511. // v = 1h 9 1 0
  31512. // v = 0h 3 8 7 A
  31513. // u = 0 1 2 3 4 5 6 *a
  31514. // Second island of uv mapping
  31515. // v = 4h 0+ B+ 4+
  31516. // v = 3h A+ 2+
  31517. // v = 2h 7+ 6 3+
  31518. // v = 1h 8+ 3+
  31519. // v = 0h
  31520. // u = 0 1 2 3 4 5 6 *a
  31521. // Face layout on texture UV mapping
  31522. // ============
  31523. // \ 4 /\ 16 / ======
  31524. // \ / \ / /\ 11 /
  31525. // \/ 7 \/ / \ /
  31526. // ======= / 10 \/
  31527. // /\ 17 /\ =======
  31528. // / \ / \ \ 15 /\
  31529. // / 8 \/ 12 \ \ / \
  31530. // ============ \/ 6 \
  31531. // \ 18 /\ ============
  31532. // \ / \ \ 5 /\ 0 /
  31533. // \/ 13 \ \ / \ /
  31534. // ======= \/ 1 \/
  31535. // =============
  31536. // /\ 19 /\ 2 /\
  31537. // / \ / \ / \
  31538. // / 14 \/ 9 \/ 3 \
  31539. // ===================
  31540. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  31541. var ustep = 138 / 1024;
  31542. var vstep = 239 / 1024;
  31543. var uoffset = 60 / 1024;
  31544. var voffset = 26 / 1024;
  31545. // Second island should have margin, not to touch the first island
  31546. // avoid any borderline artefact in pixel rounding
  31547. var island_u_offset = -40 / 1024;
  31548. var island_v_offset = +20 / 1024;
  31549. // face is either island 0 or 1 :
  31550. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  31551. var island = [
  31552. 0, 0, 0, 0, 1,
  31553. 0, 0, 1, 1, 0,
  31554. 0, 0, 1, 1, 0,
  31555. 0, 1, 1, 1, 0 // 15 - 19
  31556. ];
  31557. var indices = new Array();
  31558. var positions = new Array();
  31559. var normals = new Array();
  31560. var uvs = new Array();
  31561. var current_indice = 0;
  31562. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  31563. var face_vertex_pos = new Array(3);
  31564. var face_vertex_uv = new Array(3);
  31565. var v012;
  31566. for (v012 = 0; v012 < 3; v012++) {
  31567. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  31568. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  31569. }
  31570. // create all with normals
  31571. for (var face = 0; face < 20; face++) {
  31572. // 3 vertex per face
  31573. for (v012 = 0; v012 < 3; v012++) {
  31574. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  31575. var v_id = ico_indices[3 * face + v012];
  31576. // vertex have 3D position (x,y,z)
  31577. 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]);
  31578. // Normalize to get normal, then scale to radius
  31579. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  31580. // uv Coordinates from vertex ID
  31581. 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);
  31582. }
  31583. // Subdivide the face (interpolate pos, norm, uv)
  31584. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  31585. // - norm is linear interpolation of vertex corner normal
  31586. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  31587. // - uv is linear interpolation
  31588. //
  31589. // Topology is as below for sub-divide by 2
  31590. // vertex shown as v0,v1,v2
  31591. // interp index is i1 to progress in range [v0,v1[
  31592. // interp index is i2 to progress in range [v0,v2[
  31593. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  31594. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  31595. //
  31596. //
  31597. // i2 v2
  31598. // ^ ^
  31599. // / / \
  31600. // / / \
  31601. // / / \
  31602. // / / (0,1) \
  31603. // / #---------\
  31604. // / / \ (0,0)'/ \
  31605. // / / \ / \
  31606. // / / \ / \
  31607. // / / (0,0) \ / (1,0) \
  31608. // / #---------#---------\
  31609. // v0 v1
  31610. //
  31611. // --------------------> i1
  31612. //
  31613. // interp of (i1,i2):
  31614. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  31615. // along i1 : lerp(x0,x1, i1/(S-i2))
  31616. //
  31617. // centroid of triangle is needed to get help normal computation
  31618. // (c1,c2) are used for centroid location
  31619. var interp_vertex = function (i1, i2, c1, c2) {
  31620. // vertex is interpolated from
  31621. // - face_vertex_pos[0..2]
  31622. // - face_vertex_uv[0..2]
  31623. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  31624. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  31625. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  31626. pos_interp.normalize();
  31627. var vertex_normal;
  31628. if (flat) {
  31629. // in flat mode, recalculate normal as face centroid normal
  31630. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  31631. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  31632. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  31633. }
  31634. else {
  31635. // in smooth mode, recalculate normal from each single vertex position
  31636. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  31637. }
  31638. // Vertex normal need correction due to X,Y,Z radius scaling
  31639. vertex_normal.x /= radiusX;
  31640. vertex_normal.y /= radiusY;
  31641. vertex_normal.z /= radiusZ;
  31642. vertex_normal.normalize();
  31643. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  31644. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  31645. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  31646. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  31647. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  31648. uvs.push(uv_interp.x, uv_interp.y);
  31649. // push each vertex has member of a face
  31650. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  31651. indices.push(current_indice);
  31652. current_indice++;
  31653. };
  31654. for (var i2 = 0; i2 < subdivisions; i2++) {
  31655. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  31656. // face : (i1,i2) for /\ :
  31657. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  31658. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  31659. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  31660. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  31661. if (i1 + i2 + 1 < subdivisions) {
  31662. // face : (i1,i2)' for \/ :
  31663. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  31664. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  31665. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  31666. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  31667. }
  31668. }
  31669. }
  31670. }
  31671. // Sides
  31672. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  31673. // Result
  31674. var vertexData = new VertexData();
  31675. vertexData.indices = indices;
  31676. vertexData.positions = positions;
  31677. vertexData.normals = normals;
  31678. vertexData.uvs = uvs;
  31679. return vertexData;
  31680. };
  31681. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  31682. /**
  31683. * Creates the VertexData of the Polyhedron.
  31684. */
  31685. VertexData.CreatePolyhedron = function (options) {
  31686. // provided polyhedron types :
  31687. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  31688. // 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)
  31689. var polyhedra = [];
  31690. 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]] };
  31691. 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]] };
  31692. polyhedra[2] = {
  31693. 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]],
  31694. 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]]
  31695. };
  31696. polyhedra[3] = {
  31697. 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]],
  31698. 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]]
  31699. };
  31700. polyhedra[4] = {
  31701. 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]],
  31702. 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]]
  31703. };
  31704. 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]] };
  31705. 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]] };
  31706. 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]] };
  31707. 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]] };
  31708. 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]] };
  31709. 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]] };
  31710. 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]] };
  31711. 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]] };
  31712. 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]] };
  31713. polyhedra[14] = {
  31714. 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]],
  31715. 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]]
  31716. };
  31717. var type = options.type && (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  31718. var size = options.size;
  31719. var sizeX = options.sizeX || size || 1;
  31720. var sizeY = options.sizeY || size || 1;
  31721. var sizeZ = options.sizeZ || size || 1;
  31722. var data = options.custom || polyhedra[type];
  31723. var nbfaces = data.face.length;
  31724. var faceUV = options.faceUV || new Array(nbfaces);
  31725. var faceColors = options.faceColors;
  31726. var flat = (options.flat === undefined) ? true : options.flat;
  31727. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  31728. var positions = new Array();
  31729. var indices = new Array();
  31730. var normals = new Array();
  31731. var uvs = new Array();
  31732. var colors = new Array();
  31733. var index = 0;
  31734. var faceIdx = 0; // face cursor in the array "indexes"
  31735. var indexes = new Array();
  31736. var i = 0;
  31737. var f = 0;
  31738. var u, v, ang, x, y, tmp;
  31739. // default face colors and UV if undefined
  31740. if (flat) {
  31741. for (f = 0; f < nbfaces; f++) {
  31742. if (faceColors && faceColors[f] === undefined) {
  31743. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  31744. }
  31745. if (faceUV && faceUV[f] === undefined) {
  31746. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  31747. }
  31748. }
  31749. }
  31750. if (!flat) {
  31751. for (i = 0; i < data.vertex.length; i++) {
  31752. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  31753. uvs.push(0, 0);
  31754. }
  31755. for (f = 0; f < nbfaces; f++) {
  31756. for (i = 0; i < data.face[f].length - 2; i++) {
  31757. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  31758. }
  31759. }
  31760. }
  31761. else {
  31762. for (f = 0; f < nbfaces; f++) {
  31763. var fl = data.face[f].length; // number of vertices of the current face
  31764. ang = 2 * Math.PI / fl;
  31765. x = 0.5 * Math.tan(ang / 2);
  31766. y = 0.5;
  31767. // positions, uvs, colors
  31768. for (i = 0; i < fl; i++) {
  31769. // positions
  31770. 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);
  31771. indexes.push(index);
  31772. index++;
  31773. // uvs
  31774. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  31775. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  31776. uvs.push(u, v);
  31777. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  31778. y = x * Math.sin(ang) + y * Math.cos(ang);
  31779. x = tmp;
  31780. // colors
  31781. if (faceColors) {
  31782. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  31783. }
  31784. }
  31785. // indices from indexes
  31786. for (i = 0; i < fl - 2; i++) {
  31787. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  31788. }
  31789. faceIdx += fl;
  31790. }
  31791. }
  31792. VertexData.ComputeNormals(positions, indices, normals);
  31793. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  31794. var vertexData = new VertexData();
  31795. vertexData.positions = positions;
  31796. vertexData.indices = indices;
  31797. vertexData.normals = normals;
  31798. vertexData.uvs = uvs;
  31799. if (faceColors && flat) {
  31800. vertexData.colors = colors;
  31801. }
  31802. return vertexData;
  31803. };
  31804. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  31805. /**
  31806. * Creates the VertexData of the Torus Knot.
  31807. */
  31808. VertexData.CreateTorusKnot = function (options) {
  31809. var indices = new Array();
  31810. var positions = new Array();
  31811. var normals = new Array();
  31812. var uvs = new Array();
  31813. var radius = options.radius || 2;
  31814. var tube = options.tube || 0.5;
  31815. var radialSegments = options.radialSegments || 32;
  31816. var tubularSegments = options.tubularSegments || 32;
  31817. var p = options.p || 2;
  31818. var q = options.q || 3;
  31819. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  31820. // Helper
  31821. var getPos = function (angle) {
  31822. var cu = Math.cos(angle);
  31823. var su = Math.sin(angle);
  31824. var quOverP = q / p * angle;
  31825. var cs = Math.cos(quOverP);
  31826. var tx = radius * (2 + cs) * 0.5 * cu;
  31827. var ty = radius * (2 + cs) * su * 0.5;
  31828. var tz = radius * Math.sin(quOverP) * 0.5;
  31829. return new BABYLON.Vector3(tx, ty, tz);
  31830. };
  31831. // Vertices
  31832. var i;
  31833. var j;
  31834. for (i = 0; i <= radialSegments; i++) {
  31835. var modI = i % radialSegments;
  31836. var u = modI / radialSegments * 2 * p * Math.PI;
  31837. var p1 = getPos(u);
  31838. var p2 = getPos(u + 0.01);
  31839. var tang = p2.subtract(p1);
  31840. var n = p2.add(p1);
  31841. var bitan = BABYLON.Vector3.Cross(tang, n);
  31842. n = BABYLON.Vector3.Cross(bitan, tang);
  31843. bitan.normalize();
  31844. n.normalize();
  31845. for (j = 0; j < tubularSegments; j++) {
  31846. var modJ = j % tubularSegments;
  31847. var v = modJ / tubularSegments * 2 * Math.PI;
  31848. var cx = -tube * Math.cos(v);
  31849. var cy = tube * Math.sin(v);
  31850. positions.push(p1.x + cx * n.x + cy * bitan.x);
  31851. positions.push(p1.y + cx * n.y + cy * bitan.y);
  31852. positions.push(p1.z + cx * n.z + cy * bitan.z);
  31853. uvs.push(i / radialSegments);
  31854. uvs.push(j / tubularSegments);
  31855. }
  31856. }
  31857. for (i = 0; i < radialSegments; i++) {
  31858. for (j = 0; j < tubularSegments; j++) {
  31859. var jNext = (j + 1) % tubularSegments;
  31860. var a = i * tubularSegments + j;
  31861. var b = (i + 1) * tubularSegments + j;
  31862. var c = (i + 1) * tubularSegments + jNext;
  31863. var d = i * tubularSegments + jNext;
  31864. indices.push(d);
  31865. indices.push(b);
  31866. indices.push(a);
  31867. indices.push(d);
  31868. indices.push(c);
  31869. indices.push(b);
  31870. }
  31871. }
  31872. // Normals
  31873. VertexData.ComputeNormals(positions, indices, normals);
  31874. // Sides
  31875. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  31876. // Result
  31877. var vertexData = new VertexData();
  31878. vertexData.indices = indices;
  31879. vertexData.positions = positions;
  31880. vertexData.normals = normals;
  31881. vertexData.uvs = uvs;
  31882. return vertexData;
  31883. };
  31884. // Tools
  31885. /**
  31886. * @param {any} - positions (number[] or Float32Array)
  31887. * @param {any} - indices (number[] or Uint16Array)
  31888. * @param {any} - normals (number[] or Float32Array)
  31889. * options (optional) :
  31890. * facetPositions : optional array of facet positions (vector3)
  31891. * facetNormals : optional array of facet normals (vector3)
  31892. * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  31893. * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  31894. * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  31895. * bbSize : optional bounding box size data, required for facetPartitioning computation
  31896. * bInfo : optional bounding info, required for facetPartitioning computation
  31897. * useRightHandedSystem: optional boolean to for right handed system computation
  31898. * depthSort : optional boolean to enable the facet depth sort computation
  31899. * distanceTo : optional Vector3 to compute the facet depth from this location
  31900. * depthSortedFacets : optional array of depthSortedFacets to store the facet distances from the reference location
  31901. */
  31902. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  31903. // temporary scalar variables
  31904. var index = 0; // facet index
  31905. var p1p2x = 0.0; // p1p2 vector x coordinate
  31906. var p1p2y = 0.0; // p1p2 vector y coordinate
  31907. var p1p2z = 0.0; // p1p2 vector z coordinate
  31908. var p3p2x = 0.0; // p3p2 vector x coordinate
  31909. var p3p2y = 0.0; // p3p2 vector y coordinate
  31910. var p3p2z = 0.0; // p3p2 vector z coordinate
  31911. var faceNormalx = 0.0; // facet normal x coordinate
  31912. var faceNormaly = 0.0; // facet normal y coordinate
  31913. var faceNormalz = 0.0; // facet normal z coordinate
  31914. var length = 0.0; // facet normal length before normalization
  31915. var v1x = 0; // vector1 x index in the positions array
  31916. var v1y = 0; // vector1 y index in the positions array
  31917. var v1z = 0; // vector1 z index in the positions array
  31918. var v2x = 0; // vector2 x index in the positions array
  31919. var v2y = 0; // vector2 y index in the positions array
  31920. var v2z = 0; // vector2 z index in the positions array
  31921. var v3x = 0; // vector3 x index in the positions array
  31922. var v3y = 0; // vector3 y index in the positions array
  31923. var v3z = 0; // vector3 z index in the positions array
  31924. var computeFacetNormals = false;
  31925. var computeFacetPositions = false;
  31926. var computeFacetPartitioning = false;
  31927. var computeDepthSort = false;
  31928. var faceNormalSign = 1;
  31929. var ratio = 0;
  31930. var distanceTo = null;
  31931. if (options) {
  31932. computeFacetNormals = (options.facetNormals) ? true : false;
  31933. computeFacetPositions = (options.facetPositions) ? true : false;
  31934. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  31935. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  31936. ratio = options.ratio || 0;
  31937. computeDepthSort = (options.depthSort) ? true : false;
  31938. distanceTo = (options.distanceTo);
  31939. if (computeDepthSort) {
  31940. if (distanceTo === undefined) {
  31941. distanceTo = BABYLON.Vector3.Zero();
  31942. }
  31943. var depthSortedFacets = options.depthSortedFacets;
  31944. }
  31945. }
  31946. // facetPartitioning reinit if needed
  31947. var xSubRatio = 0;
  31948. var ySubRatio = 0;
  31949. var zSubRatio = 0;
  31950. var subSq = 0;
  31951. if (computeFacetPartitioning && options && options.bbSize) {
  31952. var ox = 0; // X partitioning index for facet position
  31953. var oy = 0; // Y partinioning index for facet position
  31954. var oz = 0; // Z partinioning index for facet position
  31955. var b1x = 0; // X partitioning index for facet v1 vertex
  31956. var b1y = 0; // Y partitioning index for facet v1 vertex
  31957. var b1z = 0; // z partitioning index for facet v1 vertex
  31958. var b2x = 0; // X partitioning index for facet v2 vertex
  31959. var b2y = 0; // Y partitioning index for facet v2 vertex
  31960. var b2z = 0; // Z partitioning index for facet v2 vertex
  31961. var b3x = 0; // X partitioning index for facet v3 vertex
  31962. var b3y = 0; // Y partitioning index for facet v3 vertex
  31963. var b3z = 0; // Z partitioning index for facet v3 vertex
  31964. var block_idx_o = 0; // facet barycenter block index
  31965. var block_idx_v1 = 0; // v1 vertex block index
  31966. var block_idx_v2 = 0; // v2 vertex block index
  31967. var block_idx_v3 = 0; // v3 vertex block index
  31968. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  31969. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  31970. xSubRatio = options.subDiv.X * ratio / options.bbSize.x;
  31971. ySubRatio = options.subDiv.Y * ratio / options.bbSize.y;
  31972. zSubRatio = options.subDiv.Z * ratio / options.bbSize.z;
  31973. subSq = options.subDiv.max * options.subDiv.max;
  31974. options.facetPartitioning.length = 0;
  31975. }
  31976. // reset the normals
  31977. for (index = 0; index < positions.length; index++) {
  31978. normals[index] = 0.0;
  31979. }
  31980. // Loop : 1 indice triplet = 1 facet
  31981. var nbFaces = (indices.length / 3) | 0;
  31982. for (index = 0; index < nbFaces; index++) {
  31983. // get the indexes of the coordinates of each vertex of the facet
  31984. v1x = indices[index * 3] * 3;
  31985. v1y = v1x + 1;
  31986. v1z = v1x + 2;
  31987. v2x = indices[index * 3 + 1] * 3;
  31988. v2y = v2x + 1;
  31989. v2z = v2x + 2;
  31990. v3x = indices[index * 3 + 2] * 3;
  31991. v3y = v3x + 1;
  31992. v3z = v3x + 2;
  31993. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  31994. p1p2y = positions[v1y] - positions[v2y];
  31995. p1p2z = positions[v1z] - positions[v2z];
  31996. p3p2x = positions[v3x] - positions[v2x];
  31997. p3p2y = positions[v3y] - positions[v2y];
  31998. p3p2z = positions[v3z] - positions[v2z];
  31999. // compute the face normal with the cross product
  32000. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  32001. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  32002. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  32003. // normalize this normal and store it in the array facetData
  32004. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  32005. length = (length === 0) ? 1.0 : length;
  32006. faceNormalx /= length;
  32007. faceNormaly /= length;
  32008. faceNormalz /= length;
  32009. if (computeFacetNormals && options) {
  32010. options.facetNormals[index].x = faceNormalx;
  32011. options.facetNormals[index].y = faceNormaly;
  32012. options.facetNormals[index].z = faceNormalz;
  32013. }
  32014. if (computeFacetPositions && options) {
  32015. // compute and the facet barycenter coordinates in the array facetPositions
  32016. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  32017. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  32018. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  32019. }
  32020. if (computeFacetPartitioning && options) {
  32021. // store the facet indexes in arrays in the main facetPartitioning array :
  32022. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  32023. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * ratio) * xSubRatio);
  32024. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * ratio) * ySubRatio);
  32025. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * ratio) * zSubRatio);
  32026. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  32027. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  32028. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  32029. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  32030. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  32031. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  32032. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  32033. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  32034. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  32035. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  32036. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  32037. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  32038. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  32039. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  32040. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  32041. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  32042. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  32043. // push each facet index in each block containing the vertex
  32044. options.facetPartitioning[block_idx_v1].push(index);
  32045. if (block_idx_v2 != block_idx_v1) {
  32046. options.facetPartitioning[block_idx_v2].push(index);
  32047. }
  32048. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  32049. options.facetPartitioning[block_idx_v3].push(index);
  32050. }
  32051. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  32052. options.facetPartitioning[block_idx_o].push(index);
  32053. }
  32054. }
  32055. if (computeDepthSort && options && options.facetPositions) {
  32056. var dsf = depthSortedFacets[index];
  32057. dsf.ind = index * 3;
  32058. dsf.sqDistance = BABYLON.Vector3.DistanceSquared(options.facetPositions[index], distanceTo);
  32059. }
  32060. // compute the normals anyway
  32061. normals[v1x] += faceNormalx; // accumulate all the normals per face
  32062. normals[v1y] += faceNormaly;
  32063. normals[v1z] += faceNormalz;
  32064. normals[v2x] += faceNormalx;
  32065. normals[v2y] += faceNormaly;
  32066. normals[v2z] += faceNormalz;
  32067. normals[v3x] += faceNormalx;
  32068. normals[v3y] += faceNormaly;
  32069. normals[v3z] += faceNormalz;
  32070. }
  32071. // last normalization of each normal
  32072. for (index = 0; index < normals.length / 3; index++) {
  32073. faceNormalx = normals[index * 3];
  32074. faceNormaly = normals[index * 3 + 1];
  32075. faceNormalz = normals[index * 3 + 2];
  32076. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  32077. length = (length === 0) ? 1.0 : length;
  32078. faceNormalx /= length;
  32079. faceNormaly /= length;
  32080. faceNormalz /= length;
  32081. normals[index * 3] = faceNormalx;
  32082. normals[index * 3 + 1] = faceNormaly;
  32083. normals[index * 3 + 2] = faceNormalz;
  32084. }
  32085. };
  32086. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  32087. var li = indices.length;
  32088. var ln = normals.length;
  32089. var i;
  32090. var n;
  32091. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  32092. switch (sideOrientation) {
  32093. case BABYLON.Mesh.FRONTSIDE:
  32094. // nothing changed
  32095. break;
  32096. case BABYLON.Mesh.BACKSIDE:
  32097. var tmp;
  32098. // indices
  32099. for (i = 0; i < li; i += 3) {
  32100. tmp = indices[i];
  32101. indices[i] = indices[i + 2];
  32102. indices[i + 2] = tmp;
  32103. }
  32104. // normals
  32105. for (n = 0; n < ln; n++) {
  32106. normals[n] = -normals[n];
  32107. }
  32108. break;
  32109. case BABYLON.Mesh.DOUBLESIDE:
  32110. // positions
  32111. var lp = positions.length;
  32112. var l = lp / 3;
  32113. for (var p = 0; p < lp; p++) {
  32114. positions[lp + p] = positions[p];
  32115. }
  32116. // indices
  32117. for (i = 0; i < li; i += 3) {
  32118. indices[i + li] = indices[i + 2] + l;
  32119. indices[i + 1 + li] = indices[i + 1] + l;
  32120. indices[i + 2 + li] = indices[i] + l;
  32121. }
  32122. // normals
  32123. for (n = 0; n < ln; n++) {
  32124. normals[ln + n] = -normals[n];
  32125. }
  32126. // uvs
  32127. var lu = uvs.length;
  32128. var u = 0;
  32129. for (u = 0; u < lu; u++) {
  32130. uvs[u + lu] = uvs[u];
  32131. }
  32132. frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  32133. backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  32134. u = 0;
  32135. for (i = 0; i < lu / 2; i++) {
  32136. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  32137. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  32138. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  32139. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  32140. u += 2;
  32141. }
  32142. break;
  32143. }
  32144. };
  32145. /**
  32146. * Creates a new VertexData from the imported parameters.
  32147. */
  32148. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  32149. var vertexData = new VertexData();
  32150. // positions
  32151. var positions = parsedVertexData.positions;
  32152. if (positions) {
  32153. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  32154. }
  32155. // normals
  32156. var normals = parsedVertexData.normals;
  32157. if (normals) {
  32158. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  32159. }
  32160. // tangents
  32161. var tangents = parsedVertexData.tangents;
  32162. if (tangents) {
  32163. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  32164. }
  32165. // uvs
  32166. var uvs = parsedVertexData.uvs;
  32167. if (uvs) {
  32168. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  32169. }
  32170. // uv2s
  32171. var uv2s = parsedVertexData.uv2s;
  32172. if (uv2s) {
  32173. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  32174. }
  32175. // uv3s
  32176. var uv3s = parsedVertexData.uv3s;
  32177. if (uv3s) {
  32178. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  32179. }
  32180. // uv4s
  32181. var uv4s = parsedVertexData.uv4s;
  32182. if (uv4s) {
  32183. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  32184. }
  32185. // uv5s
  32186. var uv5s = parsedVertexData.uv5s;
  32187. if (uv5s) {
  32188. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  32189. }
  32190. // uv6s
  32191. var uv6s = parsedVertexData.uv6s;
  32192. if (uv6s) {
  32193. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  32194. }
  32195. // colors
  32196. var colors = parsedVertexData.colors;
  32197. if (colors) {
  32198. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  32199. }
  32200. // matricesIndices
  32201. var matricesIndices = parsedVertexData.matricesIndices;
  32202. if (matricesIndices) {
  32203. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  32204. }
  32205. // matricesWeights
  32206. var matricesWeights = parsedVertexData.matricesWeights;
  32207. if (matricesWeights) {
  32208. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  32209. }
  32210. // indices
  32211. var indices = parsedVertexData.indices;
  32212. if (indices) {
  32213. vertexData.indices = indices;
  32214. }
  32215. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  32216. };
  32217. return VertexData;
  32218. }());
  32219. BABYLON.VertexData = VertexData;
  32220. })(BABYLON || (BABYLON = {}));
  32221. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  32222. var BABYLON;
  32223. (function (BABYLON) {
  32224. /**
  32225. * Class used to store geometry data (vertex buffers + index buffer)
  32226. */
  32227. var Geometry = /** @class */ (function () {
  32228. /**
  32229. * Creates a new geometry
  32230. * @param id defines the unique ID
  32231. * @param scene defines the hosting scene
  32232. * @param vertexData defines the {BABYLON.VertexData} used to get geometry data
  32233. * @param updatable defines if geometry must be updatable (false by default)
  32234. * @param mesh defines the mesh that will be associated with the geometry
  32235. */
  32236. function Geometry(id, scene, vertexData, updatable, mesh) {
  32237. if (updatable === void 0) { updatable = false; }
  32238. if (mesh === void 0) { mesh = null; }
  32239. /**
  32240. * Gets the delay loading state of the geometry (none by default which means not delayed)
  32241. */
  32242. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  32243. this._totalVertices = 0;
  32244. this._isDisposed = false;
  32245. this._indexBufferIsUpdatable = false;
  32246. this.id = id;
  32247. this._engine = scene.getEngine();
  32248. this._meshes = [];
  32249. this._scene = scene;
  32250. //Init vertex buffer cache
  32251. this._vertexBuffers = {};
  32252. this._indices = [];
  32253. this._updatable = updatable;
  32254. // vertexData
  32255. if (vertexData) {
  32256. this.setAllVerticesData(vertexData, updatable);
  32257. }
  32258. else {
  32259. this._totalVertices = 0;
  32260. this._indices = [];
  32261. }
  32262. if (this._engine.getCaps().vertexArrayObject) {
  32263. this._vertexArrayObjects = {};
  32264. }
  32265. // applyToMesh
  32266. if (mesh) {
  32267. if (mesh.getClassName() === "LinesMesh") {
  32268. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  32269. this.updateExtend();
  32270. }
  32271. this.applyToMesh(mesh);
  32272. mesh.computeWorldMatrix(true);
  32273. }
  32274. }
  32275. Object.defineProperty(Geometry.prototype, "boundingBias", {
  32276. /**
  32277. * Gets or sets 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
  32278. */
  32279. get: function () {
  32280. return this._boundingBias;
  32281. },
  32282. /**
  32283. * Gets or sets 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
  32284. */
  32285. set: function (value) {
  32286. if (this._boundingBias && this._boundingBias.equals(value)) {
  32287. return;
  32288. }
  32289. this._boundingBias = value.clone();
  32290. this.updateBoundingInfo(true, null);
  32291. },
  32292. enumerable: true,
  32293. configurable: true
  32294. });
  32295. /**
  32296. * Static function used to attach a new empty geometry to a mesh
  32297. * @param mesh defines the mesh to attach the geometry to
  32298. * @returns the new {BABYLON.Geometry}
  32299. */
  32300. Geometry.CreateGeometryForMesh = function (mesh) {
  32301. var geometry = new Geometry(Geometry.RandomId(), mesh.getScene());
  32302. geometry.applyToMesh(mesh);
  32303. return geometry;
  32304. };
  32305. Object.defineProperty(Geometry.prototype, "extend", {
  32306. /**
  32307. * Gets the current extend of the geometry
  32308. */
  32309. get: function () {
  32310. return this._extend;
  32311. },
  32312. enumerable: true,
  32313. configurable: true
  32314. });
  32315. /**
  32316. * Gets the hosting scene
  32317. * @returns the hosting {BABYLON.Scene}
  32318. */
  32319. Geometry.prototype.getScene = function () {
  32320. return this._scene;
  32321. };
  32322. /**
  32323. * Gets the hosting engine
  32324. * @returns the hosting {BABYLON.Engine}
  32325. */
  32326. Geometry.prototype.getEngine = function () {
  32327. return this._engine;
  32328. };
  32329. /**
  32330. * Defines if the geometry is ready to use
  32331. * @returns true if the geometry is ready to be used
  32332. */
  32333. Geometry.prototype.isReady = function () {
  32334. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  32335. };
  32336. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  32337. /**
  32338. * Gets a value indicating that the geometry should not be serialized
  32339. */
  32340. get: function () {
  32341. for (var index = 0; index < this._meshes.length; index++) {
  32342. if (!this._meshes[index].doNotSerialize) {
  32343. return false;
  32344. }
  32345. }
  32346. return true;
  32347. },
  32348. enumerable: true,
  32349. configurable: true
  32350. });
  32351. /** @ignore */
  32352. Geometry.prototype._rebuild = function () {
  32353. if (this._vertexArrayObjects) {
  32354. this._vertexArrayObjects = {};
  32355. }
  32356. // Index buffer
  32357. if (this._meshes.length !== 0 && this._indices) {
  32358. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  32359. }
  32360. // Vertex buffers
  32361. for (var key in this._vertexBuffers) {
  32362. var vertexBuffer = this._vertexBuffers[key];
  32363. vertexBuffer._rebuild();
  32364. }
  32365. };
  32366. /**
  32367. * Affects all gemetry data in one call
  32368. * @param vertexData defines the geometry data
  32369. * @param updatable defines if the geometry must be flagged as updatable (false as default)
  32370. */
  32371. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  32372. vertexData.applyToGeometry(this, updatable);
  32373. this.notifyUpdate();
  32374. };
  32375. /**
  32376. * Set specific vertex data
  32377. * @param kind defines the data kind (Position, normal, etc...)
  32378. * @param data defines the vertex data to use
  32379. * @param updatable defines if the vertex must be flagged as updatable (false as default)
  32380. * @param stride defines the stride to use (0 by default). This value is deduced from the kind value if not specified
  32381. */
  32382. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  32383. if (updatable === void 0) { updatable = false; }
  32384. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  32385. this.setVerticesBuffer(buffer);
  32386. };
  32387. /**
  32388. * Removes a specific vertex data
  32389. * @param kind defines the data kind (Position, normal, etc...)
  32390. */
  32391. Geometry.prototype.removeVerticesData = function (kind) {
  32392. if (this._vertexBuffers[kind]) {
  32393. this._vertexBuffers[kind].dispose();
  32394. delete this._vertexBuffers[kind];
  32395. }
  32396. };
  32397. /**
  32398. * Affect a vertex buffer to the geometry. the vertexBuffer.getKind() function is used to determine where to store the data
  32399. * @param buffer defines the vertex buffer to use
  32400. */
  32401. Geometry.prototype.setVerticesBuffer = function (buffer) {
  32402. var kind = buffer.getKind();
  32403. if (this._vertexBuffers[kind]) {
  32404. this._vertexBuffers[kind].dispose();
  32405. }
  32406. this._vertexBuffers[kind] = buffer;
  32407. if (kind === BABYLON.VertexBuffer.PositionKind) {
  32408. var data = buffer.getData();
  32409. var stride = buffer.getStrideSize();
  32410. this._totalVertices = data.length / stride;
  32411. this.updateExtend(data, stride);
  32412. this._resetPointsArrayCache();
  32413. var meshes = this._meshes;
  32414. var numOfMeshes = meshes.length;
  32415. for (var index = 0; index < numOfMeshes; index++) {
  32416. var mesh = meshes[index];
  32417. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  32418. mesh._createGlobalSubMesh(false);
  32419. mesh.computeWorldMatrix(true);
  32420. }
  32421. }
  32422. this.notifyUpdate(kind);
  32423. if (this._vertexArrayObjects) {
  32424. this._disposeVertexArrayObjects();
  32425. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  32426. }
  32427. };
  32428. /**
  32429. * Update a specific vertex buffer
  32430. * This function will directly update the underlying WebGLBuffer according to the passed numeric array or Float32Array
  32431. * It will do nothing if the buffer is not updatable
  32432. * @param kind defines the data kind (Position, normal, etc...)
  32433. * @param data defines the data to use
  32434. * @param offset defines the offset in the target buffer where to store the data
  32435. */
  32436. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  32437. var vertexBuffer = this.getVertexBuffer(kind);
  32438. if (!vertexBuffer) {
  32439. return;
  32440. }
  32441. vertexBuffer.updateDirectly(data, offset);
  32442. this.notifyUpdate(kind);
  32443. };
  32444. /**
  32445. * Update a specific vertex buffer
  32446. * This function will create a new buffer if the current one is not updatable
  32447. * @param kind defines the data kind (Position, normal, etc...)
  32448. * @param data defines the data to use
  32449. * @param updateExtends defines if the geometry extends must be recomputed (false by default)
  32450. */
  32451. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  32452. if (updateExtends === void 0) { updateExtends = false; }
  32453. var vertexBuffer = this.getVertexBuffer(kind);
  32454. if (!vertexBuffer) {
  32455. return;
  32456. }
  32457. vertexBuffer.update(data);
  32458. if (kind === BABYLON.VertexBuffer.PositionKind) {
  32459. var stride = vertexBuffer.getStrideSize();
  32460. this._totalVertices = data.length / stride;
  32461. this.updateBoundingInfo(updateExtends, data);
  32462. }
  32463. this.notifyUpdate(kind);
  32464. };
  32465. Geometry.prototype.updateBoundingInfo = function (updateExtends, data) {
  32466. if (updateExtends) {
  32467. this.updateExtend(data);
  32468. }
  32469. var meshes = this._meshes;
  32470. var numOfMeshes = meshes.length;
  32471. this._resetPointsArrayCache();
  32472. for (var index = 0; index < numOfMeshes; index++) {
  32473. var mesh = meshes[index];
  32474. if (updateExtends) {
  32475. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  32476. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  32477. var subMesh = mesh.subMeshes[subIndex];
  32478. subMesh.refreshBoundingInfo();
  32479. }
  32480. }
  32481. }
  32482. };
  32483. /** @ignore */
  32484. Geometry.prototype._bind = function (effect, indexToBind) {
  32485. if (!effect) {
  32486. return;
  32487. }
  32488. if (indexToBind === undefined) {
  32489. indexToBind = this._indexBuffer;
  32490. }
  32491. var vbs = this.getVertexBuffers();
  32492. if (!vbs) {
  32493. return;
  32494. }
  32495. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  32496. this._engine.bindBuffers(vbs, indexToBind, effect);
  32497. return;
  32498. }
  32499. // Using VAO
  32500. if (!this._vertexArrayObjects[effect.key]) {
  32501. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(vbs, indexToBind, effect);
  32502. }
  32503. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  32504. };
  32505. /**
  32506. * Gets total number of vertices
  32507. * @returns the total number of vertices
  32508. */
  32509. Geometry.prototype.getTotalVertices = function () {
  32510. if (!this.isReady()) {
  32511. return 0;
  32512. }
  32513. return this._totalVertices;
  32514. };
  32515. /**
  32516. * Gets a specific vertex data attached to this geometry
  32517. * @param kind defines the data kind (Position, normal, etc...)
  32518. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  32519. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  32520. * @returns a float array containing vertex data
  32521. */
  32522. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  32523. var vertexBuffer = this.getVertexBuffer(kind);
  32524. if (!vertexBuffer) {
  32525. return null;
  32526. }
  32527. var orig = vertexBuffer.getData();
  32528. if (!forceCopy && (!copyWhenShared || this._meshes.length === 1)) {
  32529. return orig;
  32530. }
  32531. else {
  32532. var len = orig.length;
  32533. var copy = [];
  32534. for (var i = 0; i < len; i++) {
  32535. copy.push(orig[i]);
  32536. }
  32537. return copy;
  32538. }
  32539. };
  32540. /**
  32541. * Returns a boolean defining if the vertex data for the requested `kind` is updatable
  32542. * @param kind defines the data kind (Position, normal, etc...)
  32543. * @returns true if the vertex buffer with the specified kind is updatable
  32544. */
  32545. Geometry.prototype.isVertexBufferUpdatable = function (kind) {
  32546. var vb = this._vertexBuffers[kind];
  32547. if (!vb) {
  32548. return false;
  32549. }
  32550. return vb.isUpdatable();
  32551. };
  32552. /**
  32553. * Gets a specific vertex buffer
  32554. * @param kind defines the data kind (Position, normal, etc...)
  32555. * @returns a {BABYLON.VertexBuffer}
  32556. */
  32557. Geometry.prototype.getVertexBuffer = function (kind) {
  32558. if (!this.isReady()) {
  32559. return null;
  32560. }
  32561. return this._vertexBuffers[kind];
  32562. };
  32563. /**
  32564. * Returns all vertex buffers
  32565. * @return an object holding all vertex buffers indexed by kind
  32566. */
  32567. Geometry.prototype.getVertexBuffers = function () {
  32568. if (!this.isReady()) {
  32569. return null;
  32570. }
  32571. return this._vertexBuffers;
  32572. };
  32573. /**
  32574. * Gets a boolean indicating if specific vertex buffer is present
  32575. * @param kind defines the data kind (Position, normal, etc...)
  32576. * @returns true if data is present
  32577. */
  32578. Geometry.prototype.isVerticesDataPresent = function (kind) {
  32579. if (!this._vertexBuffers) {
  32580. if (this._delayInfo) {
  32581. return this._delayInfo.indexOf(kind) !== -1;
  32582. }
  32583. return false;
  32584. }
  32585. return this._vertexBuffers[kind] !== undefined;
  32586. };
  32587. /**
  32588. * Gets a list of all attached data kinds (Position, normal, etc...)
  32589. * @returns a list of string containing all kinds
  32590. */
  32591. Geometry.prototype.getVerticesDataKinds = function () {
  32592. var result = [];
  32593. var kind;
  32594. if (!this._vertexBuffers && this._delayInfo) {
  32595. for (kind in this._delayInfo) {
  32596. result.push(kind);
  32597. }
  32598. }
  32599. else {
  32600. for (kind in this._vertexBuffers) {
  32601. result.push(kind);
  32602. }
  32603. }
  32604. return result;
  32605. };
  32606. /**
  32607. * Update index buffer
  32608. * @param indices defines the indices to store in the index buffer
  32609. * @param offset defines the offset in the target buffer where to store the data
  32610. */
  32611. Geometry.prototype.updateIndices = function (indices, offset) {
  32612. if (!this._indexBuffer) {
  32613. return;
  32614. }
  32615. if (!this._indexBufferIsUpdatable) {
  32616. this.setIndices(indices, null, true);
  32617. }
  32618. else {
  32619. this._engine.updateDynamicIndexBuffer(this._indexBuffer, indices, offset);
  32620. }
  32621. };
  32622. /**
  32623. * Creates a new index buffer
  32624. * @param indices defines the indices to store in the index buffer
  32625. * @param totalVertices defines the total number of vertices (could be null)
  32626. * @param updatable defines if the index buffer must be flagged as updatable (false by default)
  32627. */
  32628. Geometry.prototype.setIndices = function (indices, totalVertices, updatable) {
  32629. if (totalVertices === void 0) { totalVertices = null; }
  32630. if (updatable === void 0) { updatable = false; }
  32631. if (this._indexBuffer) {
  32632. this._engine._releaseBuffer(this._indexBuffer);
  32633. }
  32634. this._disposeVertexArrayObjects();
  32635. this._indices = indices;
  32636. this._indexBufferIsUpdatable = updatable;
  32637. if (this._meshes.length !== 0 && this._indices) {
  32638. this._indexBuffer = this._engine.createIndexBuffer(this._indices, updatable);
  32639. }
  32640. if (totalVertices != undefined) {
  32641. this._totalVertices = totalVertices;
  32642. }
  32643. var meshes = this._meshes;
  32644. var numOfMeshes = meshes.length;
  32645. for (var index = 0; index < numOfMeshes; index++) {
  32646. meshes[index]._createGlobalSubMesh(true);
  32647. }
  32648. this.notifyUpdate();
  32649. };
  32650. /**
  32651. * Return the total number of indices
  32652. * @returns the total number of indices
  32653. */
  32654. Geometry.prototype.getTotalIndices = function () {
  32655. if (!this.isReady()) {
  32656. return 0;
  32657. }
  32658. return this._indices.length;
  32659. };
  32660. /**
  32661. * Gets the index buffer array
  32662. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  32663. * @returns the index buffer array
  32664. */
  32665. Geometry.prototype.getIndices = function (copyWhenShared) {
  32666. if (!this.isReady()) {
  32667. return null;
  32668. }
  32669. var orig = this._indices;
  32670. if (!copyWhenShared || this._meshes.length === 1) {
  32671. return orig;
  32672. }
  32673. else {
  32674. var len = orig.length;
  32675. var copy = [];
  32676. for (var i = 0; i < len; i++) {
  32677. copy.push(orig[i]);
  32678. }
  32679. return copy;
  32680. }
  32681. };
  32682. /**
  32683. * Gets the index buffer
  32684. * @return the index buffer
  32685. */
  32686. Geometry.prototype.getIndexBuffer = function () {
  32687. if (!this.isReady()) {
  32688. return null;
  32689. }
  32690. return this._indexBuffer;
  32691. };
  32692. /** @ignore */
  32693. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  32694. if (effect === void 0) { effect = null; }
  32695. if (!effect || !this._vertexArrayObjects) {
  32696. return;
  32697. }
  32698. if (this._vertexArrayObjects[effect.key]) {
  32699. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  32700. delete this._vertexArrayObjects[effect.key];
  32701. }
  32702. };
  32703. /**
  32704. * Release the associated resources for a specific mesh
  32705. * @param mesh defines the source mesh
  32706. * @param shouldDispose defines if the geometry must be disposed if there is no more mesh pointing to it
  32707. */
  32708. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  32709. var meshes = this._meshes;
  32710. var index = meshes.indexOf(mesh);
  32711. if (index === -1) {
  32712. return;
  32713. }
  32714. meshes.splice(index, 1);
  32715. mesh._geometry = null;
  32716. if (meshes.length === 0 && shouldDispose) {
  32717. this.dispose();
  32718. }
  32719. };
  32720. /**
  32721. * Apply current geometry to a given mesh
  32722. * @param mesh defines the mesh to apply geometry to
  32723. */
  32724. Geometry.prototype.applyToMesh = function (mesh) {
  32725. if (mesh._geometry === this) {
  32726. return;
  32727. }
  32728. var previousGeometry = mesh._geometry;
  32729. if (previousGeometry) {
  32730. previousGeometry.releaseForMesh(mesh);
  32731. }
  32732. var meshes = this._meshes;
  32733. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  32734. mesh._geometry = this;
  32735. this._scene.pushGeometry(this);
  32736. meshes.push(mesh);
  32737. if (this.isReady()) {
  32738. this._applyToMesh(mesh);
  32739. }
  32740. else {
  32741. mesh._boundingInfo = this._boundingInfo;
  32742. }
  32743. };
  32744. Geometry.prototype.updateExtend = function (data, stride) {
  32745. if (data === void 0) { data = null; }
  32746. if (!data) {
  32747. data = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind].getData();
  32748. }
  32749. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, stride);
  32750. };
  32751. Geometry.prototype._applyToMesh = function (mesh) {
  32752. var numOfMeshes = this._meshes.length;
  32753. // vertexBuffers
  32754. for (var kind in this._vertexBuffers) {
  32755. if (numOfMeshes === 1) {
  32756. this._vertexBuffers[kind].create();
  32757. }
  32758. var buffer = this._vertexBuffers[kind].getBuffer();
  32759. if (buffer)
  32760. buffer.references = numOfMeshes;
  32761. if (kind === BABYLON.VertexBuffer.PositionKind) {
  32762. if (!this._extend) {
  32763. this.updateExtend(this._vertexBuffers[kind].getData());
  32764. }
  32765. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  32766. mesh._createGlobalSubMesh(false);
  32767. //bounding info was just created again, world matrix should be applied again.
  32768. mesh._updateBoundingInfo();
  32769. }
  32770. }
  32771. // indexBuffer
  32772. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  32773. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  32774. }
  32775. if (this._indexBuffer) {
  32776. this._indexBuffer.references = numOfMeshes;
  32777. }
  32778. };
  32779. Geometry.prototype.notifyUpdate = function (kind) {
  32780. if (this.onGeometryUpdated) {
  32781. this.onGeometryUpdated(this, kind);
  32782. }
  32783. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  32784. var mesh = _a[_i];
  32785. mesh._markSubMeshesAsAttributesDirty();
  32786. }
  32787. };
  32788. /**
  32789. * Load the geometry if it was flagged as delay loaded
  32790. * @param scene defines the hosting scene
  32791. * @param onLoaded defines a callback called when the geometry is loaded
  32792. */
  32793. Geometry.prototype.load = function (scene, onLoaded) {
  32794. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  32795. return;
  32796. }
  32797. if (this.isReady()) {
  32798. if (onLoaded) {
  32799. onLoaded();
  32800. }
  32801. return;
  32802. }
  32803. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  32804. this._queueLoad(scene, onLoaded);
  32805. };
  32806. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  32807. var _this = this;
  32808. if (!this.delayLoadingFile) {
  32809. return;
  32810. }
  32811. scene._addPendingData(this);
  32812. scene._loadFile(this.delayLoadingFile, function (data) {
  32813. if (!_this._delayLoadingFunction) {
  32814. return;
  32815. }
  32816. _this._delayLoadingFunction(JSON.parse(data), _this);
  32817. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  32818. _this._delayInfo = [];
  32819. scene._removePendingData(_this);
  32820. var meshes = _this._meshes;
  32821. var numOfMeshes = meshes.length;
  32822. for (var index = 0; index < numOfMeshes; index++) {
  32823. _this._applyToMesh(meshes[index]);
  32824. }
  32825. if (onLoaded) {
  32826. onLoaded();
  32827. }
  32828. }, undefined, true);
  32829. };
  32830. /**
  32831. * Invert the geometry to move from a right handed system to a left handed one.
  32832. */
  32833. Geometry.prototype.toLeftHanded = function () {
  32834. // Flip faces
  32835. var tIndices = this.getIndices(false);
  32836. if (tIndices != null && tIndices.length > 0) {
  32837. for (var i = 0; i < tIndices.length; i += 3) {
  32838. var tTemp = tIndices[i + 0];
  32839. tIndices[i + 0] = tIndices[i + 2];
  32840. tIndices[i + 2] = tTemp;
  32841. }
  32842. this.setIndices(tIndices);
  32843. }
  32844. // Negate position.z
  32845. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  32846. if (tPositions != null && tPositions.length > 0) {
  32847. for (var i = 0; i < tPositions.length; i += 3) {
  32848. tPositions[i + 2] = -tPositions[i + 2];
  32849. }
  32850. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  32851. }
  32852. // Negate normal.z
  32853. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  32854. if (tNormals != null && tNormals.length > 0) {
  32855. for (var i = 0; i < tNormals.length; i += 3) {
  32856. tNormals[i + 2] = -tNormals[i + 2];
  32857. }
  32858. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  32859. }
  32860. };
  32861. // Cache
  32862. /** @ignore */
  32863. Geometry.prototype._resetPointsArrayCache = function () {
  32864. this._positions = null;
  32865. };
  32866. /** @ignore */
  32867. Geometry.prototype._generatePointsArray = function () {
  32868. if (this._positions)
  32869. return true;
  32870. this._positions = [];
  32871. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32872. if (!data) {
  32873. return false;
  32874. }
  32875. for (var index = 0; index < data.length; index += 3) {
  32876. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  32877. }
  32878. return true;
  32879. };
  32880. /**
  32881. * Gets a value indicating if the geometry is disposed
  32882. * @returns true if the geometry was disposed
  32883. */
  32884. Geometry.prototype.isDisposed = function () {
  32885. return this._isDisposed;
  32886. };
  32887. Geometry.prototype._disposeVertexArrayObjects = function () {
  32888. if (this._vertexArrayObjects) {
  32889. for (var kind in this._vertexArrayObjects) {
  32890. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  32891. }
  32892. this._vertexArrayObjects = {};
  32893. }
  32894. };
  32895. /**
  32896. * Free all associated resources
  32897. */
  32898. Geometry.prototype.dispose = function () {
  32899. var meshes = this._meshes;
  32900. var numOfMeshes = meshes.length;
  32901. var index;
  32902. for (index = 0; index < numOfMeshes; index++) {
  32903. this.releaseForMesh(meshes[index]);
  32904. }
  32905. this._meshes = [];
  32906. this._disposeVertexArrayObjects();
  32907. for (var kind in this._vertexBuffers) {
  32908. this._vertexBuffers[kind].dispose();
  32909. }
  32910. this._vertexBuffers = {};
  32911. this._totalVertices = 0;
  32912. if (this._indexBuffer) {
  32913. this._engine._releaseBuffer(this._indexBuffer);
  32914. }
  32915. this._indexBuffer = null;
  32916. this._indices = [];
  32917. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  32918. this.delayLoadingFile = null;
  32919. this._delayLoadingFunction = null;
  32920. this._delayInfo = [];
  32921. this._boundingInfo = null;
  32922. this._scene.removeGeometry(this);
  32923. this._isDisposed = true;
  32924. };
  32925. /**
  32926. * Clone the current geometry into a new geometry
  32927. * @param id defines the unique ID of the new geometry
  32928. * @returns a new geometry object
  32929. */
  32930. Geometry.prototype.copy = function (id) {
  32931. var vertexData = new BABYLON.VertexData();
  32932. vertexData.indices = [];
  32933. var indices = this.getIndices();
  32934. if (indices) {
  32935. for (var index = 0; index < indices.length; index++) {
  32936. vertexData.indices.push(indices[index]);
  32937. }
  32938. }
  32939. var updatable = false;
  32940. var stopChecking = false;
  32941. var kind;
  32942. for (kind in this._vertexBuffers) {
  32943. // using slice() to make a copy of the array and not just reference it
  32944. var data = this.getVerticesData(kind);
  32945. if (data instanceof Float32Array) {
  32946. vertexData.set(new Float32Array(data), kind);
  32947. }
  32948. else {
  32949. vertexData.set(data.slice(0), kind);
  32950. }
  32951. if (!stopChecking) {
  32952. var vb = this.getVertexBuffer(kind);
  32953. if (vb) {
  32954. updatable = vb.isUpdatable();
  32955. stopChecking = !updatable;
  32956. }
  32957. }
  32958. }
  32959. var geometry = new Geometry(id, this._scene, vertexData, updatable);
  32960. geometry.delayLoadState = this.delayLoadState;
  32961. geometry.delayLoadingFile = this.delayLoadingFile;
  32962. geometry._delayLoadingFunction = this._delayLoadingFunction;
  32963. for (kind in this._delayInfo) {
  32964. geometry._delayInfo = geometry._delayInfo || [];
  32965. geometry._delayInfo.push(kind);
  32966. }
  32967. // Bounding info
  32968. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  32969. return geometry;
  32970. };
  32971. /**
  32972. * Serialize the current geometry info (and not the vertices data) into a JSON object
  32973. * @return a JSON representation of the current geometry data (without the vertices data)
  32974. */
  32975. Geometry.prototype.serialize = function () {
  32976. var serializationObject = {};
  32977. serializationObject.id = this.id;
  32978. serializationObject.updatable = this._updatable;
  32979. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  32980. serializationObject.tags = BABYLON.Tags.GetTags(this);
  32981. }
  32982. return serializationObject;
  32983. };
  32984. Geometry.prototype.toNumberArray = function (origin) {
  32985. if (Array.isArray(origin)) {
  32986. return origin;
  32987. }
  32988. else {
  32989. return Array.prototype.slice.call(origin);
  32990. }
  32991. };
  32992. /**
  32993. * Serialize all vertices data into a JSON oject
  32994. * @returns a JSON representation of the current geometry data
  32995. */
  32996. Geometry.prototype.serializeVerticeData = function () {
  32997. var serializationObject = this.serialize();
  32998. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  32999. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  33000. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  33001. serializationObject.positions._updatable = true;
  33002. }
  33003. }
  33004. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  33005. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  33006. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  33007. serializationObject.normals._updatable = true;
  33008. }
  33009. }
  33010. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  33011. serializationObject.tangets = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  33012. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.TangentKind)) {
  33013. serializationObject.tangets._updatable = true;
  33014. }
  33015. }
  33016. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  33017. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  33018. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UVKind)) {
  33019. serializationObject.uvs._updatable = true;
  33020. }
  33021. }
  33022. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  33023. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  33024. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV2Kind)) {
  33025. serializationObject.uv2s._updatable = true;
  33026. }
  33027. }
  33028. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  33029. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  33030. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV3Kind)) {
  33031. serializationObject.uv3s._updatable = true;
  33032. }
  33033. }
  33034. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  33035. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  33036. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV4Kind)) {
  33037. serializationObject.uv4s._updatable = true;
  33038. }
  33039. }
  33040. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  33041. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  33042. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV5Kind)) {
  33043. serializationObject.uv5s._updatable = true;
  33044. }
  33045. }
  33046. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  33047. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  33048. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV6Kind)) {
  33049. serializationObject.uv6s._updatable = true;
  33050. }
  33051. }
  33052. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  33053. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  33054. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.ColorKind)) {
  33055. serializationObject.colors._updatable = true;
  33056. }
  33057. }
  33058. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  33059. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  33060. serializationObject.matricesIndices._isExpanded = true;
  33061. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  33062. serializationObject.matricesIndices._updatable = true;
  33063. }
  33064. }
  33065. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  33066. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  33067. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  33068. serializationObject.matricesWeights._updatable = true;
  33069. }
  33070. }
  33071. serializationObject.indices = this.toNumberArray(this.getIndices());
  33072. return serializationObject;
  33073. };
  33074. // Statics
  33075. /**
  33076. * Extracts a clone of a mesh geometry
  33077. * @param mesh defines the source mesh
  33078. * @param id defines the unique ID of the new geometry object
  33079. * @returns the new geometry object
  33080. */
  33081. Geometry.ExtractFromMesh = function (mesh, id) {
  33082. var geometry = mesh._geometry;
  33083. if (!geometry) {
  33084. return null;
  33085. }
  33086. return geometry.copy(id);
  33087. };
  33088. /**
  33089. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  33090. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  33091. * Be aware Math.random() could cause collisions, but:
  33092. * "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"
  33093. * @returns a string containing a new GUID
  33094. */
  33095. Geometry.RandomId = function () {
  33096. return BABYLON.Tools.RandomId();
  33097. };
  33098. /** @ignore */
  33099. Geometry._ImportGeometry = function (parsedGeometry, mesh) {
  33100. var scene = mesh.getScene();
  33101. // Geometry
  33102. var geometryId = parsedGeometry.geometryId;
  33103. if (geometryId) {
  33104. var geometry = scene.getGeometryByID(geometryId);
  33105. if (geometry) {
  33106. geometry.applyToMesh(mesh);
  33107. }
  33108. }
  33109. else if (parsedGeometry instanceof ArrayBuffer) {
  33110. var binaryInfo = mesh._binaryInfo;
  33111. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  33112. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  33113. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  33114. }
  33115. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  33116. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  33117. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  33118. }
  33119. if (binaryInfo.tangetsAttrDesc && binaryInfo.tangetsAttrDesc.count > 0) {
  33120. var tangentsData = new Float32Array(parsedGeometry, binaryInfo.tangetsAttrDesc.offset, binaryInfo.tangetsAttrDesc.count);
  33121. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, tangentsData, false);
  33122. }
  33123. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  33124. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  33125. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  33126. }
  33127. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  33128. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  33129. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  33130. }
  33131. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  33132. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  33133. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  33134. }
  33135. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  33136. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  33137. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  33138. }
  33139. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  33140. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  33141. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  33142. }
  33143. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  33144. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  33145. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  33146. }
  33147. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  33148. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  33149. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  33150. }
  33151. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  33152. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  33153. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  33154. }
  33155. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  33156. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  33157. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  33158. }
  33159. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  33160. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  33161. mesh.setIndices(indicesData, null);
  33162. }
  33163. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  33164. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  33165. mesh.subMeshes = [];
  33166. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  33167. var materialIndex = subMeshesData[(i * 5) + 0];
  33168. var verticesStart = subMeshesData[(i * 5) + 1];
  33169. var verticesCount = subMeshesData[(i * 5) + 2];
  33170. var indexStart = subMeshesData[(i * 5) + 3];
  33171. var indexCount = subMeshesData[(i * 5) + 4];
  33172. BABYLON.SubMesh.AddToMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  33173. }
  33174. }
  33175. }
  33176. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  33177. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  33178. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  33179. if (parsedGeometry.tangents) {
  33180. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, parsedGeometry.tangents, parsedGeometry.tangents._updatable);
  33181. }
  33182. if (parsedGeometry.uvs) {
  33183. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  33184. }
  33185. if (parsedGeometry.uvs2) {
  33186. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  33187. }
  33188. if (parsedGeometry.uvs3) {
  33189. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  33190. }
  33191. if (parsedGeometry.uvs4) {
  33192. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  33193. }
  33194. if (parsedGeometry.uvs5) {
  33195. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  33196. }
  33197. if (parsedGeometry.uvs6) {
  33198. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  33199. }
  33200. if (parsedGeometry.colors) {
  33201. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  33202. }
  33203. if (parsedGeometry.matricesIndices) {
  33204. if (!parsedGeometry.matricesIndices._isExpanded) {
  33205. var floatIndices = [];
  33206. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  33207. var matricesIndex = parsedGeometry.matricesIndices[i];
  33208. floatIndices.push(matricesIndex & 0x000000FF);
  33209. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  33210. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  33211. floatIndices.push(matricesIndex >> 24);
  33212. }
  33213. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  33214. }
  33215. else {
  33216. delete parsedGeometry.matricesIndices._isExpanded;
  33217. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  33218. }
  33219. }
  33220. if (parsedGeometry.matricesIndicesExtra) {
  33221. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  33222. var floatIndices = [];
  33223. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  33224. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  33225. floatIndices.push(matricesIndex & 0x000000FF);
  33226. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  33227. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  33228. floatIndices.push(matricesIndex >> 24);
  33229. }
  33230. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  33231. }
  33232. else {
  33233. delete parsedGeometry.matricesIndices._isExpanded;
  33234. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  33235. }
  33236. }
  33237. if (parsedGeometry.matricesWeights) {
  33238. Geometry._CleanMatricesWeights(parsedGeometry, mesh);
  33239. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  33240. }
  33241. if (parsedGeometry.matricesWeightsExtra) {
  33242. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  33243. }
  33244. mesh.setIndices(parsedGeometry.indices, null);
  33245. }
  33246. // SubMeshes
  33247. if (parsedGeometry.subMeshes) {
  33248. mesh.subMeshes = [];
  33249. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  33250. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  33251. BABYLON.SubMesh.AddToMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  33252. }
  33253. }
  33254. // Flat shading
  33255. if (mesh._shouldGenerateFlatShading) {
  33256. mesh.convertToFlatShadedMesh();
  33257. delete mesh._shouldGenerateFlatShading;
  33258. }
  33259. // Update
  33260. mesh.computeWorldMatrix(true);
  33261. // Octree
  33262. var sceneOctree = scene.selectionOctree;
  33263. if (sceneOctree !== undefined && sceneOctree !== null) {
  33264. sceneOctree.addMesh(mesh);
  33265. }
  33266. };
  33267. Geometry._CleanMatricesWeights = function (parsedGeometry, mesh) {
  33268. var epsilon = 1e-3;
  33269. if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) {
  33270. return;
  33271. }
  33272. var noInfluenceBoneIndex = 0.0;
  33273. if (parsedGeometry.skeletonId > -1) {
  33274. var skeleton = mesh.getScene().getLastSkeletonByID(parsedGeometry.skeletonId);
  33275. if (!skeleton) {
  33276. return;
  33277. }
  33278. noInfluenceBoneIndex = skeleton.bones.length;
  33279. }
  33280. else {
  33281. return;
  33282. }
  33283. var matricesIndices = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  33284. var matricesIndicesExtra = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  33285. var matricesWeights = parsedGeometry.matricesWeights;
  33286. var matricesWeightsExtra = parsedGeometry.matricesWeightsExtra;
  33287. var influencers = parsedGeometry.numBoneInfluencer;
  33288. var size = matricesWeights.length;
  33289. for (var i = 0; i < size; i += 4) {
  33290. var weight = 0.0;
  33291. var firstZeroWeight = -1;
  33292. for (var j = 0; j < 4; j++) {
  33293. var w = matricesWeights[i + j];
  33294. weight += w;
  33295. if (w < epsilon && firstZeroWeight < 0) {
  33296. firstZeroWeight = j;
  33297. }
  33298. }
  33299. if (matricesWeightsExtra) {
  33300. for (var j = 0; j < 4; j++) {
  33301. var w = matricesWeightsExtra[i + j];
  33302. weight += w;
  33303. if (w < epsilon && firstZeroWeight < 0) {
  33304. firstZeroWeight = j + 4;
  33305. }
  33306. }
  33307. }
  33308. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  33309. firstZeroWeight = influencers - 1;
  33310. }
  33311. if (weight > epsilon) {
  33312. var mweight = 1.0 / weight;
  33313. for (var j = 0; j < 4; j++) {
  33314. matricesWeights[i + j] *= mweight;
  33315. }
  33316. if (matricesWeightsExtra) {
  33317. for (var j = 0; j < 4; j++) {
  33318. matricesWeightsExtra[i + j] *= mweight;
  33319. }
  33320. }
  33321. }
  33322. else {
  33323. if (firstZeroWeight >= 4) {
  33324. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  33325. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  33326. }
  33327. else {
  33328. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  33329. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  33330. }
  33331. }
  33332. }
  33333. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  33334. if (parsedGeometry.matricesWeightsExtra) {
  33335. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  33336. }
  33337. };
  33338. /**
  33339. * Create a new geometry from persisted data (Using .babylon file format)
  33340. * @param parsedVertexData defines the persisted data
  33341. * @param scene defines the hosting scene
  33342. * @param rootUrl defines the root url to use to load assets (like delayed data)
  33343. * @returns the new geometry object
  33344. */
  33345. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  33346. if (scene.getGeometryByID(parsedVertexData.id)) {
  33347. return null; // null since geometry could be something else than a box...
  33348. }
  33349. var geometry = new Geometry(parsedVertexData.id, scene, undefined, parsedVertexData.updatable);
  33350. if (BABYLON.Tags) {
  33351. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  33352. }
  33353. if (parsedVertexData.delayLoadingFile) {
  33354. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  33355. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  33356. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  33357. geometry._delayInfo = [];
  33358. if (parsedVertexData.hasUVs) {
  33359. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  33360. }
  33361. if (parsedVertexData.hasUVs2) {
  33362. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  33363. }
  33364. if (parsedVertexData.hasUVs3) {
  33365. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  33366. }
  33367. if (parsedVertexData.hasUVs4) {
  33368. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  33369. }
  33370. if (parsedVertexData.hasUVs5) {
  33371. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  33372. }
  33373. if (parsedVertexData.hasUVs6) {
  33374. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  33375. }
  33376. if (parsedVertexData.hasColors) {
  33377. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  33378. }
  33379. if (parsedVertexData.hasMatricesIndices) {
  33380. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  33381. }
  33382. if (parsedVertexData.hasMatricesWeights) {
  33383. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  33384. }
  33385. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  33386. }
  33387. else {
  33388. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  33389. }
  33390. scene.pushGeometry(geometry, true);
  33391. return geometry;
  33392. };
  33393. return Geometry;
  33394. }());
  33395. BABYLON.Geometry = Geometry;
  33396. // Primitives
  33397. /// Abstract class
  33398. /**
  33399. * Abstract class used to provide common services for all typed geometries
  33400. */
  33401. var _PrimitiveGeometry = /** @class */ (function (_super) {
  33402. __extends(_PrimitiveGeometry, _super);
  33403. /**
  33404. * Creates a new typed geometry
  33405. * @param id defines the unique ID of the geometry
  33406. * @param scene defines the hosting scene
  33407. * @param _canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  33408. * @param mesh defines the hosting mesh (can be null)
  33409. */
  33410. function _PrimitiveGeometry(id, scene, _canBeRegenerated, mesh) {
  33411. if (_canBeRegenerated === void 0) { _canBeRegenerated = false; }
  33412. if (mesh === void 0) { mesh = null; }
  33413. var _this = _super.call(this, id, scene, undefined, false, mesh) || this;
  33414. _this._canBeRegenerated = _canBeRegenerated;
  33415. _this._beingRegenerated = true;
  33416. _this.regenerate();
  33417. _this._beingRegenerated = false;
  33418. return _this;
  33419. }
  33420. /**
  33421. * Gets a value indicating if the geometry supports being regenerated with new parameters (false by default)
  33422. * @returns true if the geometry can be regenerated
  33423. */
  33424. _PrimitiveGeometry.prototype.canBeRegenerated = function () {
  33425. return this._canBeRegenerated;
  33426. };
  33427. /**
  33428. * If the geometry supports regeneration, the function will recreates the geometry with updated parameter values
  33429. */
  33430. _PrimitiveGeometry.prototype.regenerate = function () {
  33431. if (!this._canBeRegenerated) {
  33432. return;
  33433. }
  33434. this._beingRegenerated = true;
  33435. this.setAllVerticesData(this._regenerateVertexData(), false);
  33436. this._beingRegenerated = false;
  33437. };
  33438. /**
  33439. * Clone the geometry
  33440. * @param id defines the unique ID of the new geometry
  33441. * @returns the new geometry
  33442. */
  33443. _PrimitiveGeometry.prototype.asNewGeometry = function (id) {
  33444. return _super.prototype.copy.call(this, id);
  33445. };
  33446. // overrides
  33447. _PrimitiveGeometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  33448. if (!this._beingRegenerated) {
  33449. return;
  33450. }
  33451. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  33452. };
  33453. _PrimitiveGeometry.prototype.setVerticesData = function (kind, data, updatable) {
  33454. if (!this._beingRegenerated) {
  33455. return;
  33456. }
  33457. _super.prototype.setVerticesData.call(this, kind, data, false);
  33458. };
  33459. // to override
  33460. /** @ignore */
  33461. _PrimitiveGeometry.prototype._regenerateVertexData = function () {
  33462. throw new Error("Abstract method");
  33463. };
  33464. _PrimitiveGeometry.prototype.copy = function (id) {
  33465. throw new Error("Must be overriden in sub-classes.");
  33466. };
  33467. _PrimitiveGeometry.prototype.serialize = function () {
  33468. var serializationObject = _super.prototype.serialize.call(this);
  33469. serializationObject.canBeRegenerated = this.canBeRegenerated();
  33470. return serializationObject;
  33471. };
  33472. return _PrimitiveGeometry;
  33473. }(Geometry));
  33474. BABYLON._PrimitiveGeometry = _PrimitiveGeometry;
  33475. /**
  33476. * Creates a ribbon geometry
  33477. * @description See http://doc.babylonjs.com/how_to/ribbon_tutorial, http://doc.babylonjs.com/resources/maths_make_ribbons
  33478. */
  33479. var RibbonGeometry = /** @class */ (function (_super) {
  33480. __extends(RibbonGeometry, _super);
  33481. /**
  33482. * Creates a ribbon geometry
  33483. * @param id defines the unique ID of the geometry
  33484. * @param scene defines the hosting scene
  33485. * @param pathArray defines the array of paths to use
  33486. * @param closeArray defines if the last path and the first path must be joined
  33487. * @param closePath defines if the last and first points of each path in your pathArray must be joined
  33488. * @param offset defines the offset between points
  33489. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  33490. * @param mesh defines the hosting mesh (can be null)
  33491. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  33492. */
  33493. function RibbonGeometry(id, scene,
  33494. /**
  33495. * Defines the array of paths to use
  33496. */
  33497. pathArray,
  33498. /**
  33499. * Defines if the last and first points of each path in your pathArray must be joined
  33500. */
  33501. closeArray,
  33502. /**
  33503. * Defines if the last and first points of each path in your pathArray must be joined
  33504. */
  33505. closePath,
  33506. /**
  33507. * Defines the offset between points
  33508. */
  33509. offset, canBeRegenerated, mesh,
  33510. /**
  33511. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  33512. */
  33513. side) {
  33514. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  33515. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  33516. _this.pathArray = pathArray;
  33517. _this.closeArray = closeArray;
  33518. _this.closePath = closePath;
  33519. _this.offset = offset;
  33520. _this.side = side;
  33521. return _this;
  33522. }
  33523. /** @ignore */
  33524. RibbonGeometry.prototype._regenerateVertexData = function () {
  33525. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  33526. };
  33527. RibbonGeometry.prototype.copy = function (id) {
  33528. return new RibbonGeometry(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), undefined, this.side);
  33529. };
  33530. return RibbonGeometry;
  33531. }(_PrimitiveGeometry));
  33532. BABYLON.RibbonGeometry = RibbonGeometry;
  33533. /**
  33534. * Creates a box geometry
  33535. * @description see http://doc.babylonjs.com/how_to/set_shapes#box
  33536. */
  33537. var BoxGeometry = /** @class */ (function (_super) {
  33538. __extends(BoxGeometry, _super);
  33539. /**
  33540. * Creates a box geometry
  33541. * @param id defines the unique ID of the geometry
  33542. * @param scene defines the hosting scene
  33543. * @param size defines the zise of the box (width, height and depth are the same)
  33544. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  33545. * @param mesh defines the hosting mesh (can be null)
  33546. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  33547. */
  33548. function BoxGeometry(id, scene,
  33549. /**
  33550. * Defines the zise of the box (width, height and depth are the same)
  33551. */
  33552. size, canBeRegenerated, mesh,
  33553. /**
  33554. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  33555. */
  33556. side) {
  33557. if (mesh === void 0) { mesh = null; }
  33558. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  33559. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  33560. _this.size = size;
  33561. _this.side = side;
  33562. return _this;
  33563. }
  33564. BoxGeometry.prototype._regenerateVertexData = function () {
  33565. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  33566. };
  33567. BoxGeometry.prototype.copy = function (id) {
  33568. return new BoxGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), undefined, this.side);
  33569. };
  33570. BoxGeometry.prototype.serialize = function () {
  33571. var serializationObject = _super.prototype.serialize.call(this);
  33572. serializationObject.size = this.size;
  33573. return serializationObject;
  33574. };
  33575. BoxGeometry.Parse = function (parsedBox, scene) {
  33576. if (scene.getGeometryByID(parsedBox.id)) {
  33577. return null; // null since geometry could be something else than a box...
  33578. }
  33579. var box = new BoxGeometry(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  33580. if (BABYLON.Tags) {
  33581. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  33582. }
  33583. scene.pushGeometry(box, true);
  33584. return box;
  33585. };
  33586. return BoxGeometry;
  33587. }(_PrimitiveGeometry));
  33588. BABYLON.BoxGeometry = BoxGeometry;
  33589. /**
  33590. * Creates a sphere geometry
  33591. * @description see http://doc.babylonjs.com/how_to/set_shapes#sphere
  33592. */
  33593. var SphereGeometry = /** @class */ (function (_super) {
  33594. __extends(SphereGeometry, _super);
  33595. /**
  33596. * Create a new sphere geometry
  33597. * @param id defines the unique ID of the geometry
  33598. * @param scene defines the hosting scene
  33599. * @param segments defines the number of segments to use to create the sphere
  33600. * @param diameter defines the diameter of the sphere
  33601. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  33602. * @param mesh defines the hosting mesh (can be null)
  33603. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  33604. */
  33605. function SphereGeometry(id, scene,
  33606. /**
  33607. * Defines the number of segments to use to create the sphere
  33608. */
  33609. segments,
  33610. /**
  33611. * Defines the diameter of the sphere
  33612. */
  33613. diameter, canBeRegenerated, mesh,
  33614. /**
  33615. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  33616. */
  33617. side) {
  33618. if (mesh === void 0) { mesh = null; }
  33619. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  33620. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  33621. _this.segments = segments;
  33622. _this.diameter = diameter;
  33623. _this.side = side;
  33624. return _this;
  33625. }
  33626. SphereGeometry.prototype._regenerateVertexData = function () {
  33627. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  33628. };
  33629. SphereGeometry.prototype.copy = function (id) {
  33630. return new SphereGeometry(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  33631. };
  33632. SphereGeometry.prototype.serialize = function () {
  33633. var serializationObject = _super.prototype.serialize.call(this);
  33634. serializationObject.segments = this.segments;
  33635. serializationObject.diameter = this.diameter;
  33636. return serializationObject;
  33637. };
  33638. SphereGeometry.Parse = function (parsedSphere, scene) {
  33639. if (scene.getGeometryByID(parsedSphere.id)) {
  33640. return null; // null since geometry could be something else than a sphere...
  33641. }
  33642. var sphere = new SphereGeometry(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  33643. if (BABYLON.Tags) {
  33644. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  33645. }
  33646. scene.pushGeometry(sphere, true);
  33647. return sphere;
  33648. };
  33649. return SphereGeometry;
  33650. }(_PrimitiveGeometry));
  33651. BABYLON.SphereGeometry = SphereGeometry;
  33652. /**
  33653. * Creates a disc geometry
  33654. * @description see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  33655. */
  33656. var DiscGeometry = /** @class */ (function (_super) {
  33657. __extends(DiscGeometry, _super);
  33658. /**
  33659. * Creates a new disc geometry
  33660. * @param id defines the unique ID of the geometry
  33661. * @param scene defines the hosting scene
  33662. * @param radius defines the radius of the disc
  33663. * @param tessellation defines the tesselation factor to apply to the disc
  33664. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  33665. * @param mesh defines the hosting mesh (can be null)
  33666. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  33667. */
  33668. function DiscGeometry(id, scene,
  33669. /**
  33670. * Defines the radius of the disc
  33671. */
  33672. radius,
  33673. /**
  33674. * Defines the tesselation factor to apply to the disc
  33675. */
  33676. tessellation, canBeRegenerated, mesh,
  33677. /**
  33678. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  33679. */
  33680. side) {
  33681. if (mesh === void 0) { mesh = null; }
  33682. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  33683. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  33684. _this.radius = radius;
  33685. _this.tessellation = tessellation;
  33686. _this.side = side;
  33687. return _this;
  33688. }
  33689. DiscGeometry.prototype._regenerateVertexData = function () {
  33690. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  33691. };
  33692. DiscGeometry.prototype.copy = function (id) {
  33693. return new DiscGeometry(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  33694. };
  33695. return DiscGeometry;
  33696. }(_PrimitiveGeometry));
  33697. BABYLON.DiscGeometry = DiscGeometry;
  33698. /**
  33699. * Creates a new cylinder geometry
  33700. * @description see http://doc.babylonjs.com/how_to/set_shapes#cylinder-or-cone
  33701. */
  33702. var CylinderGeometry = /** @class */ (function (_super) {
  33703. __extends(CylinderGeometry, _super);
  33704. /**
  33705. * Creates a new cylinder geometry
  33706. * @param id defines the unique ID of the geometry
  33707. * @param scene defines the hosting scene
  33708. * @param height defines the height of the cylinder
  33709. * @param diameterTop defines the diameter of the cylinder's top cap
  33710. * @param diameterBottom defines the diameter of the cylinder's bottom cap
  33711. * @param tessellation defines the tessellation factor to apply to the cylinder (number of radial sides)
  33712. * @param subdivisions defines the number of subdivisions to apply to the cylinder (number of rings) (1 by default)
  33713. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  33714. * @param mesh defines the hosting mesh (can be null)
  33715. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  33716. */
  33717. function CylinderGeometry(id, scene,
  33718. /**
  33719. * Defines the height of the cylinder
  33720. */
  33721. height,
  33722. /**
  33723. * Defines the diameter of the cylinder's top cap
  33724. */
  33725. diameterTop,
  33726. /**
  33727. * Defines the diameter of the cylinder's bottom cap
  33728. */
  33729. diameterBottom,
  33730. /**
  33731. * Defines the tessellation factor to apply to the cylinder
  33732. */
  33733. tessellation,
  33734. /**
  33735. * Defines the number of subdivisions to apply to the cylinder (1 by default)
  33736. */
  33737. subdivisions, canBeRegenerated, mesh,
  33738. /**
  33739. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  33740. */
  33741. side) {
  33742. if (subdivisions === void 0) { subdivisions = 1; }
  33743. if (mesh === void 0) { mesh = null; }
  33744. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  33745. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  33746. _this.height = height;
  33747. _this.diameterTop = diameterTop;
  33748. _this.diameterBottom = diameterBottom;
  33749. _this.tessellation = tessellation;
  33750. _this.subdivisions = subdivisions;
  33751. _this.side = side;
  33752. return _this;
  33753. }
  33754. CylinderGeometry.prototype._regenerateVertexData = function () {
  33755. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  33756. };
  33757. CylinderGeometry.prototype.copy = function (id) {
  33758. return new CylinderGeometry(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  33759. };
  33760. CylinderGeometry.prototype.serialize = function () {
  33761. var serializationObject = _super.prototype.serialize.call(this);
  33762. serializationObject.height = this.height;
  33763. serializationObject.diameterTop = this.diameterTop;
  33764. serializationObject.diameterBottom = this.diameterBottom;
  33765. serializationObject.tessellation = this.tessellation;
  33766. return serializationObject;
  33767. };
  33768. CylinderGeometry.Parse = function (parsedCylinder, scene) {
  33769. if (scene.getGeometryByID(parsedCylinder.id)) {
  33770. return null; // null since geometry could be something else than a cylinder...
  33771. }
  33772. var cylinder = new CylinderGeometry(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  33773. if (BABYLON.Tags) {
  33774. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  33775. }
  33776. scene.pushGeometry(cylinder, true);
  33777. return cylinder;
  33778. };
  33779. return CylinderGeometry;
  33780. }(_PrimitiveGeometry));
  33781. BABYLON.CylinderGeometry = CylinderGeometry;
  33782. /**
  33783. * Creates a new torus geometry
  33784. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus
  33785. */
  33786. var TorusGeometry = /** @class */ (function (_super) {
  33787. __extends(TorusGeometry, _super);
  33788. /**
  33789. * Creates a new torus geometry
  33790. * @param id defines the unique ID of the geometry
  33791. * @param scene defines the hosting scene
  33792. * @param diameter defines the diameter of the torus
  33793. * @param thickness defines the thickness of the torus (ie. internal diameter)
  33794. * @param tessellation defines the tesselation factor to apply to the torus (number of segments along the circle)
  33795. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  33796. * @param mesh defines the hosting mesh (can be null)
  33797. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  33798. */
  33799. function TorusGeometry(id, scene,
  33800. /**
  33801. * Defines the diameter of the torus
  33802. */
  33803. diameter,
  33804. /**
  33805. * Defines the thickness of the torus (ie. internal diameter)
  33806. */
  33807. thickness,
  33808. /**
  33809. * Defines the tesselation factor to apply to the torus
  33810. */
  33811. tessellation, canBeRegenerated, mesh,
  33812. /**
  33813. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  33814. */
  33815. side) {
  33816. if (mesh === void 0) { mesh = null; }
  33817. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  33818. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  33819. _this.diameter = diameter;
  33820. _this.thickness = thickness;
  33821. _this.tessellation = tessellation;
  33822. _this.side = side;
  33823. return _this;
  33824. }
  33825. TorusGeometry.prototype._regenerateVertexData = function () {
  33826. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  33827. };
  33828. TorusGeometry.prototype.copy = function (id) {
  33829. return new TorusGeometry(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  33830. };
  33831. TorusGeometry.prototype.serialize = function () {
  33832. var serializationObject = _super.prototype.serialize.call(this);
  33833. serializationObject.diameter = this.diameter;
  33834. serializationObject.thickness = this.thickness;
  33835. serializationObject.tessellation = this.tessellation;
  33836. return serializationObject;
  33837. };
  33838. TorusGeometry.Parse = function (parsedTorus, scene) {
  33839. if (scene.getGeometryByID(parsedTorus.id)) {
  33840. return null; // null since geometry could be something else than a torus...
  33841. }
  33842. var torus = new TorusGeometry(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  33843. if (BABYLON.Tags) {
  33844. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  33845. }
  33846. scene.pushGeometry(torus, true);
  33847. return torus;
  33848. };
  33849. return TorusGeometry;
  33850. }(_PrimitiveGeometry));
  33851. BABYLON.TorusGeometry = TorusGeometry;
  33852. /**
  33853. * Creates a new ground geometry
  33854. * @description see http://doc.babylonjs.com/how_to/set_shapes#ground
  33855. */
  33856. var GroundGeometry = /** @class */ (function (_super) {
  33857. __extends(GroundGeometry, _super);
  33858. /**
  33859. * Creates a new ground geometry
  33860. * @param id defines the unique ID of the geometry
  33861. * @param scene defines the hosting scene
  33862. * @param width defines the width of the ground
  33863. * @param height defines the height of the ground
  33864. * @param subdivisions defines the subdivisions to apply to the ground
  33865. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  33866. * @param mesh defines the hosting mesh (can be null)
  33867. */
  33868. function GroundGeometry(id, scene,
  33869. /**
  33870. * Defines the width of the ground
  33871. */
  33872. width,
  33873. /**
  33874. * Defines the height of the ground
  33875. */
  33876. height,
  33877. /**
  33878. * Defines the subdivisions to apply to the ground
  33879. */
  33880. subdivisions, canBeRegenerated, mesh) {
  33881. if (mesh === void 0) { mesh = null; }
  33882. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  33883. _this.width = width;
  33884. _this.height = height;
  33885. _this.subdivisions = subdivisions;
  33886. return _this;
  33887. }
  33888. GroundGeometry.prototype._regenerateVertexData = function () {
  33889. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  33890. };
  33891. GroundGeometry.prototype.copy = function (id) {
  33892. return new GroundGeometry(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  33893. };
  33894. GroundGeometry.prototype.serialize = function () {
  33895. var serializationObject = _super.prototype.serialize.call(this);
  33896. serializationObject.width = this.width;
  33897. serializationObject.height = this.height;
  33898. serializationObject.subdivisions = this.subdivisions;
  33899. return serializationObject;
  33900. };
  33901. GroundGeometry.Parse = function (parsedGround, scene) {
  33902. if (scene.getGeometryByID(parsedGround.id)) {
  33903. return null; // null since geometry could be something else than a ground...
  33904. }
  33905. var ground = new GroundGeometry(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  33906. if (BABYLON.Tags) {
  33907. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  33908. }
  33909. scene.pushGeometry(ground, true);
  33910. return ground;
  33911. };
  33912. return GroundGeometry;
  33913. }(_PrimitiveGeometry));
  33914. BABYLON.GroundGeometry = GroundGeometry;
  33915. /**
  33916. * Creates a tiled ground geometry
  33917. * @description see http://doc.babylonjs.com/how_to/set_shapes#tiled-ground
  33918. */
  33919. var TiledGroundGeometry = /** @class */ (function (_super) {
  33920. __extends(TiledGroundGeometry, _super);
  33921. /**
  33922. * Creates a tiled ground geometry
  33923. * @param id defines the unique ID of the geometry
  33924. * @param scene defines the hosting scene
  33925. * @param xmin defines the minimum value on X axis
  33926. * @param zmin defines the minimum value on Z axis
  33927. * @param xmax defines the maximum value on X axis
  33928. * @param zmax defines the maximum value on Z axis
  33929. * @param subdivisions defines the subdivisions to apply to the ground (number of subdivisions (tiles) on the height and the width of the map)
  33930. * @param precision defines the precision to use when computing the tiles
  33931. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  33932. * @param mesh defines the hosting mesh (can be null)
  33933. */
  33934. function TiledGroundGeometry(id, scene,
  33935. /**
  33936. * Defines the minimum value on X axis
  33937. */
  33938. xmin,
  33939. /**
  33940. * Defines the minimum value on Z axis
  33941. */
  33942. zmin,
  33943. /**
  33944. * Defines the maximum value on X axis
  33945. */
  33946. xmax,
  33947. /**
  33948. * Defines the maximum value on Z axis
  33949. */
  33950. zmax,
  33951. /**
  33952. * Defines the subdivisions to apply to the ground
  33953. */
  33954. subdivisions,
  33955. /**
  33956. * Defines the precision to use when computing the tiles
  33957. */
  33958. precision, canBeRegenerated, mesh) {
  33959. if (mesh === void 0) { mesh = null; }
  33960. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  33961. _this.xmin = xmin;
  33962. _this.zmin = zmin;
  33963. _this.xmax = xmax;
  33964. _this.zmax = zmax;
  33965. _this.subdivisions = subdivisions;
  33966. _this.precision = precision;
  33967. return _this;
  33968. }
  33969. TiledGroundGeometry.prototype._regenerateVertexData = function () {
  33970. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  33971. };
  33972. TiledGroundGeometry.prototype.copy = function (id) {
  33973. return new TiledGroundGeometry(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  33974. };
  33975. return TiledGroundGeometry;
  33976. }(_PrimitiveGeometry));
  33977. BABYLON.TiledGroundGeometry = TiledGroundGeometry;
  33978. /**
  33979. * Creates a plane geometry
  33980. * @description see http://doc.babylonjs.com/how_to/set_shapes#plane
  33981. */
  33982. var PlaneGeometry = /** @class */ (function (_super) {
  33983. __extends(PlaneGeometry, _super);
  33984. /**
  33985. * Creates a plane geometry
  33986. * @param id defines the unique ID of the geometry
  33987. * @param scene defines the hosting scene
  33988. * @param size defines the size of the plane (width === height)
  33989. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  33990. * @param mesh defines the hosting mesh (can be null)
  33991. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  33992. */
  33993. function PlaneGeometry(id, scene,
  33994. /**
  33995. * Defines the size of the plane (width === height)
  33996. */
  33997. size, canBeRegenerated, mesh,
  33998. /**
  33999. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  34000. */
  34001. side) {
  34002. if (mesh === void 0) { mesh = null; }
  34003. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  34004. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  34005. _this.size = size;
  34006. _this.side = side;
  34007. return _this;
  34008. }
  34009. PlaneGeometry.prototype._regenerateVertexData = function () {
  34010. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  34011. };
  34012. PlaneGeometry.prototype.copy = function (id) {
  34013. return new PlaneGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  34014. };
  34015. PlaneGeometry.prototype.serialize = function () {
  34016. var serializationObject = _super.prototype.serialize.call(this);
  34017. serializationObject.size = this.size;
  34018. return serializationObject;
  34019. };
  34020. PlaneGeometry.Parse = function (parsedPlane, scene) {
  34021. if (scene.getGeometryByID(parsedPlane.id)) {
  34022. return null; // null since geometry could be something else than a ground...
  34023. }
  34024. var plane = new PlaneGeometry(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  34025. if (BABYLON.Tags) {
  34026. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  34027. }
  34028. scene.pushGeometry(plane, true);
  34029. return plane;
  34030. };
  34031. return PlaneGeometry;
  34032. }(_PrimitiveGeometry));
  34033. BABYLON.PlaneGeometry = PlaneGeometry;
  34034. /**
  34035. * Creates a torus knot geometry
  34036. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus-knot
  34037. */
  34038. var TorusKnotGeometry = /** @class */ (function (_super) {
  34039. __extends(TorusKnotGeometry, _super);
  34040. /**
  34041. * Creates a torus knot geometry
  34042. * @param id defines the unique ID of the geometry
  34043. * @param scene defines the hosting scene
  34044. * @param radius defines the radius of the torus knot
  34045. * @param tube defines the thickness of the torus knot tube
  34046. * @param radialSegments defines the number of radial segments
  34047. * @param tubularSegments defines the number of tubular segments
  34048. * @param p defines the first number of windings
  34049. * @param q defines the second number of windings
  34050. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  34051. * @param mesh defines the hosting mesh (can be null)
  34052. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  34053. */
  34054. function TorusKnotGeometry(id, scene,
  34055. /**
  34056. * Defines the radius of the torus knot
  34057. */
  34058. radius,
  34059. /**
  34060. * Defines the thickness of the torus knot tube
  34061. */
  34062. tube,
  34063. /**
  34064. * Defines the number of radial segments
  34065. */
  34066. radialSegments,
  34067. /**
  34068. * Defines the number of tubular segments
  34069. */
  34070. tubularSegments,
  34071. /**
  34072. * Defines the first number of windings
  34073. */
  34074. p,
  34075. /**
  34076. * Defines the second number of windings
  34077. */
  34078. q, canBeRegenerated, mesh,
  34079. /**
  34080. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  34081. */
  34082. side) {
  34083. if (mesh === void 0) { mesh = null; }
  34084. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  34085. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  34086. _this.radius = radius;
  34087. _this.tube = tube;
  34088. _this.radialSegments = radialSegments;
  34089. _this.tubularSegments = tubularSegments;
  34090. _this.p = p;
  34091. _this.q = q;
  34092. _this.side = side;
  34093. return _this;
  34094. }
  34095. TorusKnotGeometry.prototype._regenerateVertexData = function () {
  34096. 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 });
  34097. };
  34098. TorusKnotGeometry.prototype.copy = function (id) {
  34099. return new TorusKnotGeometry(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  34100. };
  34101. TorusKnotGeometry.prototype.serialize = function () {
  34102. var serializationObject = _super.prototype.serialize.call(this);
  34103. serializationObject.radius = this.radius;
  34104. serializationObject.tube = this.tube;
  34105. serializationObject.radialSegments = this.radialSegments;
  34106. serializationObject.tubularSegments = this.tubularSegments;
  34107. serializationObject.p = this.p;
  34108. serializationObject.q = this.q;
  34109. return serializationObject;
  34110. };
  34111. ;
  34112. TorusKnotGeometry.Parse = function (parsedTorusKnot, scene) {
  34113. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  34114. return null; // null since geometry could be something else than a ground...
  34115. }
  34116. var torusKnot = new TorusKnotGeometry(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  34117. if (BABYLON.Tags) {
  34118. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  34119. }
  34120. scene.pushGeometry(torusKnot, true);
  34121. return torusKnot;
  34122. };
  34123. return TorusKnotGeometry;
  34124. }(_PrimitiveGeometry));
  34125. BABYLON.TorusKnotGeometry = TorusKnotGeometry;
  34126. //}
  34127. })(BABYLON || (BABYLON = {}));
  34128. //# sourceMappingURL=babylon.geometry.js.map
  34129. var BABYLON;
  34130. (function (BABYLON) {
  34131. var PostProcessManager = /** @class */ (function () {
  34132. function PostProcessManager(scene) {
  34133. this._vertexBuffers = {};
  34134. this._scene = scene;
  34135. }
  34136. PostProcessManager.prototype._prepareBuffers = function () {
  34137. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  34138. return;
  34139. }
  34140. // VBO
  34141. var vertices = [];
  34142. vertices.push(1, 1);
  34143. vertices.push(-1, 1);
  34144. vertices.push(-1, -1);
  34145. vertices.push(1, -1);
  34146. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  34147. this._buildIndexBuffer();
  34148. };
  34149. PostProcessManager.prototype._buildIndexBuffer = function () {
  34150. // Indices
  34151. var indices = [];
  34152. indices.push(0);
  34153. indices.push(1);
  34154. indices.push(2);
  34155. indices.push(0);
  34156. indices.push(2);
  34157. indices.push(3);
  34158. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  34159. };
  34160. PostProcessManager.prototype._rebuild = function () {
  34161. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  34162. if (!vb) {
  34163. return;
  34164. }
  34165. vb._rebuild();
  34166. this._buildIndexBuffer();
  34167. };
  34168. // Methods
  34169. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  34170. if (sourceTexture === void 0) { sourceTexture = null; }
  34171. if (postProcesses === void 0) { postProcesses = null; }
  34172. var camera = this._scene.activeCamera;
  34173. if (!camera) {
  34174. return false;
  34175. }
  34176. var postProcesses = postProcesses || camera._postProcesses;
  34177. if (!postProcesses || postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  34178. return false;
  34179. }
  34180. postProcesses[0].activate(camera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  34181. return true;
  34182. };
  34183. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture, forceFullscreenViewport) {
  34184. if (targetTexture === void 0) { targetTexture = null; }
  34185. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  34186. var engine = this._scene.getEngine();
  34187. for (var index = 0; index < postProcesses.length; index++) {
  34188. if (index < postProcesses.length - 1) {
  34189. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  34190. }
  34191. else {
  34192. if (targetTexture) {
  34193. engine.bindFramebuffer(targetTexture, 0, undefined, undefined, forceFullscreenViewport);
  34194. }
  34195. else {
  34196. engine.restoreDefaultFramebuffer();
  34197. }
  34198. }
  34199. var pp = postProcesses[index];
  34200. var effect = pp.apply();
  34201. if (effect) {
  34202. pp.onBeforeRenderObservable.notifyObservers(effect);
  34203. // VBOs
  34204. this._prepareBuffers();
  34205. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  34206. // Draw order
  34207. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  34208. pp.onAfterRenderObservable.notifyObservers(effect);
  34209. }
  34210. }
  34211. // Restore depth buffer
  34212. engine.setDepthBuffer(true);
  34213. engine.setDepthWrite(true);
  34214. };
  34215. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses, forceFullscreenViewport) {
  34216. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  34217. var camera = this._scene.activeCamera;
  34218. if (!camera) {
  34219. return;
  34220. }
  34221. postProcesses = postProcesses || camera._postProcesses;
  34222. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  34223. return;
  34224. }
  34225. var engine = this._scene.getEngine();
  34226. for (var index = 0, len = postProcesses.length; index < len; index++) {
  34227. if (index < len - 1) {
  34228. postProcesses[index + 1].activate(camera, targetTexture);
  34229. }
  34230. else {
  34231. if (targetTexture) {
  34232. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport);
  34233. }
  34234. else {
  34235. engine.restoreDefaultFramebuffer();
  34236. }
  34237. }
  34238. if (doNotPresent) {
  34239. break;
  34240. }
  34241. var pp = postProcesses[index];
  34242. var effect = pp.apply();
  34243. if (effect) {
  34244. pp.onBeforeRenderObservable.notifyObservers(effect);
  34245. // VBOs
  34246. this._prepareBuffers();
  34247. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  34248. // Draw order
  34249. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  34250. pp.onAfterRenderObservable.notifyObservers(effect);
  34251. }
  34252. }
  34253. // Restore states
  34254. engine.setDepthBuffer(true);
  34255. engine.setDepthWrite(true);
  34256. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  34257. };
  34258. PostProcessManager.prototype.dispose = function () {
  34259. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  34260. if (buffer) {
  34261. buffer.dispose();
  34262. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  34263. }
  34264. if (this._indexBuffer) {
  34265. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  34266. this._indexBuffer = null;
  34267. }
  34268. };
  34269. return PostProcessManager;
  34270. }());
  34271. BABYLON.PostProcessManager = PostProcessManager;
  34272. })(BABYLON || (BABYLON = {}));
  34273. //# sourceMappingURL=babylon.postProcessManager.js.map
  34274. var BABYLON;
  34275. (function (BABYLON) {
  34276. /**
  34277. * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
  34278. */
  34279. var PerformanceMonitor = /** @class */ (function () {
  34280. /**
  34281. * constructor
  34282. * @param frameSampleSize The number of samples required to saturate the sliding window
  34283. */
  34284. function PerformanceMonitor(frameSampleSize) {
  34285. if (frameSampleSize === void 0) { frameSampleSize = 30; }
  34286. this._enabled = true;
  34287. this._rollingFrameTime = new RollingAverage(frameSampleSize);
  34288. }
  34289. /**
  34290. * Samples current frame
  34291. * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
  34292. */
  34293. PerformanceMonitor.prototype.sampleFrame = function (timeMs) {
  34294. if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }
  34295. if (!this._enabled)
  34296. return;
  34297. if (this._lastFrameTimeMs != null) {
  34298. var dt = timeMs - this._lastFrameTimeMs;
  34299. this._rollingFrameTime.add(dt);
  34300. }
  34301. this._lastFrameTimeMs = timeMs;
  34302. };
  34303. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTime", {
  34304. /**
  34305. * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  34306. * @return Average frame time in milliseconds
  34307. */
  34308. get: function () {
  34309. return this._rollingFrameTime.average;
  34310. },
  34311. enumerable: true,
  34312. configurable: true
  34313. });
  34314. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTimeVariance", {
  34315. /**
  34316. * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  34317. * @return Frame time variance in milliseconds squared
  34318. */
  34319. get: function () {
  34320. return this._rollingFrameTime.variance;
  34321. },
  34322. enumerable: true,
  34323. configurable: true
  34324. });
  34325. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFrameTime", {
  34326. /**
  34327. * Returns the frame time of the most recent frame
  34328. * @return Frame time in milliseconds
  34329. */
  34330. get: function () {
  34331. return this._rollingFrameTime.history(0);
  34332. },
  34333. enumerable: true,
  34334. configurable: true
  34335. });
  34336. Object.defineProperty(PerformanceMonitor.prototype, "averageFPS", {
  34337. /**
  34338. * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
  34339. * @return Framerate in frames per second
  34340. */
  34341. get: function () {
  34342. return 1000.0 / this._rollingFrameTime.average;
  34343. },
  34344. enumerable: true,
  34345. configurable: true
  34346. });
  34347. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFPS", {
  34348. /**
  34349. * Returns the average framerate in frames per second using the most recent frame time
  34350. * @return Framerate in frames per second
  34351. */
  34352. get: function () {
  34353. var history = this._rollingFrameTime.history(0);
  34354. if (history === 0) {
  34355. return 0;
  34356. }
  34357. return 1000.0 / history;
  34358. },
  34359. enumerable: true,
  34360. configurable: true
  34361. });
  34362. Object.defineProperty(PerformanceMonitor.prototype, "isSaturated", {
  34363. /**
  34364. * Returns true if enough samples have been taken to completely fill the sliding window
  34365. * @return true if saturated
  34366. */
  34367. get: function () {
  34368. return this._rollingFrameTime.isSaturated();
  34369. },
  34370. enumerable: true,
  34371. configurable: true
  34372. });
  34373. /**
  34374. * Enables contributions to the sliding window sample set
  34375. */
  34376. PerformanceMonitor.prototype.enable = function () {
  34377. this._enabled = true;
  34378. };
  34379. /**
  34380. * Disables contributions to the sliding window sample set
  34381. * Samples will not be interpolated over the disabled period
  34382. */
  34383. PerformanceMonitor.prototype.disable = function () {
  34384. this._enabled = false;
  34385. //clear last sample to avoid interpolating over the disabled period when next enabled
  34386. this._lastFrameTimeMs = null;
  34387. };
  34388. Object.defineProperty(PerformanceMonitor.prototype, "isEnabled", {
  34389. /**
  34390. * Returns true if sampling is enabled
  34391. * @return true if enabled
  34392. */
  34393. get: function () {
  34394. return this._enabled;
  34395. },
  34396. enumerable: true,
  34397. configurable: true
  34398. });
  34399. /**
  34400. * Resets performance monitor
  34401. */
  34402. PerformanceMonitor.prototype.reset = function () {
  34403. //clear last sample to avoid interpolating over the disabled period when next enabled
  34404. this._lastFrameTimeMs = null;
  34405. //wipe record
  34406. this._rollingFrameTime.reset();
  34407. };
  34408. return PerformanceMonitor;
  34409. }());
  34410. BABYLON.PerformanceMonitor = PerformanceMonitor;
  34411. /**
  34412. * RollingAverage
  34413. *
  34414. * Utility to efficiently compute the rolling average and variance over a sliding window of samples
  34415. */
  34416. var RollingAverage = /** @class */ (function () {
  34417. /**
  34418. * constructor
  34419. * @param length The number of samples required to saturate the sliding window
  34420. */
  34421. function RollingAverage(length) {
  34422. this._samples = new Array(length);
  34423. this.reset();
  34424. }
  34425. /**
  34426. * Adds a sample to the sample set
  34427. * @param v The sample value
  34428. */
  34429. RollingAverage.prototype.add = function (v) {
  34430. //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  34431. var delta;
  34432. //we need to check if we've already wrapped round
  34433. if (this.isSaturated()) {
  34434. //remove bottom of stack from mean
  34435. var bottomValue = this._samples[this._pos];
  34436. delta = bottomValue - this.average;
  34437. this.average -= delta / (this._sampleCount - 1);
  34438. this._m2 -= delta * (bottomValue - this.average);
  34439. }
  34440. else {
  34441. this._sampleCount++;
  34442. }
  34443. //add new value to mean
  34444. delta = v - this.average;
  34445. this.average += delta / (this._sampleCount);
  34446. this._m2 += delta * (v - this.average);
  34447. //set the new variance
  34448. this.variance = this._m2 / (this._sampleCount - 1);
  34449. this._samples[this._pos] = v;
  34450. this._pos++;
  34451. this._pos %= this._samples.length; //positive wrap around
  34452. };
  34453. /**
  34454. * Returns previously added values or null if outside of history or outside the sliding window domain
  34455. * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
  34456. * @return Value previously recorded with add() or null if outside of range
  34457. */
  34458. RollingAverage.prototype.history = function (i) {
  34459. if ((i >= this._sampleCount) || (i >= this._samples.length)) {
  34460. return 0;
  34461. }
  34462. var i0 = this._wrapPosition(this._pos - 1.0);
  34463. return this._samples[this._wrapPosition(i0 - i)];
  34464. };
  34465. /**
  34466. * Returns true if enough samples have been taken to completely fill the sliding window
  34467. * @return true if sample-set saturated
  34468. */
  34469. RollingAverage.prototype.isSaturated = function () {
  34470. return this._sampleCount >= this._samples.length;
  34471. };
  34472. /**
  34473. * Resets the rolling average (equivalent to 0 samples taken so far)
  34474. */
  34475. RollingAverage.prototype.reset = function () {
  34476. this.average = 0;
  34477. this.variance = 0;
  34478. this._sampleCount = 0;
  34479. this._pos = 0;
  34480. this._m2 = 0;
  34481. };
  34482. /**
  34483. * Wraps a value around the sample range boundaries
  34484. * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
  34485. * @return Wrapped position in sample range
  34486. */
  34487. RollingAverage.prototype._wrapPosition = function (i) {
  34488. var max = this._samples.length;
  34489. return ((i % max) + max) % max;
  34490. };
  34491. return RollingAverage;
  34492. }());
  34493. BABYLON.RollingAverage = RollingAverage;
  34494. })(BABYLON || (BABYLON = {}));
  34495. //# sourceMappingURL=babylon.performanceMonitor.js.map
  34496. var BABYLON;
  34497. (function (BABYLON) {
  34498. /**
  34499. * This groups together the common properties used for image processing either in direct forward pass
  34500. * or through post processing effect depending on the use of the image processing pipeline in your scene
  34501. * or not.
  34502. */
  34503. var ImageProcessingConfiguration = /** @class */ (function () {
  34504. function ImageProcessingConfiguration() {
  34505. /**
  34506. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  34507. */
  34508. this.colorCurves = new BABYLON.ColorCurves();
  34509. this._colorCurvesEnabled = false;
  34510. this._colorGradingEnabled = false;
  34511. this._colorGradingWithGreenDepth = true;
  34512. this._colorGradingBGR = true;
  34513. this._exposure = 1.0;
  34514. this._toneMappingEnabled = false;
  34515. this._contrast = 1.0;
  34516. /**
  34517. * Vignette stretch size.
  34518. */
  34519. this.vignetteStretch = 0;
  34520. /**
  34521. * Vignette centre X Offset.
  34522. */
  34523. this.vignetteCentreX = 0;
  34524. /**
  34525. * Vignette centre Y Offset.
  34526. */
  34527. this.vignetteCentreY = 0;
  34528. /**
  34529. * Vignette weight or intensity of the vignette effect.
  34530. */
  34531. this.vignetteWeight = 1.5;
  34532. /**
  34533. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  34534. * if vignetteEnabled is set to true.
  34535. */
  34536. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  34537. /**
  34538. * Camera field of view used by the Vignette effect.
  34539. */
  34540. this.vignetteCameraFov = 0.5;
  34541. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  34542. this._vignetteEnabled = false;
  34543. this._applyByPostProcess = false;
  34544. this._isEnabled = true;
  34545. /**
  34546. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  34547. * @type {BABYLON.Observable}
  34548. */
  34549. this.onUpdateParameters = new BABYLON.Observable();
  34550. }
  34551. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  34552. /**
  34553. * Gets wether the color curves effect is enabled.
  34554. */
  34555. get: function () {
  34556. return this._colorCurvesEnabled;
  34557. },
  34558. /**
  34559. * Sets wether the color curves effect is enabled.
  34560. */
  34561. set: function (value) {
  34562. if (this._colorCurvesEnabled === value) {
  34563. return;
  34564. }
  34565. this._colorCurvesEnabled = value;
  34566. this._updateParameters();
  34567. },
  34568. enumerable: true,
  34569. configurable: true
  34570. });
  34571. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  34572. /**
  34573. * Gets wether the color grading effect is enabled.
  34574. */
  34575. get: function () {
  34576. return this._colorGradingEnabled;
  34577. },
  34578. /**
  34579. * Sets wether the color grading effect is enabled.
  34580. */
  34581. set: function (value) {
  34582. if (this._colorGradingEnabled === value) {
  34583. return;
  34584. }
  34585. this._colorGradingEnabled = value;
  34586. this._updateParameters();
  34587. },
  34588. enumerable: true,
  34589. configurable: true
  34590. });
  34591. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  34592. /**
  34593. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  34594. */
  34595. get: function () {
  34596. return this._colorGradingWithGreenDepth;
  34597. },
  34598. /**
  34599. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  34600. */
  34601. set: function (value) {
  34602. if (this._colorGradingWithGreenDepth === value) {
  34603. return;
  34604. }
  34605. this._colorGradingWithGreenDepth = value;
  34606. this._updateParameters();
  34607. },
  34608. enumerable: true,
  34609. configurable: true
  34610. });
  34611. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  34612. /**
  34613. * Gets wether the color grading texture contains BGR values.
  34614. */
  34615. get: function () {
  34616. return this._colorGradingBGR;
  34617. },
  34618. /**
  34619. * Sets wether the color grading texture contains BGR values.
  34620. */
  34621. set: function (value) {
  34622. if (this._colorGradingBGR === value) {
  34623. return;
  34624. }
  34625. this._colorGradingBGR = value;
  34626. this._updateParameters();
  34627. },
  34628. enumerable: true,
  34629. configurable: true
  34630. });
  34631. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  34632. /**
  34633. * Gets the Exposure used in the effect.
  34634. */
  34635. get: function () {
  34636. return this._exposure;
  34637. },
  34638. /**
  34639. * Sets the Exposure used in the effect.
  34640. */
  34641. set: function (value) {
  34642. if (this._exposure === value) {
  34643. return;
  34644. }
  34645. this._exposure = value;
  34646. this._updateParameters();
  34647. },
  34648. enumerable: true,
  34649. configurable: true
  34650. });
  34651. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  34652. /**
  34653. * Gets wether the tone mapping effect is enabled.
  34654. */
  34655. get: function () {
  34656. return this._toneMappingEnabled;
  34657. },
  34658. /**
  34659. * Sets wether the tone mapping effect is enabled.
  34660. */
  34661. set: function (value) {
  34662. if (this._toneMappingEnabled === value) {
  34663. return;
  34664. }
  34665. this._toneMappingEnabled = value;
  34666. this._updateParameters();
  34667. },
  34668. enumerable: true,
  34669. configurable: true
  34670. });
  34671. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  34672. /**
  34673. * Gets the contrast used in the effect.
  34674. */
  34675. get: function () {
  34676. return this._contrast;
  34677. },
  34678. /**
  34679. * Sets the contrast used in the effect.
  34680. */
  34681. set: function (value) {
  34682. if (this._contrast === value) {
  34683. return;
  34684. }
  34685. this._contrast = value;
  34686. this._updateParameters();
  34687. },
  34688. enumerable: true,
  34689. configurable: true
  34690. });
  34691. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  34692. /**
  34693. * Gets the vignette blend mode allowing different kind of effect.
  34694. */
  34695. get: function () {
  34696. return this._vignetteBlendMode;
  34697. },
  34698. /**
  34699. * Sets the vignette blend mode allowing different kind of effect.
  34700. */
  34701. set: function (value) {
  34702. if (this._vignetteBlendMode === value) {
  34703. return;
  34704. }
  34705. this._vignetteBlendMode = value;
  34706. this._updateParameters();
  34707. },
  34708. enumerable: true,
  34709. configurable: true
  34710. });
  34711. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  34712. /**
  34713. * Gets wether the vignette effect is enabled.
  34714. */
  34715. get: function () {
  34716. return this._vignetteEnabled;
  34717. },
  34718. /**
  34719. * Sets wether the vignette effect is enabled.
  34720. */
  34721. set: function (value) {
  34722. if (this._vignetteEnabled === value) {
  34723. return;
  34724. }
  34725. this._vignetteEnabled = value;
  34726. this._updateParameters();
  34727. },
  34728. enumerable: true,
  34729. configurable: true
  34730. });
  34731. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  34732. /**
  34733. * Gets wether the image processing is applied through a post process or not.
  34734. */
  34735. get: function () {
  34736. return this._applyByPostProcess;
  34737. },
  34738. /**
  34739. * Sets wether the image processing is applied through a post process or not.
  34740. */
  34741. set: function (value) {
  34742. if (this._applyByPostProcess === value) {
  34743. return;
  34744. }
  34745. this._applyByPostProcess = value;
  34746. this._updateParameters();
  34747. },
  34748. enumerable: true,
  34749. configurable: true
  34750. });
  34751. Object.defineProperty(ImageProcessingConfiguration.prototype, "isEnabled", {
  34752. /**
  34753. * Gets wether the image processing is enabled or not.
  34754. */
  34755. get: function () {
  34756. return this._isEnabled;
  34757. },
  34758. /**
  34759. * Sets wether the image processing is enabled or not.
  34760. */
  34761. set: function (value) {
  34762. if (this._isEnabled === value) {
  34763. return;
  34764. }
  34765. this._isEnabled = value;
  34766. this._updateParameters();
  34767. },
  34768. enumerable: true,
  34769. configurable: true
  34770. });
  34771. /**
  34772. * Method called each time the image processing information changes requires to recompile the effect.
  34773. */
  34774. ImageProcessingConfiguration.prototype._updateParameters = function () {
  34775. this.onUpdateParameters.notifyObservers(this);
  34776. };
  34777. ImageProcessingConfiguration.prototype.getClassName = function () {
  34778. return "ImageProcessingConfiguration";
  34779. };
  34780. /**
  34781. * Prepare the list of uniforms associated with the Image Processing effects.
  34782. * @param uniformsList The list of uniforms used in the effect
  34783. * @param defines the list of defines currently in use
  34784. */
  34785. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  34786. if (defines.EXPOSURE) {
  34787. uniforms.push("exposureLinear");
  34788. }
  34789. if (defines.CONTRAST) {
  34790. uniforms.push("contrast");
  34791. }
  34792. if (defines.COLORGRADING) {
  34793. uniforms.push("colorTransformSettings");
  34794. }
  34795. if (defines.VIGNETTE) {
  34796. uniforms.push("vInverseScreenSize");
  34797. uniforms.push("vignetteSettings1");
  34798. uniforms.push("vignetteSettings2");
  34799. }
  34800. if (defines.COLORCURVES) {
  34801. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  34802. }
  34803. };
  34804. /**
  34805. * Prepare the list of samplers associated with the Image Processing effects.
  34806. * @param uniformsList The list of uniforms used in the effect
  34807. * @param defines the list of defines currently in use
  34808. */
  34809. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  34810. if (defines.COLORGRADING) {
  34811. samplersList.push("txColorTransform");
  34812. }
  34813. };
  34814. /**
  34815. * Prepare the list of defines associated to the shader.
  34816. * @param defines the list of defines to complete
  34817. */
  34818. ImageProcessingConfiguration.prototype.prepareDefines = function (defines, forPostProcess) {
  34819. if (forPostProcess === void 0) { forPostProcess = false; }
  34820. if (forPostProcess !== this.applyByPostProcess || !this._isEnabled) {
  34821. defines.VIGNETTE = false;
  34822. defines.TONEMAPPING = false;
  34823. defines.CONTRAST = false;
  34824. defines.EXPOSURE = false;
  34825. defines.COLORCURVES = false;
  34826. defines.COLORGRADING = false;
  34827. defines.COLORGRADING3D = false;
  34828. defines.IMAGEPROCESSING = false;
  34829. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess && this._isEnabled;
  34830. return;
  34831. }
  34832. defines.VIGNETTE = this.vignetteEnabled;
  34833. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  34834. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  34835. defines.TONEMAPPING = this.toneMappingEnabled;
  34836. defines.CONTRAST = (this.contrast !== 1.0);
  34837. defines.EXPOSURE = (this.exposure !== 1.0);
  34838. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  34839. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  34840. if (defines.COLORGRADING) {
  34841. defines.COLORGRADING3D = this.colorGradingTexture.is3D;
  34842. }
  34843. else {
  34844. defines.COLORGRADING3D = false;
  34845. }
  34846. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  34847. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  34848. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  34849. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING;
  34850. };
  34851. /**
  34852. * Returns true if all the image processing information are ready.
  34853. */
  34854. ImageProcessingConfiguration.prototype.isReady = function () {
  34855. // Color Grading texure can not be none blocking.
  34856. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  34857. };
  34858. /**
  34859. * Binds the image processing to the shader.
  34860. * @param effect The effect to bind to
  34861. */
  34862. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  34863. if (aspectRatio === void 0) { aspectRatio = 1; }
  34864. // Color Curves
  34865. if (this._colorCurvesEnabled && this.colorCurves) {
  34866. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  34867. }
  34868. // Vignette
  34869. if (this._vignetteEnabled) {
  34870. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  34871. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  34872. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  34873. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  34874. var vignetteScaleX = vignetteScaleY * aspectRatio;
  34875. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  34876. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  34877. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  34878. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  34879. var vignettePower = -2.0 * this.vignetteWeight;
  34880. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  34881. }
  34882. // Exposure
  34883. effect.setFloat("exposureLinear", this.exposure);
  34884. // Contrast
  34885. effect.setFloat("contrast", this.contrast);
  34886. // Color transform settings
  34887. if (this.colorGradingTexture) {
  34888. effect.setTexture("txColorTransform", this.colorGradingTexture);
  34889. var textureSize = this.colorGradingTexture.getSize().height;
  34890. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  34891. 0.5 / textureSize, // textureOffset
  34892. textureSize, // textureSize
  34893. this.colorGradingTexture.level // weight
  34894. );
  34895. }
  34896. };
  34897. /**
  34898. * Clones the current image processing instance.
  34899. * @return The cloned image processing
  34900. */
  34901. ImageProcessingConfiguration.prototype.clone = function () {
  34902. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  34903. };
  34904. /**
  34905. * Serializes the current image processing instance to a json representation.
  34906. * @return a JSON representation
  34907. */
  34908. ImageProcessingConfiguration.prototype.serialize = function () {
  34909. return BABYLON.SerializationHelper.Serialize(this);
  34910. };
  34911. /**
  34912. * Parses the image processing from a json representation.
  34913. * @param source the JSON source to parse
  34914. * @return The parsed image processing
  34915. */
  34916. ImageProcessingConfiguration.Parse = function (source) {
  34917. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  34918. };
  34919. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  34920. /**
  34921. * Used to apply the vignette as a mix with the pixel color.
  34922. */
  34923. get: function () {
  34924. return this._VIGNETTEMODE_MULTIPLY;
  34925. },
  34926. enumerable: true,
  34927. configurable: true
  34928. });
  34929. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  34930. /**
  34931. * Used to apply the vignette as a replacement of the pixel color.
  34932. */
  34933. get: function () {
  34934. return this._VIGNETTEMODE_OPAQUE;
  34935. },
  34936. enumerable: true,
  34937. configurable: true
  34938. });
  34939. // Static constants associated to the image processing.
  34940. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  34941. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  34942. __decorate([
  34943. BABYLON.serializeAsColorCurves()
  34944. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  34945. __decorate([
  34946. BABYLON.serialize()
  34947. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  34948. __decorate([
  34949. BABYLON.serializeAsTexture()
  34950. ], ImageProcessingConfiguration.prototype, "colorGradingTexture", void 0);
  34951. __decorate([
  34952. BABYLON.serialize()
  34953. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  34954. __decorate([
  34955. BABYLON.serialize()
  34956. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  34957. __decorate([
  34958. BABYLON.serialize()
  34959. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  34960. __decorate([
  34961. BABYLON.serialize()
  34962. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  34963. __decorate([
  34964. BABYLON.serialize()
  34965. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  34966. __decorate([
  34967. BABYLON.serialize()
  34968. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  34969. __decorate([
  34970. BABYLON.serialize()
  34971. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  34972. __decorate([
  34973. BABYLON.serialize()
  34974. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  34975. __decorate([
  34976. BABYLON.serialize()
  34977. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  34978. __decorate([
  34979. BABYLON.serialize()
  34980. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  34981. __decorate([
  34982. BABYLON.serializeAsColor4()
  34983. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  34984. __decorate([
  34985. BABYLON.serialize()
  34986. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  34987. __decorate([
  34988. BABYLON.serialize()
  34989. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  34990. __decorate([
  34991. BABYLON.serialize()
  34992. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  34993. __decorate([
  34994. BABYLON.serialize()
  34995. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  34996. __decorate([
  34997. BABYLON.serialize()
  34998. ], ImageProcessingConfiguration.prototype, "_isEnabled", void 0);
  34999. return ImageProcessingConfiguration;
  35000. }());
  35001. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  35002. })(BABYLON || (BABYLON = {}));
  35003. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  35004. var BABYLON;
  35005. (function (BABYLON) {
  35006. /**
  35007. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  35008. * It can help converting any input color in a desired output one. This can then be used to create effects
  35009. * from sepia, black and white to sixties or futuristic rendering...
  35010. *
  35011. * The only supported format is currently 3dl.
  35012. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  35013. */
  35014. var ColorGradingTexture = /** @class */ (function (_super) {
  35015. __extends(ColorGradingTexture, _super);
  35016. /**
  35017. * Instantiates a ColorGradingTexture from the following parameters.
  35018. *
  35019. * @param url The location of the color gradind data (currently only supporting 3dl)
  35020. * @param scene The scene the texture will be used in
  35021. */
  35022. function ColorGradingTexture(url, scene) {
  35023. var _this = _super.call(this, scene) || this;
  35024. if (!url) {
  35025. return _this;
  35026. }
  35027. _this._engine = scene.getEngine();
  35028. _this._textureMatrix = BABYLON.Matrix.Identity();
  35029. _this.name = url;
  35030. _this.url = url;
  35031. _this.hasAlpha = false;
  35032. _this.isCube = false;
  35033. _this.is3D = _this._engine.webGLVersion > 1;
  35034. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  35035. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  35036. _this.wrapR = BABYLON.Texture.CLAMP_ADDRESSMODE;
  35037. _this.anisotropicFilteringLevel = 1;
  35038. _this._texture = _this._getFromCache(url, true);
  35039. if (!_this._texture) {
  35040. if (!scene.useDelayedTextureLoading) {
  35041. _this.loadTexture();
  35042. }
  35043. else {
  35044. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  35045. }
  35046. }
  35047. return _this;
  35048. }
  35049. /**
  35050. * Returns the texture matrix used in most of the material.
  35051. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  35052. */
  35053. ColorGradingTexture.prototype.getTextureMatrix = function () {
  35054. return this._textureMatrix;
  35055. };
  35056. /**
  35057. * Occurs when the file being loaded is a .3dl LUT file.
  35058. */
  35059. ColorGradingTexture.prototype.load3dlTexture = function () {
  35060. var engine = this._engine;
  35061. var texture;
  35062. if (engine.webGLVersion === 1) {
  35063. texture = engine.createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  35064. }
  35065. else {
  35066. texture = engine.createRawTexture3D(null, 1, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  35067. }
  35068. this._texture = texture;
  35069. var callback = function (text) {
  35070. if (typeof text !== "string") {
  35071. return;
  35072. }
  35073. var data = null;
  35074. var tempData = null;
  35075. var line;
  35076. var lines = text.split('\n');
  35077. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  35078. var maxColor = 0;
  35079. for (var i = 0; i < lines.length; i++) {
  35080. line = lines[i];
  35081. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  35082. continue;
  35083. if (line.indexOf('#') === 0)
  35084. continue;
  35085. var words = line.split(" ");
  35086. if (size === 0) {
  35087. // Number of space + one
  35088. size = words.length;
  35089. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  35090. tempData = new Float32Array(size * size * size * 4);
  35091. continue;
  35092. }
  35093. if (size != 0) {
  35094. var r = Math.max(parseInt(words[0]), 0);
  35095. var g = Math.max(parseInt(words[1]), 0);
  35096. var b = Math.max(parseInt(words[2]), 0);
  35097. maxColor = Math.max(r, maxColor);
  35098. maxColor = Math.max(g, maxColor);
  35099. maxColor = Math.max(b, maxColor);
  35100. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  35101. if (tempData) {
  35102. tempData[pixelStorageIndex + 0] = r;
  35103. tempData[pixelStorageIndex + 1] = g;
  35104. tempData[pixelStorageIndex + 2] = b;
  35105. }
  35106. pixelIndexSlice++;
  35107. if (pixelIndexSlice % size == 0) {
  35108. pixelIndexH++;
  35109. pixelIndexSlice = 0;
  35110. if (pixelIndexH % size == 0) {
  35111. pixelIndexW++;
  35112. pixelIndexH = 0;
  35113. }
  35114. }
  35115. }
  35116. }
  35117. if (tempData && data) {
  35118. for (var i = 0; i < tempData.length; i++) {
  35119. if (i > 0 && (i + 1) % 4 === 0) {
  35120. data[i] = 255;
  35121. }
  35122. else {
  35123. var value = tempData[i];
  35124. data[i] = (value / maxColor * 255);
  35125. }
  35126. }
  35127. }
  35128. if (texture.is3D) {
  35129. texture.updateSize(size, size, size);
  35130. engine.updateRawTexture3D(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  35131. }
  35132. else {
  35133. texture.updateSize(size * size, size);
  35134. engine.updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  35135. }
  35136. };
  35137. var scene = this.getScene();
  35138. if (scene) {
  35139. scene._loadFile(this.url, callback);
  35140. }
  35141. else {
  35142. this._engine._loadFile(this.url, callback);
  35143. }
  35144. return this._texture;
  35145. };
  35146. /**
  35147. * Starts the loading process of the texture.
  35148. */
  35149. ColorGradingTexture.prototype.loadTexture = function () {
  35150. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  35151. this.load3dlTexture();
  35152. }
  35153. };
  35154. /**
  35155. * Clones the color gradind texture.
  35156. */
  35157. ColorGradingTexture.prototype.clone = function () {
  35158. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  35159. // Base texture
  35160. newTexture.level = this.level;
  35161. return newTexture;
  35162. };
  35163. /**
  35164. * Called during delayed load for textures.
  35165. */
  35166. ColorGradingTexture.prototype.delayLoad = function () {
  35167. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  35168. return;
  35169. }
  35170. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  35171. this._texture = this._getFromCache(this.url, true);
  35172. if (!this._texture) {
  35173. this.loadTexture();
  35174. }
  35175. };
  35176. /**
  35177. * Parses a color grading texture serialized by Babylon.
  35178. * @param parsedTexture The texture information being parsedTexture
  35179. * @param scene The scene to load the texture in
  35180. * @param rootUrl The root url of the data assets to load
  35181. * @return A color gradind texture
  35182. */
  35183. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  35184. var texture = null;
  35185. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  35186. texture = new ColorGradingTexture(parsedTexture.name, scene);
  35187. texture.name = parsedTexture.name;
  35188. texture.level = parsedTexture.level;
  35189. }
  35190. return texture;
  35191. };
  35192. /**
  35193. * Serializes the LUT texture to json format.
  35194. */
  35195. ColorGradingTexture.prototype.serialize = function () {
  35196. if (!this.name) {
  35197. return null;
  35198. }
  35199. var serializationObject = {};
  35200. serializationObject.name = this.name;
  35201. serializationObject.level = this.level;
  35202. serializationObject.customType = "BABYLON.ColorGradingTexture";
  35203. return serializationObject;
  35204. };
  35205. /**
  35206. * Empty line regex stored for GC.
  35207. */
  35208. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  35209. return ColorGradingTexture;
  35210. }(BABYLON.BaseTexture));
  35211. BABYLON.ColorGradingTexture = ColorGradingTexture;
  35212. })(BABYLON || (BABYLON = {}));
  35213. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  35214. var BABYLON;
  35215. (function (BABYLON) {
  35216. /**
  35217. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  35218. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  35219. * 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;
  35220. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  35221. */
  35222. var ColorCurves = /** @class */ (function () {
  35223. function ColorCurves() {
  35224. this._dirty = true;
  35225. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  35226. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  35227. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  35228. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  35229. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  35230. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  35231. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  35232. this._globalHue = 30;
  35233. this._globalDensity = 0;
  35234. this._globalSaturation = 0;
  35235. this._globalExposure = 0;
  35236. this._highlightsHue = 30;
  35237. this._highlightsDensity = 0;
  35238. this._highlightsSaturation = 0;
  35239. this._highlightsExposure = 0;
  35240. this._midtonesHue = 30;
  35241. this._midtonesDensity = 0;
  35242. this._midtonesSaturation = 0;
  35243. this._midtonesExposure = 0;
  35244. this._shadowsHue = 30;
  35245. this._shadowsDensity = 0;
  35246. this._shadowsSaturation = 0;
  35247. this._shadowsExposure = 0;
  35248. }
  35249. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  35250. /**
  35251. * Gets the global Hue value.
  35252. * 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).
  35253. */
  35254. get: function () {
  35255. return this._globalHue;
  35256. },
  35257. /**
  35258. * Sets the global Hue value.
  35259. * 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).
  35260. */
  35261. set: function (value) {
  35262. this._globalHue = value;
  35263. this._dirty = true;
  35264. },
  35265. enumerable: true,
  35266. configurable: true
  35267. });
  35268. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  35269. /**
  35270. * Gets the global Density value.
  35271. * 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.
  35272. * Values less than zero provide a filter of opposite hue.
  35273. */
  35274. get: function () {
  35275. return this._globalDensity;
  35276. },
  35277. /**
  35278. * Sets the global Density value.
  35279. * 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.
  35280. * Values less than zero provide a filter of opposite hue.
  35281. */
  35282. set: function (value) {
  35283. this._globalDensity = value;
  35284. this._dirty = true;
  35285. },
  35286. enumerable: true,
  35287. configurable: true
  35288. });
  35289. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  35290. /**
  35291. * Gets the global Saturation value.
  35292. * 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.
  35293. */
  35294. get: function () {
  35295. return this._globalSaturation;
  35296. },
  35297. /**
  35298. * Sets the global Saturation value.
  35299. * 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.
  35300. */
  35301. set: function (value) {
  35302. this._globalSaturation = value;
  35303. this._dirty = true;
  35304. },
  35305. enumerable: true,
  35306. configurable: true
  35307. });
  35308. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  35309. /**
  35310. * Gets the highlights Hue value.
  35311. * 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).
  35312. */
  35313. get: function () {
  35314. return this._highlightsHue;
  35315. },
  35316. /**
  35317. * Sets the highlights Hue value.
  35318. * 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).
  35319. */
  35320. set: function (value) {
  35321. this._highlightsHue = value;
  35322. this._dirty = true;
  35323. },
  35324. enumerable: true,
  35325. configurable: true
  35326. });
  35327. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  35328. /**
  35329. * Gets the highlights Density value.
  35330. * 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.
  35331. * Values less than zero provide a filter of opposite hue.
  35332. */
  35333. get: function () {
  35334. return this._highlightsDensity;
  35335. },
  35336. /**
  35337. * Sets the highlights Density value.
  35338. * 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.
  35339. * Values less than zero provide a filter of opposite hue.
  35340. */
  35341. set: function (value) {
  35342. this._highlightsDensity = value;
  35343. this._dirty = true;
  35344. },
  35345. enumerable: true,
  35346. configurable: true
  35347. });
  35348. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  35349. /**
  35350. * Gets the highlights Saturation value.
  35351. * 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.
  35352. */
  35353. get: function () {
  35354. return this._highlightsSaturation;
  35355. },
  35356. /**
  35357. * Sets the highlights Saturation value.
  35358. * 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.
  35359. */
  35360. set: function (value) {
  35361. this._highlightsSaturation = value;
  35362. this._dirty = true;
  35363. },
  35364. enumerable: true,
  35365. configurable: true
  35366. });
  35367. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  35368. /**
  35369. * Gets the highlights Exposure value.
  35370. * 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.
  35371. */
  35372. get: function () {
  35373. return this._highlightsExposure;
  35374. },
  35375. /**
  35376. * Sets the highlights Exposure value.
  35377. * 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.
  35378. */
  35379. set: function (value) {
  35380. this._highlightsExposure = value;
  35381. this._dirty = true;
  35382. },
  35383. enumerable: true,
  35384. configurable: true
  35385. });
  35386. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  35387. /**
  35388. * Gets the midtones Hue value.
  35389. * 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).
  35390. */
  35391. get: function () {
  35392. return this._midtonesHue;
  35393. },
  35394. /**
  35395. * Sets the midtones Hue value.
  35396. * 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).
  35397. */
  35398. set: function (value) {
  35399. this._midtonesHue = value;
  35400. this._dirty = true;
  35401. },
  35402. enumerable: true,
  35403. configurable: true
  35404. });
  35405. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  35406. /**
  35407. * Gets the midtones Density value.
  35408. * 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.
  35409. * Values less than zero provide a filter of opposite hue.
  35410. */
  35411. get: function () {
  35412. return this._midtonesDensity;
  35413. },
  35414. /**
  35415. * Sets the midtones Density value.
  35416. * 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.
  35417. * Values less than zero provide a filter of opposite hue.
  35418. */
  35419. set: function (value) {
  35420. this._midtonesDensity = value;
  35421. this._dirty = true;
  35422. },
  35423. enumerable: true,
  35424. configurable: true
  35425. });
  35426. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  35427. /**
  35428. * Gets the midtones Saturation value.
  35429. * 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.
  35430. */
  35431. get: function () {
  35432. return this._midtonesSaturation;
  35433. },
  35434. /**
  35435. * Sets the midtones Saturation value.
  35436. * 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.
  35437. */
  35438. set: function (value) {
  35439. this._midtonesSaturation = value;
  35440. this._dirty = true;
  35441. },
  35442. enumerable: true,
  35443. configurable: true
  35444. });
  35445. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  35446. /**
  35447. * Gets the midtones Exposure value.
  35448. * 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.
  35449. */
  35450. get: function () {
  35451. return this._midtonesExposure;
  35452. },
  35453. /**
  35454. * Sets the midtones Exposure value.
  35455. * 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.
  35456. */
  35457. set: function (value) {
  35458. this._midtonesExposure = value;
  35459. this._dirty = true;
  35460. },
  35461. enumerable: true,
  35462. configurable: true
  35463. });
  35464. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  35465. /**
  35466. * Gets the shadows Hue value.
  35467. * 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).
  35468. */
  35469. get: function () {
  35470. return this._shadowsHue;
  35471. },
  35472. /**
  35473. * Sets the shadows Hue value.
  35474. * 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).
  35475. */
  35476. set: function (value) {
  35477. this._shadowsHue = value;
  35478. this._dirty = true;
  35479. },
  35480. enumerable: true,
  35481. configurable: true
  35482. });
  35483. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  35484. /**
  35485. * Gets the shadows Density value.
  35486. * 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.
  35487. * Values less than zero provide a filter of opposite hue.
  35488. */
  35489. get: function () {
  35490. return this._shadowsDensity;
  35491. },
  35492. /**
  35493. * Sets the shadows Density value.
  35494. * 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.
  35495. * Values less than zero provide a filter of opposite hue.
  35496. */
  35497. set: function (value) {
  35498. this._shadowsDensity = value;
  35499. this._dirty = true;
  35500. },
  35501. enumerable: true,
  35502. configurable: true
  35503. });
  35504. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  35505. /**
  35506. * Gets the shadows Saturation value.
  35507. * 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.
  35508. */
  35509. get: function () {
  35510. return this._shadowsSaturation;
  35511. },
  35512. /**
  35513. * Sets the shadows Saturation value.
  35514. * 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.
  35515. */
  35516. set: function (value) {
  35517. this._shadowsSaturation = value;
  35518. this._dirty = true;
  35519. },
  35520. enumerable: true,
  35521. configurable: true
  35522. });
  35523. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  35524. /**
  35525. * Gets the shadows Exposure value.
  35526. * 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.
  35527. */
  35528. get: function () {
  35529. return this._shadowsExposure;
  35530. },
  35531. /**
  35532. * Sets the shadows Exposure value.
  35533. * 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.
  35534. */
  35535. set: function (value) {
  35536. this._shadowsExposure = value;
  35537. this._dirty = true;
  35538. },
  35539. enumerable: true,
  35540. configurable: true
  35541. });
  35542. ColorCurves.prototype.getClassName = function () {
  35543. return "ColorCurves";
  35544. };
  35545. /**
  35546. * Binds the color curves to the shader.
  35547. * @param colorCurves The color curve to bind
  35548. * @param effect The effect to bind to
  35549. */
  35550. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  35551. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  35552. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  35553. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  35554. if (colorCurves._dirty) {
  35555. colorCurves._dirty = false;
  35556. // Fill in global info.
  35557. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  35558. // Compute highlights info.
  35559. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  35560. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  35561. // Compute midtones info.
  35562. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  35563. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  35564. // Compute shadows info.
  35565. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  35566. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  35567. // Compute deltas (neutral is midtones).
  35568. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  35569. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  35570. }
  35571. if (effect) {
  35572. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  35573. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  35574. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  35575. }
  35576. };
  35577. /**
  35578. * Prepare the list of uniforms associated with the ColorCurves effects.
  35579. * @param uniformsList The list of uniforms used in the effect
  35580. */
  35581. ColorCurves.PrepareUniforms = function (uniformsList) {
  35582. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  35583. };
  35584. /**
  35585. * Returns color grading data based on a hue, density, saturation and exposure value.
  35586. * @param filterHue The hue of the color filter.
  35587. * @param filterDensity The density of the color filter.
  35588. * @param saturation The saturation.
  35589. * @param exposure The exposure.
  35590. * @param result The result data container.
  35591. */
  35592. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  35593. if (hue == null) {
  35594. return;
  35595. }
  35596. hue = ColorCurves.clamp(hue, 0, 360);
  35597. density = ColorCurves.clamp(density, -100, 100);
  35598. saturation = ColorCurves.clamp(saturation, -100, 100);
  35599. exposure = ColorCurves.clamp(exposure, -100, 100);
  35600. // Remap the slider/config filter density with non-linear mapping and also scale by half
  35601. // so that the maximum filter density is only 50% control. This provides fine control
  35602. // for small values and reasonable range.
  35603. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  35604. density *= 0.5;
  35605. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  35606. if (density < 0) {
  35607. density *= -1;
  35608. hue = (hue + 180) % 360;
  35609. }
  35610. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  35611. result.scaleToRef(2, result);
  35612. result.a = 1 + 0.01 * saturation;
  35613. };
  35614. /**
  35615. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  35616. * @param value The input slider value in range [-100,100].
  35617. * @returns Adjusted value.
  35618. */
  35619. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  35620. value /= 100;
  35621. var x = Math.abs(value);
  35622. x = Math.pow(x, 2);
  35623. if (value < 0) {
  35624. x *= -1;
  35625. }
  35626. x *= 100;
  35627. return x;
  35628. };
  35629. /**
  35630. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  35631. * @param hue The hue (H) input.
  35632. * @param saturation The saturation (S) input.
  35633. * @param brightness The brightness (B) input.
  35634. * @result An RGBA color represented as Vector4.
  35635. */
  35636. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  35637. var h = ColorCurves.clamp(hue, 0, 360);
  35638. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  35639. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  35640. if (s === 0) {
  35641. result.r = v;
  35642. result.g = v;
  35643. result.b = v;
  35644. }
  35645. else {
  35646. // sector 0 to 5
  35647. h /= 60;
  35648. var i = Math.floor(h);
  35649. // fractional part of h
  35650. var f = h - i;
  35651. var p = v * (1 - s);
  35652. var q = v * (1 - s * f);
  35653. var t = v * (1 - s * (1 - f));
  35654. switch (i) {
  35655. case 0:
  35656. result.r = v;
  35657. result.g = t;
  35658. result.b = p;
  35659. break;
  35660. case 1:
  35661. result.r = q;
  35662. result.g = v;
  35663. result.b = p;
  35664. break;
  35665. case 2:
  35666. result.r = p;
  35667. result.g = v;
  35668. result.b = t;
  35669. break;
  35670. case 3:
  35671. result.r = p;
  35672. result.g = q;
  35673. result.b = v;
  35674. break;
  35675. case 4:
  35676. result.r = t;
  35677. result.g = p;
  35678. result.b = v;
  35679. break;
  35680. default:// case 5:
  35681. result.r = v;
  35682. result.g = p;
  35683. result.b = q;
  35684. break;
  35685. }
  35686. }
  35687. result.a = 1;
  35688. };
  35689. /**
  35690. * Returns a value clamped between min and max
  35691. * @param value The value to clamp
  35692. * @param min The minimum of value
  35693. * @param max The maximum of value
  35694. * @returns The clamped value.
  35695. */
  35696. ColorCurves.clamp = function (value, min, max) {
  35697. return Math.min(Math.max(value, min), max);
  35698. };
  35699. /**
  35700. * Clones the current color curve instance.
  35701. * @return The cloned curves
  35702. */
  35703. ColorCurves.prototype.clone = function () {
  35704. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  35705. };
  35706. /**
  35707. * Serializes the current color curve instance to a json representation.
  35708. * @return a JSON representation
  35709. */
  35710. ColorCurves.prototype.serialize = function () {
  35711. return BABYLON.SerializationHelper.Serialize(this);
  35712. };
  35713. /**
  35714. * Parses the color curve from a json representation.
  35715. * @param source the JSON source to parse
  35716. * @return The parsed curves
  35717. */
  35718. ColorCurves.Parse = function (source) {
  35719. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  35720. };
  35721. __decorate([
  35722. BABYLON.serialize()
  35723. ], ColorCurves.prototype, "_globalHue", void 0);
  35724. __decorate([
  35725. BABYLON.serialize()
  35726. ], ColorCurves.prototype, "_globalDensity", void 0);
  35727. __decorate([
  35728. BABYLON.serialize()
  35729. ], ColorCurves.prototype, "_globalSaturation", void 0);
  35730. __decorate([
  35731. BABYLON.serialize()
  35732. ], ColorCurves.prototype, "_globalExposure", void 0);
  35733. __decorate([
  35734. BABYLON.serialize()
  35735. ], ColorCurves.prototype, "_highlightsHue", void 0);
  35736. __decorate([
  35737. BABYLON.serialize()
  35738. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  35739. __decorate([
  35740. BABYLON.serialize()
  35741. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  35742. __decorate([
  35743. BABYLON.serialize()
  35744. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  35745. __decorate([
  35746. BABYLON.serialize()
  35747. ], ColorCurves.prototype, "_midtonesHue", void 0);
  35748. __decorate([
  35749. BABYLON.serialize()
  35750. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  35751. __decorate([
  35752. BABYLON.serialize()
  35753. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  35754. __decorate([
  35755. BABYLON.serialize()
  35756. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  35757. return ColorCurves;
  35758. }());
  35759. BABYLON.ColorCurves = ColorCurves;
  35760. })(BABYLON || (BABYLON = {}));
  35761. //# sourceMappingURL=babylon.colorCurves.js.map
  35762. //# sourceMappingURL=babylon.behavior.js.map
  35763. var BABYLON;
  35764. (function (BABYLON) {
  35765. var MaterialHelper = /** @class */ (function () {
  35766. function MaterialHelper() {
  35767. }
  35768. MaterialHelper.BindEyePosition = function (effect, scene) {
  35769. if (scene._forcedViewPosition) {
  35770. effect.setVector3("vEyePosition", scene._forcedViewPosition);
  35771. return;
  35772. }
  35773. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  35774. };
  35775. MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {
  35776. defines._needUVs = true;
  35777. defines[key] = true;
  35778. if (texture.getTextureMatrix().isIdentity(true)) {
  35779. defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
  35780. if (texture.coordinatesIndex === 0) {
  35781. defines["MAINUV1"] = true;
  35782. }
  35783. else {
  35784. defines["MAINUV2"] = true;
  35785. }
  35786. }
  35787. else {
  35788. defines[key + "DIRECTUV"] = 0;
  35789. }
  35790. };
  35791. MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {
  35792. var matrix = texture.getTextureMatrix();
  35793. if (!matrix.isIdentity(true)) {
  35794. uniformBuffer.updateMatrix(key + "Matrix", matrix);
  35795. }
  35796. };
  35797. /**
  35798. * Helper used to prepare the list of defines associated with misc. values for shader compilation
  35799. * @param mesh defines the current mesh
  35800. * @param scene defines the current scene
  35801. * @param useLogarithmicDepth defines if logarithmic depth has to be turned on
  35802. * @param pointsCloud defines if point cloud rendering has to be turned on
  35803. * @param fogEnabled defines if fog has to be turned on
  35804. * @param alphaTest defines if alpha testing has to be turned on
  35805. * @param defines defines the current list of defines
  35806. */
  35807. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, alphaTest, defines) {
  35808. if (defines._areMiscDirty) {
  35809. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  35810. defines["POINTSIZE"] = (pointsCloud || scene.forcePointsCloud);
  35811. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  35812. defines["NONUNIFORMSCALING"] = mesh.nonUniformScaling;
  35813. defines["ALPHATEST"] = alphaTest;
  35814. }
  35815. };
  35816. /**
  35817. * Helper used to prepare the list of defines associated with frame values for shader compilation
  35818. * @param scene defines the current scene
  35819. * @param engine defines the current engine
  35820. * @param defines specifies the list of active defines
  35821. * @param useInstances defines if instances have to be turned on
  35822. * @param alphaTest defines if alpha testing has to be turned on
  35823. */
  35824. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances) {
  35825. var changed = false;
  35826. if (defines["CLIPPLANE"] !== (scene.clipPlane !== undefined && scene.clipPlane !== null)) {
  35827. defines["CLIPPLANE"] = !defines["CLIPPLANE"];
  35828. changed = true;
  35829. }
  35830. if (defines["DEPTHPREPASS"] !== !engine.getColorWrite()) {
  35831. defines["DEPTHPREPASS"] = !defines["DEPTHPREPASS"];
  35832. changed = true;
  35833. }
  35834. if (defines["INSTANCES"] !== useInstances) {
  35835. defines["INSTANCES"] = useInstances;
  35836. changed = true;
  35837. }
  35838. if (changed) {
  35839. defines.markAsUnprocessed();
  35840. }
  35841. };
  35842. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets, useVertexAlpha) {
  35843. if (useMorphTargets === void 0) { useMorphTargets = false; }
  35844. if (useVertexAlpha === void 0) { useVertexAlpha = true; }
  35845. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  35846. return false;
  35847. }
  35848. defines._normals = defines._needNormals;
  35849. defines._uvs = defines._needUVs;
  35850. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  35851. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  35852. defines["TANGENT"] = true;
  35853. }
  35854. if (defines._needUVs) {
  35855. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  35856. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  35857. }
  35858. else {
  35859. defines["UV1"] = false;
  35860. defines["UV2"] = false;
  35861. }
  35862. if (useVertexColor) {
  35863. var hasVertexColors = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  35864. defines["VERTEXCOLOR"] = hasVertexColors;
  35865. defines["VERTEXALPHA"] = mesh.hasVertexAlpha && hasVertexColors && useVertexAlpha;
  35866. }
  35867. if (useBones) {
  35868. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  35869. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  35870. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  35871. }
  35872. else {
  35873. defines["NUM_BONE_INFLUENCERS"] = 0;
  35874. defines["BonesPerMesh"] = 0;
  35875. }
  35876. }
  35877. if (useMorphTargets) {
  35878. var manager = mesh.morphTargetManager;
  35879. if (manager) {
  35880. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  35881. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  35882. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  35883. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  35884. }
  35885. else {
  35886. defines["MORPHTARGETS_TANGENT"] = false;
  35887. defines["MORPHTARGETS_NORMAL"] = false;
  35888. defines["MORPHTARGETS"] = false;
  35889. defines["NUM_MORPH_INFLUENCERS"] = 0;
  35890. }
  35891. }
  35892. return true;
  35893. };
  35894. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  35895. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  35896. if (disableLighting === void 0) { disableLighting = false; }
  35897. if (!defines._areLightsDirty) {
  35898. return defines._needNormals;
  35899. }
  35900. var lightIndex = 0;
  35901. var needNormals = false;
  35902. var needRebuild = false;
  35903. var lightmapMode = false;
  35904. var shadowEnabled = false;
  35905. var specularEnabled = false;
  35906. if (scene.lightsEnabled && !disableLighting) {
  35907. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  35908. var light = _a[_i];
  35909. needNormals = true;
  35910. if (defines["LIGHT" + lightIndex] === undefined) {
  35911. needRebuild = true;
  35912. }
  35913. defines["LIGHT" + lightIndex] = true;
  35914. defines["SPOTLIGHT" + lightIndex] = false;
  35915. defines["HEMILIGHT" + lightIndex] = false;
  35916. defines["POINTLIGHT" + lightIndex] = false;
  35917. defines["DIRLIGHT" + lightIndex] = false;
  35918. var type;
  35919. if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_SPOTLIGHT) {
  35920. type = "SPOTLIGHT" + lightIndex;
  35921. }
  35922. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT) {
  35923. type = "HEMILIGHT" + lightIndex;
  35924. }
  35925. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_POINTLIGHT) {
  35926. type = "POINTLIGHT" + lightIndex;
  35927. }
  35928. else {
  35929. type = "DIRLIGHT" + lightIndex;
  35930. }
  35931. defines[type] = true;
  35932. // Specular
  35933. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  35934. specularEnabled = true;
  35935. }
  35936. // Shadows
  35937. defines["SHADOW" + lightIndex] = false;
  35938. defines["SHADOWPCF" + lightIndex] = false;
  35939. defines["SHADOWESM" + lightIndex] = false;
  35940. defines["SHADOWCUBE" + lightIndex] = false;
  35941. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  35942. var shadowGenerator = light.getShadowGenerator();
  35943. if (shadowGenerator) {
  35944. shadowEnabled = true;
  35945. shadowGenerator.prepareDefines(defines, lightIndex);
  35946. }
  35947. }
  35948. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  35949. lightmapMode = true;
  35950. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  35951. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  35952. }
  35953. else {
  35954. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  35955. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  35956. }
  35957. lightIndex++;
  35958. if (lightIndex === maxSimultaneousLights)
  35959. break;
  35960. }
  35961. }
  35962. defines["SPECULARTERM"] = specularEnabled;
  35963. defines["SHADOWS"] = shadowEnabled;
  35964. // Resetting all other lights if any
  35965. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  35966. if (defines["LIGHT" + index] !== undefined) {
  35967. defines["LIGHT" + index] = false;
  35968. defines["HEMILIGHT" + lightIndex] = false;
  35969. defines["POINTLIGHT" + lightIndex] = false;
  35970. defines["DIRLIGHT" + lightIndex] = false;
  35971. defines["SPOTLIGHT" + lightIndex] = false;
  35972. defines["SHADOW" + lightIndex] = false;
  35973. }
  35974. }
  35975. var caps = scene.getEngine().getCaps();
  35976. if (defines["SHADOWFLOAT"] === undefined) {
  35977. needRebuild = true;
  35978. }
  35979. defines["SHADOWFLOAT"] = shadowEnabled &&
  35980. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  35981. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  35982. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  35983. if (needRebuild) {
  35984. defines.rebuild();
  35985. }
  35986. return needNormals;
  35987. };
  35988. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  35989. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  35990. var uniformsList;
  35991. var uniformBuffersList = null;
  35992. if (uniformsListOrOptions.uniformsNames) {
  35993. var options = uniformsListOrOptions;
  35994. uniformsList = options.uniformsNames;
  35995. uniformBuffersList = options.uniformBuffersNames;
  35996. samplersList = options.samplers;
  35997. defines = options.defines;
  35998. maxSimultaneousLights = options.maxSimultaneousLights;
  35999. }
  36000. else {
  36001. uniformsList = uniformsListOrOptions;
  36002. if (!samplersList) {
  36003. samplersList = [];
  36004. }
  36005. }
  36006. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  36007. if (!defines["LIGHT" + lightIndex]) {
  36008. break;
  36009. }
  36010. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  36011. if (uniformBuffersList) {
  36012. uniformBuffersList.push("Light" + lightIndex);
  36013. }
  36014. samplersList.push("shadowSampler" + lightIndex);
  36015. }
  36016. if (defines["NUM_MORPH_INFLUENCERS"]) {
  36017. uniformsList.push("morphTargetInfluences");
  36018. }
  36019. };
  36020. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights, rank) {
  36021. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  36022. if (rank === void 0) { rank = 0; }
  36023. var lightFallbackRank = 0;
  36024. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  36025. if (!defines["LIGHT" + lightIndex]) {
  36026. break;
  36027. }
  36028. if (lightIndex > 0) {
  36029. lightFallbackRank = rank + lightIndex;
  36030. fallbacks.addFallback(lightFallbackRank, "LIGHT" + lightIndex);
  36031. }
  36032. if (!defines["SHADOWS"]) {
  36033. if (defines["SHADOW" + lightIndex]) {
  36034. fallbacks.addFallback(rank, "SHADOW" + lightIndex);
  36035. }
  36036. if (defines["SHADOWPCF" + lightIndex]) {
  36037. fallbacks.addFallback(rank, "SHADOWPCF" + lightIndex);
  36038. }
  36039. if (defines["SHADOWESM" + lightIndex]) {
  36040. fallbacks.addFallback(rank, "SHADOWESM" + lightIndex);
  36041. }
  36042. }
  36043. }
  36044. return lightFallbackRank++;
  36045. };
  36046. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  36047. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  36048. if (influencers > 0 && BABYLON.Engine.LastCreatedEngine) {
  36049. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  36050. var manager = mesh.morphTargetManager;
  36051. var normal = manager && manager.supportsNormals && defines["NORMAL"];
  36052. var tangent = manager && manager.supportsTangents && defines["TANGENT"];
  36053. for (var index = 0; index < influencers; index++) {
  36054. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  36055. if (normal) {
  36056. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  36057. }
  36058. if (tangent) {
  36059. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  36060. }
  36061. if (attribs.length > maxAttributesCount) {
  36062. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  36063. }
  36064. }
  36065. }
  36066. };
  36067. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  36068. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  36069. fallbacks.addCPUSkinningFallback(0, mesh);
  36070. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  36071. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  36072. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  36073. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  36074. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  36075. }
  36076. }
  36077. };
  36078. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  36079. if (defines["INSTANCES"]) {
  36080. attribs.push("world0");
  36081. attribs.push("world1");
  36082. attribs.push("world2");
  36083. attribs.push("world3");
  36084. }
  36085. };
  36086. // Bindings
  36087. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  36088. if (light.shadowEnabled && mesh.receiveShadows) {
  36089. var shadowGenerator = light.getShadowGenerator();
  36090. if (shadowGenerator) {
  36091. shadowGenerator.bindShadowLight(lightIndex, effect);
  36092. }
  36093. }
  36094. };
  36095. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  36096. light.transferToEffect(effect, lightIndex + "");
  36097. };
  36098. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  36099. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  36100. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  36101. var len = Math.min(mesh._lightSources.length, maxSimultaneousLights);
  36102. for (var i = 0; i < len; i++) {
  36103. var light = mesh._lightSources[i];
  36104. var iAsString = i.toString();
  36105. var scaledIntensity = light.getScaledIntensity();
  36106. light._uniformBuffer.bindToEffect(effect, "Light" + i);
  36107. MaterialHelper.BindLightProperties(light, effect, i);
  36108. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  36109. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, iAsString);
  36110. if (defines["SPECULARTERM"]) {
  36111. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  36112. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], iAsString);
  36113. }
  36114. // Shadows
  36115. if (scene.shadowsEnabled) {
  36116. this.BindLightShadow(light, scene, mesh, iAsString, effect);
  36117. }
  36118. light._uniformBuffer.update();
  36119. }
  36120. };
  36121. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  36122. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  36123. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  36124. effect.setColor3("vFogColor", scene.fogColor);
  36125. }
  36126. };
  36127. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  36128. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  36129. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  36130. if (matrices && effect) {
  36131. effect.setMatrices("mBones", matrices);
  36132. }
  36133. }
  36134. };
  36135. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  36136. var manager = abstractMesh.morphTargetManager;
  36137. if (!abstractMesh || !manager) {
  36138. return;
  36139. }
  36140. effect.setFloatArray("morphTargetInfluences", manager.influences);
  36141. };
  36142. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  36143. if (defines["LOGARITHMICDEPTH"]) {
  36144. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  36145. }
  36146. };
  36147. MaterialHelper.BindClipPlane = function (effect, scene) {
  36148. if (scene.clipPlane) {
  36149. var clipPlane = scene.clipPlane;
  36150. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  36151. }
  36152. };
  36153. return MaterialHelper;
  36154. }());
  36155. BABYLON.MaterialHelper = MaterialHelper;
  36156. })(BABYLON || (BABYLON = {}));
  36157. //# sourceMappingURL=babylon.materialHelper.js.map
  36158. var BABYLON;
  36159. (function (BABYLON) {
  36160. var PushMaterial = /** @class */ (function (_super) {
  36161. __extends(PushMaterial, _super);
  36162. function PushMaterial(name, scene) {
  36163. var _this = _super.call(this, name, scene) || this;
  36164. _this.storeEffectOnSubMeshes = true;
  36165. return _this;
  36166. }
  36167. PushMaterial.prototype.getEffect = function () {
  36168. return this._activeEffect;
  36169. };
  36170. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  36171. if (!mesh) {
  36172. return false;
  36173. }
  36174. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  36175. return true;
  36176. }
  36177. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  36178. };
  36179. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  36180. this._activeEffect.setMatrix("world", world);
  36181. };
  36182. PushMaterial.prototype.bind = function (world, mesh) {
  36183. if (!mesh) {
  36184. return;
  36185. }
  36186. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  36187. };
  36188. PushMaterial.prototype._afterBind = function (mesh, effect) {
  36189. if (effect === void 0) { effect = null; }
  36190. _super.prototype._afterBind.call(this, mesh);
  36191. this.getScene()._cachedEffect = effect;
  36192. };
  36193. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  36194. if (visibility === void 0) { visibility = 1; }
  36195. return scene.isCachedMaterialInvalid(this, effect, visibility);
  36196. };
  36197. return PushMaterial;
  36198. }(BABYLON.Material));
  36199. BABYLON.PushMaterial = PushMaterial;
  36200. })(BABYLON || (BABYLON = {}));
  36201. //# sourceMappingURL=babylon.pushMaterial.js.map
  36202. var BABYLON;
  36203. (function (BABYLON) {
  36204. var StandardMaterialDefines = /** @class */ (function (_super) {
  36205. __extends(StandardMaterialDefines, _super);
  36206. function StandardMaterialDefines() {
  36207. var _this = _super.call(this) || this;
  36208. _this.MAINUV1 = false;
  36209. _this.MAINUV2 = false;
  36210. _this.DIFFUSE = false;
  36211. _this.DIFFUSEDIRECTUV = 0;
  36212. _this.AMBIENT = false;
  36213. _this.AMBIENTDIRECTUV = 0;
  36214. _this.OPACITY = false;
  36215. _this.OPACITYDIRECTUV = 0;
  36216. _this.OPACITYRGB = false;
  36217. _this.REFLECTION = false;
  36218. _this.EMISSIVE = false;
  36219. _this.EMISSIVEDIRECTUV = 0;
  36220. _this.SPECULAR = false;
  36221. _this.SPECULARDIRECTUV = 0;
  36222. _this.BUMP = false;
  36223. _this.BUMPDIRECTUV = 0;
  36224. _this.PARALLAX = false;
  36225. _this.PARALLAXOCCLUSION = false;
  36226. _this.SPECULAROVERALPHA = false;
  36227. _this.CLIPPLANE = false;
  36228. _this.ALPHATEST = false;
  36229. _this.DEPTHPREPASS = false;
  36230. _this.ALPHAFROMDIFFUSE = false;
  36231. _this.POINTSIZE = false;
  36232. _this.FOG = false;
  36233. _this.SPECULARTERM = false;
  36234. _this.DIFFUSEFRESNEL = false;
  36235. _this.OPACITYFRESNEL = false;
  36236. _this.REFLECTIONFRESNEL = false;
  36237. _this.REFRACTIONFRESNEL = false;
  36238. _this.EMISSIVEFRESNEL = false;
  36239. _this.FRESNEL = false;
  36240. _this.NORMAL = false;
  36241. _this.UV1 = false;
  36242. _this.UV2 = false;
  36243. _this.VERTEXCOLOR = false;
  36244. _this.VERTEXALPHA = false;
  36245. _this.NUM_BONE_INFLUENCERS = 0;
  36246. _this.BonesPerMesh = 0;
  36247. _this.INSTANCES = false;
  36248. _this.GLOSSINESS = false;
  36249. _this.ROUGHNESS = false;
  36250. _this.EMISSIVEASILLUMINATION = false;
  36251. _this.LINKEMISSIVEWITHDIFFUSE = false;
  36252. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  36253. _this.LIGHTMAP = false;
  36254. _this.LIGHTMAPDIRECTUV = 0;
  36255. _this.USELIGHTMAPASSHADOWMAP = false;
  36256. _this.REFLECTIONMAP_3D = false;
  36257. _this.REFLECTIONMAP_SPHERICAL = false;
  36258. _this.REFLECTIONMAP_PLANAR = false;
  36259. _this.REFLECTIONMAP_CUBIC = false;
  36260. _this.REFLECTIONMAP_PROJECTION = false;
  36261. _this.REFLECTIONMAP_SKYBOX = false;
  36262. _this.REFLECTIONMAP_EXPLICIT = false;
  36263. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  36264. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  36265. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  36266. _this.INVERTCUBICMAP = false;
  36267. _this.LOGARITHMICDEPTH = false;
  36268. _this.REFRACTION = false;
  36269. _this.REFRACTIONMAP_3D = false;
  36270. _this.REFLECTIONOVERALPHA = false;
  36271. _this.TWOSIDEDLIGHTING = false;
  36272. _this.SHADOWFLOAT = false;
  36273. _this.MORPHTARGETS = false;
  36274. _this.MORPHTARGETS_NORMAL = false;
  36275. _this.MORPHTARGETS_TANGENT = false;
  36276. _this.NUM_MORPH_INFLUENCERS = 0;
  36277. _this.NONUNIFORMSCALING = false; // https://playground.babylonjs.com#V6DWIH
  36278. _this.PREMULTIPLYALPHA = false; // https://playground.babylonjs.com#LNVJJ7
  36279. _this.IMAGEPROCESSING = false;
  36280. _this.VIGNETTE = false;
  36281. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  36282. _this.VIGNETTEBLENDMODEOPAQUE = false;
  36283. _this.TONEMAPPING = false;
  36284. _this.CONTRAST = false;
  36285. _this.COLORCURVES = false;
  36286. _this.COLORGRADING = false;
  36287. _this.COLORGRADING3D = false;
  36288. _this.SAMPLER3DGREENDEPTH = false;
  36289. _this.SAMPLER3DBGRMAP = false;
  36290. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  36291. _this.EXPOSURE = false;
  36292. _this.rebuild();
  36293. return _this;
  36294. }
  36295. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  36296. var modes = [
  36297. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  36298. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  36299. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  36300. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  36301. ];
  36302. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  36303. var mode = modes_1[_i];
  36304. this[mode] = (mode === modeToEnable);
  36305. }
  36306. };
  36307. return StandardMaterialDefines;
  36308. }(BABYLON.MaterialDefines));
  36309. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  36310. var StandardMaterial = /** @class */ (function (_super) {
  36311. __extends(StandardMaterial, _super);
  36312. function StandardMaterial(name, scene) {
  36313. var _this = _super.call(this, name, scene) || this;
  36314. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  36315. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  36316. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  36317. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  36318. _this.specularPower = 64;
  36319. _this._useAlphaFromDiffuseTexture = false;
  36320. _this._useEmissiveAsIllumination = false;
  36321. _this._linkEmissiveWithDiffuse = false;
  36322. _this._useSpecularOverAlpha = false;
  36323. _this._useReflectionOverAlpha = false;
  36324. _this._disableLighting = false;
  36325. _this._useParallax = false;
  36326. _this._useParallaxOcclusion = false;
  36327. _this.parallaxScaleBias = 0.05;
  36328. _this._roughness = 0;
  36329. _this.indexOfRefraction = 0.98;
  36330. _this.invertRefractionY = true;
  36331. _this._useLightmapAsShadowmap = false;
  36332. _this._useReflectionFresnelFromSpecular = false;
  36333. _this._useGlossinessFromSpecularMapAlpha = false;
  36334. _this._maxSimultaneousLights = 4;
  36335. /**
  36336. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  36337. */
  36338. _this._invertNormalMapX = false;
  36339. /**
  36340. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  36341. */
  36342. _this._invertNormalMapY = false;
  36343. /**
  36344. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  36345. */
  36346. _this._twoSidedLighting = false;
  36347. _this._renderTargets = new BABYLON.SmartArray(16);
  36348. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  36349. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  36350. // Setup the default processing configuration to the scene.
  36351. _this._attachImageProcessingConfiguration(null);
  36352. _this.getRenderTargetTextures = function () {
  36353. _this._renderTargets.reset();
  36354. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  36355. _this._renderTargets.push(_this._reflectionTexture);
  36356. }
  36357. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  36358. _this._renderTargets.push(_this._refractionTexture);
  36359. }
  36360. return _this._renderTargets;
  36361. };
  36362. return _this;
  36363. }
  36364. ;
  36365. ;
  36366. ;
  36367. ;
  36368. ;
  36369. ;
  36370. ;
  36371. ;
  36372. ;
  36373. ;
  36374. ;
  36375. ;
  36376. ;
  36377. ;
  36378. ;
  36379. ;
  36380. ;
  36381. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  36382. /**
  36383. * Gets the image processing configuration used either in this material.
  36384. */
  36385. get: function () {
  36386. return this._imageProcessingConfiguration;
  36387. },
  36388. /**
  36389. * Sets the Default image processing configuration used either in the this material.
  36390. *
  36391. * If sets to null, the scene one is in use.
  36392. */
  36393. set: function (value) {
  36394. this._attachImageProcessingConfiguration(value);
  36395. // Ensure the effect will be rebuilt.
  36396. this._markAllSubMeshesAsTexturesDirty();
  36397. },
  36398. enumerable: true,
  36399. configurable: true
  36400. });
  36401. /**
  36402. * Attaches a new image processing configuration to the Standard Material.
  36403. * @param configuration
  36404. */
  36405. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  36406. var _this = this;
  36407. if (configuration === this._imageProcessingConfiguration) {
  36408. return;
  36409. }
  36410. // Detaches observer.
  36411. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  36412. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  36413. }
  36414. // Pick the scene configuration if needed.
  36415. if (!configuration) {
  36416. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  36417. }
  36418. else {
  36419. this._imageProcessingConfiguration = configuration;
  36420. }
  36421. // Attaches observer.
  36422. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  36423. _this._markAllSubMeshesAsImageProcessingDirty();
  36424. });
  36425. };
  36426. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  36427. /**
  36428. * Gets wether the color curves effect is enabled.
  36429. */
  36430. get: function () {
  36431. return this.imageProcessingConfiguration.colorCurvesEnabled;
  36432. },
  36433. /**
  36434. * Sets wether the color curves effect is enabled.
  36435. */
  36436. set: function (value) {
  36437. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  36438. },
  36439. enumerable: true,
  36440. configurable: true
  36441. });
  36442. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  36443. /**
  36444. * Gets wether the color grading effect is enabled.
  36445. */
  36446. get: function () {
  36447. return this.imageProcessingConfiguration.colorGradingEnabled;
  36448. },
  36449. /**
  36450. * Gets wether the color grading effect is enabled.
  36451. */
  36452. set: function (value) {
  36453. this.imageProcessingConfiguration.colorGradingEnabled = value;
  36454. },
  36455. enumerable: true,
  36456. configurable: true
  36457. });
  36458. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  36459. /**
  36460. * Gets wether tonemapping is enabled or not.
  36461. */
  36462. get: function () {
  36463. return this._imageProcessingConfiguration.toneMappingEnabled;
  36464. },
  36465. /**
  36466. * Sets wether tonemapping is enabled or not
  36467. */
  36468. set: function (value) {
  36469. this._imageProcessingConfiguration.toneMappingEnabled = value;
  36470. },
  36471. enumerable: true,
  36472. configurable: true
  36473. });
  36474. ;
  36475. ;
  36476. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  36477. /**
  36478. * The camera exposure used on this material.
  36479. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  36480. * This corresponds to a photographic exposure.
  36481. */
  36482. get: function () {
  36483. return this._imageProcessingConfiguration.exposure;
  36484. },
  36485. /**
  36486. * The camera exposure used on this material.
  36487. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  36488. * This corresponds to a photographic exposure.
  36489. */
  36490. set: function (value) {
  36491. this._imageProcessingConfiguration.exposure = value;
  36492. },
  36493. enumerable: true,
  36494. configurable: true
  36495. });
  36496. ;
  36497. ;
  36498. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  36499. /**
  36500. * Gets The camera contrast used on this material.
  36501. */
  36502. get: function () {
  36503. return this._imageProcessingConfiguration.contrast;
  36504. },
  36505. /**
  36506. * Sets The camera contrast used on this material.
  36507. */
  36508. set: function (value) {
  36509. this._imageProcessingConfiguration.contrast = value;
  36510. },
  36511. enumerable: true,
  36512. configurable: true
  36513. });
  36514. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  36515. /**
  36516. * Gets the Color Grading 2D Lookup Texture.
  36517. */
  36518. get: function () {
  36519. return this._imageProcessingConfiguration.colorGradingTexture;
  36520. },
  36521. /**
  36522. * Sets the Color Grading 2D Lookup Texture.
  36523. */
  36524. set: function (value) {
  36525. this._imageProcessingConfiguration.colorGradingTexture = value;
  36526. },
  36527. enumerable: true,
  36528. configurable: true
  36529. });
  36530. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurves", {
  36531. /**
  36532. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  36533. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  36534. * 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;
  36535. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  36536. */
  36537. get: function () {
  36538. return this._imageProcessingConfiguration.colorCurves;
  36539. },
  36540. /**
  36541. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  36542. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  36543. * 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;
  36544. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  36545. */
  36546. set: function (value) {
  36547. this._imageProcessingConfiguration.colorCurves = value;
  36548. },
  36549. enumerable: true,
  36550. configurable: true
  36551. });
  36552. StandardMaterial.prototype.getClassName = function () {
  36553. return "StandardMaterial";
  36554. };
  36555. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  36556. get: function () {
  36557. return this._useLogarithmicDepth;
  36558. },
  36559. set: function (value) {
  36560. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  36561. this._markAllSubMeshesAsMiscDirty();
  36562. },
  36563. enumerable: true,
  36564. configurable: true
  36565. });
  36566. StandardMaterial.prototype.needAlphaBlending = function () {
  36567. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  36568. };
  36569. StandardMaterial.prototype.needAlphaTesting = function () {
  36570. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  36571. };
  36572. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  36573. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  36574. };
  36575. StandardMaterial.prototype.getAlphaTestTexture = function () {
  36576. return this._diffuseTexture;
  36577. };
  36578. /**
  36579. * Child classes can use it to update shaders
  36580. */
  36581. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  36582. if (useInstances === void 0) { useInstances = false; }
  36583. if (subMesh.effect && this.isFrozen) {
  36584. if (this._wasPreviouslyReady && subMesh.effect) {
  36585. return true;
  36586. }
  36587. }
  36588. if (!subMesh._materialDefines) {
  36589. subMesh._materialDefines = new StandardMaterialDefines();
  36590. }
  36591. var scene = this.getScene();
  36592. var defines = subMesh._materialDefines;
  36593. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  36594. if (defines._renderId === scene.getRenderId()) {
  36595. return true;
  36596. }
  36597. }
  36598. var engine = scene.getEngine();
  36599. // Lights
  36600. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  36601. // Textures
  36602. if (defines._areTexturesDirty) {
  36603. defines._needUVs = false;
  36604. defines.MAINUV1 = false;
  36605. defines.MAINUV2 = false;
  36606. if (scene.texturesEnabled) {
  36607. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  36608. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  36609. return false;
  36610. }
  36611. else {
  36612. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  36613. }
  36614. }
  36615. else {
  36616. defines.DIFFUSE = false;
  36617. }
  36618. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  36619. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  36620. return false;
  36621. }
  36622. else {
  36623. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  36624. }
  36625. }
  36626. else {
  36627. defines.AMBIENT = false;
  36628. }
  36629. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  36630. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  36631. return false;
  36632. }
  36633. else {
  36634. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  36635. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  36636. }
  36637. }
  36638. else {
  36639. defines.OPACITY = false;
  36640. }
  36641. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  36642. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  36643. return false;
  36644. }
  36645. else {
  36646. defines._needNormals = true;
  36647. defines.REFLECTION = true;
  36648. defines.ROUGHNESS = (this._roughness > 0);
  36649. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  36650. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  36651. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  36652. switch (this._reflectionTexture.coordinatesMode) {
  36653. case BABYLON.Texture.CUBIC_MODE:
  36654. case BABYLON.Texture.INVCUBIC_MODE:
  36655. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  36656. break;
  36657. case BABYLON.Texture.EXPLICIT_MODE:
  36658. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  36659. break;
  36660. case BABYLON.Texture.PLANAR_MODE:
  36661. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  36662. break;
  36663. case BABYLON.Texture.PROJECTION_MODE:
  36664. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  36665. break;
  36666. case BABYLON.Texture.SKYBOX_MODE:
  36667. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  36668. break;
  36669. case BABYLON.Texture.SPHERICAL_MODE:
  36670. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  36671. break;
  36672. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  36673. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  36674. break;
  36675. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  36676. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  36677. break;
  36678. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  36679. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  36680. break;
  36681. }
  36682. }
  36683. }
  36684. else {
  36685. defines.REFLECTION = false;
  36686. }
  36687. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  36688. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  36689. return false;
  36690. }
  36691. else {
  36692. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  36693. }
  36694. }
  36695. else {
  36696. defines.EMISSIVE = false;
  36697. }
  36698. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  36699. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  36700. return false;
  36701. }
  36702. else {
  36703. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  36704. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  36705. }
  36706. }
  36707. else {
  36708. defines.LIGHTMAP = false;
  36709. }
  36710. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  36711. if (!this._specularTexture.isReadyOrNotBlocking()) {
  36712. return false;
  36713. }
  36714. else {
  36715. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
  36716. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  36717. }
  36718. }
  36719. else {
  36720. defines.SPECULAR = false;
  36721. }
  36722. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  36723. // Bump texure can not be not blocking.
  36724. if (!this._bumpTexture.isReady()) {
  36725. return false;
  36726. }
  36727. else {
  36728. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  36729. defines.PARALLAX = this._useParallax;
  36730. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  36731. }
  36732. }
  36733. else {
  36734. defines.BUMP = false;
  36735. }
  36736. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  36737. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  36738. return false;
  36739. }
  36740. else {
  36741. defines._needUVs = true;
  36742. defines.REFRACTION = true;
  36743. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  36744. }
  36745. }
  36746. else {
  36747. defines.REFRACTION = false;
  36748. }
  36749. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  36750. }
  36751. else {
  36752. defines.DIFFUSE = false;
  36753. defines.AMBIENT = false;
  36754. defines.OPACITY = false;
  36755. defines.REFLECTION = false;
  36756. defines.EMISSIVE = false;
  36757. defines.LIGHTMAP = false;
  36758. defines.BUMP = false;
  36759. defines.REFRACTION = false;
  36760. }
  36761. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  36762. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  36763. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  36764. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  36765. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  36766. }
  36767. if (defines._areImageProcessingDirty) {
  36768. if (!this._imageProcessingConfiguration.isReady()) {
  36769. return false;
  36770. }
  36771. this._imageProcessingConfiguration.prepareDefines(defines);
  36772. }
  36773. if (defines._areFresnelDirty) {
  36774. if (StandardMaterial.FresnelEnabled) {
  36775. // Fresnel
  36776. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  36777. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  36778. this._reflectionFresnelParameters) {
  36779. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  36780. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  36781. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  36782. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  36783. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  36784. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  36785. defines._needNormals = true;
  36786. defines.FRESNEL = true;
  36787. }
  36788. }
  36789. else {
  36790. defines.FRESNEL = false;
  36791. }
  36792. }
  36793. // Misc.
  36794. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  36795. // Attribs
  36796. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  36797. // Values that need to be evaluated on every frame
  36798. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  36799. // Get correct effect
  36800. if (defines.isDirty) {
  36801. defines.markAsProcessed();
  36802. scene.resetCachedMaterial();
  36803. // Fallbacks
  36804. var fallbacks = new BABYLON.EffectFallbacks();
  36805. if (defines.REFLECTION) {
  36806. fallbacks.addFallback(0, "REFLECTION");
  36807. }
  36808. if (defines.SPECULAR) {
  36809. fallbacks.addFallback(0, "SPECULAR");
  36810. }
  36811. if (defines.BUMP) {
  36812. fallbacks.addFallback(0, "BUMP");
  36813. }
  36814. if (defines.PARALLAX) {
  36815. fallbacks.addFallback(1, "PARALLAX");
  36816. }
  36817. if (defines.PARALLAXOCCLUSION) {
  36818. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  36819. }
  36820. if (defines.SPECULAROVERALPHA) {
  36821. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  36822. }
  36823. if (defines.FOG) {
  36824. fallbacks.addFallback(1, "FOG");
  36825. }
  36826. if (defines.POINTSIZE) {
  36827. fallbacks.addFallback(0, "POINTSIZE");
  36828. }
  36829. if (defines.LOGARITHMICDEPTH) {
  36830. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  36831. }
  36832. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  36833. if (defines.SPECULARTERM) {
  36834. fallbacks.addFallback(0, "SPECULARTERM");
  36835. }
  36836. if (defines.DIFFUSEFRESNEL) {
  36837. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  36838. }
  36839. if (defines.OPACITYFRESNEL) {
  36840. fallbacks.addFallback(2, "OPACITYFRESNEL");
  36841. }
  36842. if (defines.REFLECTIONFRESNEL) {
  36843. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  36844. }
  36845. if (defines.EMISSIVEFRESNEL) {
  36846. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  36847. }
  36848. if (defines.FRESNEL) {
  36849. fallbacks.addFallback(4, "FRESNEL");
  36850. }
  36851. //Attributes
  36852. var attribs = [BABYLON.VertexBuffer.PositionKind];
  36853. if (defines.NORMAL) {
  36854. attribs.push(BABYLON.VertexBuffer.NormalKind);
  36855. }
  36856. if (defines.UV1) {
  36857. attribs.push(BABYLON.VertexBuffer.UVKind);
  36858. }
  36859. if (defines.UV2) {
  36860. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  36861. }
  36862. if (defines.VERTEXCOLOR) {
  36863. attribs.push(BABYLON.VertexBuffer.ColorKind);
  36864. }
  36865. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  36866. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  36867. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  36868. var shaderName = "default";
  36869. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  36870. "vFogInfos", "vFogColor", "pointSize",
  36871. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  36872. "mBones",
  36873. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  36874. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  36875. "logarithmicDepthConstant", "vTangentSpaceParams"
  36876. ];
  36877. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  36878. var uniformBuffers = ["Material", "Scene"];
  36879. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  36880. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  36881. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  36882. uniformsNames: uniforms,
  36883. uniformBuffersNames: uniformBuffers,
  36884. samplers: samplers,
  36885. defines: defines,
  36886. maxSimultaneousLights: this._maxSimultaneousLights
  36887. });
  36888. if (this.customShaderNameResolve) {
  36889. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  36890. }
  36891. var join = defines.toString();
  36892. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  36893. attributes: attribs,
  36894. uniformsNames: uniforms,
  36895. uniformBuffersNames: uniformBuffers,
  36896. samplers: samplers,
  36897. defines: join,
  36898. fallbacks: fallbacks,
  36899. onCompiled: this.onCompiled,
  36900. onError: this.onError,
  36901. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  36902. }, engine), defines);
  36903. this.buildUniformLayout();
  36904. }
  36905. if (!subMesh.effect || !subMesh.effect.isReady()) {
  36906. return false;
  36907. }
  36908. defines._renderId = scene.getRenderId();
  36909. this._wasPreviouslyReady = true;
  36910. return true;
  36911. };
  36912. StandardMaterial.prototype.buildUniformLayout = function () {
  36913. // Order is important !
  36914. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  36915. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  36916. this._uniformBuffer.addUniform("opacityParts", 4);
  36917. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  36918. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  36919. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  36920. this._uniformBuffer.addUniform("refractionRightColor", 4);
  36921. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  36922. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  36923. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  36924. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  36925. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  36926. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  36927. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  36928. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  36929. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  36930. this._uniformBuffer.addUniform("vBumpInfos", 3);
  36931. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  36932. this._uniformBuffer.addUniform("ambientMatrix", 16);
  36933. this._uniformBuffer.addUniform("opacityMatrix", 16);
  36934. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  36935. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  36936. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  36937. this._uniformBuffer.addUniform("specularMatrix", 16);
  36938. this._uniformBuffer.addUniform("bumpMatrix", 16);
  36939. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  36940. this._uniformBuffer.addUniform("refractionMatrix", 16);
  36941. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  36942. this._uniformBuffer.addUniform("vSpecularColor", 4);
  36943. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  36944. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  36945. this._uniformBuffer.addUniform("pointSize", 1);
  36946. this._uniformBuffer.create();
  36947. };
  36948. StandardMaterial.prototype.unbind = function () {
  36949. if (this._activeEffect) {
  36950. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  36951. this._activeEffect.setTexture("reflection2DSampler", null);
  36952. }
  36953. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  36954. this._activeEffect.setTexture("refraction2DSampler", null);
  36955. }
  36956. }
  36957. _super.prototype.unbind.call(this);
  36958. };
  36959. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  36960. var scene = this.getScene();
  36961. var defines = subMesh._materialDefines;
  36962. if (!defines) {
  36963. return;
  36964. }
  36965. var effect = subMesh.effect;
  36966. if (!effect) {
  36967. return;
  36968. }
  36969. this._activeEffect = effect;
  36970. // Matrices
  36971. this.bindOnlyWorldMatrix(world);
  36972. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  36973. // Bones
  36974. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  36975. if (mustRebind) {
  36976. this._uniformBuffer.bindToEffect(effect, "Material");
  36977. this.bindViewProjection(effect);
  36978. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  36979. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  36980. // Fresnel
  36981. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  36982. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  36983. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  36984. }
  36985. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  36986. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  36987. }
  36988. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  36989. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  36990. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  36991. }
  36992. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  36993. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  36994. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  36995. }
  36996. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  36997. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  36998. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  36999. }
  37000. }
  37001. // Textures
  37002. if (scene.texturesEnabled) {
  37003. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  37004. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  37005. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  37006. }
  37007. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  37008. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  37009. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  37010. }
  37011. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  37012. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  37013. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  37014. }
  37015. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  37016. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  37017. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  37018. }
  37019. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  37020. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  37021. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  37022. }
  37023. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  37024. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  37025. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  37026. }
  37027. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  37028. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  37029. BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
  37030. }
  37031. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  37032. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  37033. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  37034. if (scene._mirroredCameraPosition) {
  37035. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  37036. }
  37037. else {
  37038. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  37039. }
  37040. }
  37041. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  37042. var depth = 1.0;
  37043. if (!this._refractionTexture.isCube) {
  37044. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  37045. if (this._refractionTexture.depth) {
  37046. depth = this._refractionTexture.depth;
  37047. }
  37048. }
  37049. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  37050. }
  37051. }
  37052. // Point size
  37053. if (this.pointsCloud) {
  37054. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  37055. }
  37056. if (defines.SPECULARTERM) {
  37057. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  37058. }
  37059. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  37060. // Diffuse
  37061. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  37062. }
  37063. // Textures
  37064. if (scene.texturesEnabled) {
  37065. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  37066. effect.setTexture("diffuseSampler", this._diffuseTexture);
  37067. }
  37068. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  37069. effect.setTexture("ambientSampler", this._ambientTexture);
  37070. }
  37071. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  37072. effect.setTexture("opacitySampler", this._opacityTexture);
  37073. }
  37074. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  37075. if (this._reflectionTexture.isCube) {
  37076. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  37077. }
  37078. else {
  37079. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  37080. }
  37081. }
  37082. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  37083. effect.setTexture("emissiveSampler", this._emissiveTexture);
  37084. }
  37085. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  37086. effect.setTexture("lightmapSampler", this._lightmapTexture);
  37087. }
  37088. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  37089. effect.setTexture("specularSampler", this._specularTexture);
  37090. }
  37091. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  37092. effect.setTexture("bumpSampler", this._bumpTexture);
  37093. }
  37094. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  37095. var depth = 1.0;
  37096. if (this._refractionTexture.isCube) {
  37097. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  37098. }
  37099. else {
  37100. effect.setTexture("refraction2DSampler", this._refractionTexture);
  37101. }
  37102. }
  37103. }
  37104. // Clip plane
  37105. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  37106. // Colors
  37107. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  37108. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  37109. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  37110. }
  37111. if (mustRebind || !this.isFrozen) {
  37112. // Lights
  37113. if (scene.lightsEnabled && !this._disableLighting) {
  37114. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  37115. }
  37116. // View
  37117. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  37118. this.bindView(effect);
  37119. }
  37120. // Fog
  37121. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  37122. // Morph targets
  37123. if (defines.NUM_MORPH_INFLUENCERS) {
  37124. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  37125. }
  37126. // Log. depth
  37127. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  37128. // image processing
  37129. if (!this._imageProcessingConfiguration.applyByPostProcess) {
  37130. this._imageProcessingConfiguration.bind(this._activeEffect);
  37131. }
  37132. }
  37133. this._uniformBuffer.update();
  37134. this._afterBind(mesh, this._activeEffect);
  37135. };
  37136. StandardMaterial.prototype.getAnimatables = function () {
  37137. var results = [];
  37138. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  37139. results.push(this._diffuseTexture);
  37140. }
  37141. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  37142. results.push(this._ambientTexture);
  37143. }
  37144. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  37145. results.push(this._opacityTexture);
  37146. }
  37147. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  37148. results.push(this._reflectionTexture);
  37149. }
  37150. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  37151. results.push(this._emissiveTexture);
  37152. }
  37153. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  37154. results.push(this._specularTexture);
  37155. }
  37156. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  37157. results.push(this._bumpTexture);
  37158. }
  37159. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  37160. results.push(this._lightmapTexture);
  37161. }
  37162. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  37163. results.push(this._refractionTexture);
  37164. }
  37165. return results;
  37166. };
  37167. StandardMaterial.prototype.getActiveTextures = function () {
  37168. var activeTextures = _super.prototype.getActiveTextures.call(this);
  37169. if (this._diffuseTexture) {
  37170. activeTextures.push(this._diffuseTexture);
  37171. }
  37172. if (this._ambientTexture) {
  37173. activeTextures.push(this._ambientTexture);
  37174. }
  37175. if (this._opacityTexture) {
  37176. activeTextures.push(this._opacityTexture);
  37177. }
  37178. if (this._reflectionTexture) {
  37179. activeTextures.push(this._reflectionTexture);
  37180. }
  37181. if (this._emissiveTexture) {
  37182. activeTextures.push(this._emissiveTexture);
  37183. }
  37184. if (this._specularTexture) {
  37185. activeTextures.push(this._specularTexture);
  37186. }
  37187. if (this._bumpTexture) {
  37188. activeTextures.push(this._bumpTexture);
  37189. }
  37190. if (this._lightmapTexture) {
  37191. activeTextures.push(this._lightmapTexture);
  37192. }
  37193. if (this._refractionTexture) {
  37194. activeTextures.push(this._refractionTexture);
  37195. }
  37196. return activeTextures;
  37197. };
  37198. StandardMaterial.prototype.hasTexture = function (texture) {
  37199. if (_super.prototype.hasTexture.call(this, texture)) {
  37200. return true;
  37201. }
  37202. if (this._diffuseTexture === texture) {
  37203. return true;
  37204. }
  37205. if (this._ambientTexture === texture) {
  37206. return true;
  37207. }
  37208. if (this._opacityTexture === texture) {
  37209. return true;
  37210. }
  37211. if (this._reflectionTexture === texture) {
  37212. return true;
  37213. }
  37214. if (this._emissiveTexture === texture) {
  37215. return true;
  37216. }
  37217. if (this._specularTexture === texture) {
  37218. return true;
  37219. }
  37220. if (this._bumpTexture === texture) {
  37221. return true;
  37222. }
  37223. if (this._lightmapTexture === texture) {
  37224. return true;
  37225. }
  37226. if (this._refractionTexture === texture) {
  37227. return true;
  37228. }
  37229. return false;
  37230. };
  37231. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  37232. if (forceDisposeTextures) {
  37233. if (this._diffuseTexture) {
  37234. this._diffuseTexture.dispose();
  37235. }
  37236. if (this._ambientTexture) {
  37237. this._ambientTexture.dispose();
  37238. }
  37239. if (this._opacityTexture) {
  37240. this._opacityTexture.dispose();
  37241. }
  37242. if (this._reflectionTexture) {
  37243. this._reflectionTexture.dispose();
  37244. }
  37245. if (this._emissiveTexture) {
  37246. this._emissiveTexture.dispose();
  37247. }
  37248. if (this._specularTexture) {
  37249. this._specularTexture.dispose();
  37250. }
  37251. if (this._bumpTexture) {
  37252. this._bumpTexture.dispose();
  37253. }
  37254. if (this._lightmapTexture) {
  37255. this._lightmapTexture.dispose();
  37256. }
  37257. if (this._refractionTexture) {
  37258. this._refractionTexture.dispose();
  37259. }
  37260. }
  37261. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  37262. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  37263. }
  37264. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  37265. };
  37266. StandardMaterial.prototype.clone = function (name) {
  37267. var _this = this;
  37268. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  37269. result.name = name;
  37270. result.id = name;
  37271. return result;
  37272. };
  37273. StandardMaterial.prototype.serialize = function () {
  37274. return BABYLON.SerializationHelper.Serialize(this);
  37275. };
  37276. // Statics
  37277. StandardMaterial.Parse = function (source, scene, rootUrl) {
  37278. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  37279. };
  37280. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  37281. get: function () {
  37282. return StandardMaterial._DiffuseTextureEnabled;
  37283. },
  37284. set: function (value) {
  37285. if (StandardMaterial._DiffuseTextureEnabled === value) {
  37286. return;
  37287. }
  37288. StandardMaterial._DiffuseTextureEnabled = value;
  37289. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  37290. },
  37291. enumerable: true,
  37292. configurable: true
  37293. });
  37294. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  37295. get: function () {
  37296. return StandardMaterial._AmbientTextureEnabled;
  37297. },
  37298. set: function (value) {
  37299. if (StandardMaterial._AmbientTextureEnabled === value) {
  37300. return;
  37301. }
  37302. StandardMaterial._AmbientTextureEnabled = value;
  37303. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  37304. },
  37305. enumerable: true,
  37306. configurable: true
  37307. });
  37308. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  37309. get: function () {
  37310. return StandardMaterial._OpacityTextureEnabled;
  37311. },
  37312. set: function (value) {
  37313. if (StandardMaterial._OpacityTextureEnabled === value) {
  37314. return;
  37315. }
  37316. StandardMaterial._OpacityTextureEnabled = value;
  37317. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  37318. },
  37319. enumerable: true,
  37320. configurable: true
  37321. });
  37322. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  37323. get: function () {
  37324. return StandardMaterial._ReflectionTextureEnabled;
  37325. },
  37326. set: function (value) {
  37327. if (StandardMaterial._ReflectionTextureEnabled === value) {
  37328. return;
  37329. }
  37330. StandardMaterial._ReflectionTextureEnabled = value;
  37331. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  37332. },
  37333. enumerable: true,
  37334. configurable: true
  37335. });
  37336. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  37337. get: function () {
  37338. return StandardMaterial._EmissiveTextureEnabled;
  37339. },
  37340. set: function (value) {
  37341. if (StandardMaterial._EmissiveTextureEnabled === value) {
  37342. return;
  37343. }
  37344. StandardMaterial._EmissiveTextureEnabled = value;
  37345. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  37346. },
  37347. enumerable: true,
  37348. configurable: true
  37349. });
  37350. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  37351. get: function () {
  37352. return StandardMaterial._SpecularTextureEnabled;
  37353. },
  37354. set: function (value) {
  37355. if (StandardMaterial._SpecularTextureEnabled === value) {
  37356. return;
  37357. }
  37358. StandardMaterial._SpecularTextureEnabled = value;
  37359. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  37360. },
  37361. enumerable: true,
  37362. configurable: true
  37363. });
  37364. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  37365. get: function () {
  37366. return StandardMaterial._BumpTextureEnabled;
  37367. },
  37368. set: function (value) {
  37369. if (StandardMaterial._BumpTextureEnabled === value) {
  37370. return;
  37371. }
  37372. StandardMaterial._BumpTextureEnabled = value;
  37373. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  37374. },
  37375. enumerable: true,
  37376. configurable: true
  37377. });
  37378. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  37379. get: function () {
  37380. return StandardMaterial._LightmapTextureEnabled;
  37381. },
  37382. set: function (value) {
  37383. if (StandardMaterial._LightmapTextureEnabled === value) {
  37384. return;
  37385. }
  37386. StandardMaterial._LightmapTextureEnabled = value;
  37387. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  37388. },
  37389. enumerable: true,
  37390. configurable: true
  37391. });
  37392. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  37393. get: function () {
  37394. return StandardMaterial._RefractionTextureEnabled;
  37395. },
  37396. set: function (value) {
  37397. if (StandardMaterial._RefractionTextureEnabled === value) {
  37398. return;
  37399. }
  37400. StandardMaterial._RefractionTextureEnabled = value;
  37401. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  37402. },
  37403. enumerable: true,
  37404. configurable: true
  37405. });
  37406. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  37407. get: function () {
  37408. return StandardMaterial._ColorGradingTextureEnabled;
  37409. },
  37410. set: function (value) {
  37411. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  37412. return;
  37413. }
  37414. StandardMaterial._ColorGradingTextureEnabled = value;
  37415. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  37416. },
  37417. enumerable: true,
  37418. configurable: true
  37419. });
  37420. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  37421. get: function () {
  37422. return StandardMaterial._FresnelEnabled;
  37423. },
  37424. set: function (value) {
  37425. if (StandardMaterial._FresnelEnabled === value) {
  37426. return;
  37427. }
  37428. StandardMaterial._FresnelEnabled = value;
  37429. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  37430. },
  37431. enumerable: true,
  37432. configurable: true
  37433. });
  37434. // Flags used to enable or disable a type of texture for all Standard Materials
  37435. StandardMaterial._DiffuseTextureEnabled = true;
  37436. StandardMaterial._AmbientTextureEnabled = true;
  37437. StandardMaterial._OpacityTextureEnabled = true;
  37438. StandardMaterial._ReflectionTextureEnabled = true;
  37439. StandardMaterial._EmissiveTextureEnabled = true;
  37440. StandardMaterial._SpecularTextureEnabled = true;
  37441. StandardMaterial._BumpTextureEnabled = true;
  37442. StandardMaterial._LightmapTextureEnabled = true;
  37443. StandardMaterial._RefractionTextureEnabled = true;
  37444. StandardMaterial._ColorGradingTextureEnabled = true;
  37445. StandardMaterial._FresnelEnabled = true;
  37446. __decorate([
  37447. BABYLON.serializeAsTexture("diffuseTexture")
  37448. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  37449. __decorate([
  37450. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  37451. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  37452. __decorate([
  37453. BABYLON.serializeAsTexture("ambientTexture")
  37454. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  37455. __decorate([
  37456. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37457. ], StandardMaterial.prototype, "ambientTexture", void 0);
  37458. __decorate([
  37459. BABYLON.serializeAsTexture("opacityTexture")
  37460. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  37461. __decorate([
  37462. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  37463. ], StandardMaterial.prototype, "opacityTexture", void 0);
  37464. __decorate([
  37465. BABYLON.serializeAsTexture("reflectionTexture")
  37466. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  37467. __decorate([
  37468. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37469. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  37470. __decorate([
  37471. BABYLON.serializeAsTexture("emissiveTexture")
  37472. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  37473. __decorate([
  37474. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37475. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  37476. __decorate([
  37477. BABYLON.serializeAsTexture("specularTexture")
  37478. ], StandardMaterial.prototype, "_specularTexture", void 0);
  37479. __decorate([
  37480. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37481. ], StandardMaterial.prototype, "specularTexture", void 0);
  37482. __decorate([
  37483. BABYLON.serializeAsTexture("bumpTexture")
  37484. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  37485. __decorate([
  37486. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37487. ], StandardMaterial.prototype, "bumpTexture", void 0);
  37488. __decorate([
  37489. BABYLON.serializeAsTexture("lightmapTexture")
  37490. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  37491. __decorate([
  37492. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37493. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  37494. __decorate([
  37495. BABYLON.serializeAsTexture("refractionTexture")
  37496. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  37497. __decorate([
  37498. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37499. ], StandardMaterial.prototype, "refractionTexture", void 0);
  37500. __decorate([
  37501. BABYLON.serializeAsColor3("ambient")
  37502. ], StandardMaterial.prototype, "ambientColor", void 0);
  37503. __decorate([
  37504. BABYLON.serializeAsColor3("diffuse")
  37505. ], StandardMaterial.prototype, "diffuseColor", void 0);
  37506. __decorate([
  37507. BABYLON.serializeAsColor3("specular")
  37508. ], StandardMaterial.prototype, "specularColor", void 0);
  37509. __decorate([
  37510. BABYLON.serializeAsColor3("emissive")
  37511. ], StandardMaterial.prototype, "emissiveColor", void 0);
  37512. __decorate([
  37513. BABYLON.serialize()
  37514. ], StandardMaterial.prototype, "specularPower", void 0);
  37515. __decorate([
  37516. BABYLON.serialize("useAlphaFromDiffuseTexture")
  37517. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  37518. __decorate([
  37519. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37520. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  37521. __decorate([
  37522. BABYLON.serialize("useEmissiveAsIllumination")
  37523. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  37524. __decorate([
  37525. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37526. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  37527. __decorate([
  37528. BABYLON.serialize("linkEmissiveWithDiffuse")
  37529. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  37530. __decorate([
  37531. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37532. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  37533. __decorate([
  37534. BABYLON.serialize("useSpecularOverAlpha")
  37535. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  37536. __decorate([
  37537. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37538. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  37539. __decorate([
  37540. BABYLON.serialize("useReflectionOverAlpha")
  37541. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  37542. __decorate([
  37543. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37544. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  37545. __decorate([
  37546. BABYLON.serialize("disableLighting")
  37547. ], StandardMaterial.prototype, "_disableLighting", void 0);
  37548. __decorate([
  37549. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  37550. ], StandardMaterial.prototype, "disableLighting", void 0);
  37551. __decorate([
  37552. BABYLON.serialize("useParallax")
  37553. ], StandardMaterial.prototype, "_useParallax", void 0);
  37554. __decorate([
  37555. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37556. ], StandardMaterial.prototype, "useParallax", void 0);
  37557. __decorate([
  37558. BABYLON.serialize("useParallaxOcclusion")
  37559. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  37560. __decorate([
  37561. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37562. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  37563. __decorate([
  37564. BABYLON.serialize()
  37565. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  37566. __decorate([
  37567. BABYLON.serialize("roughness")
  37568. ], StandardMaterial.prototype, "_roughness", void 0);
  37569. __decorate([
  37570. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37571. ], StandardMaterial.prototype, "roughness", void 0);
  37572. __decorate([
  37573. BABYLON.serialize()
  37574. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  37575. __decorate([
  37576. BABYLON.serialize()
  37577. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  37578. __decorate([
  37579. BABYLON.serialize("useLightmapAsShadowmap")
  37580. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  37581. __decorate([
  37582. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37583. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  37584. __decorate([
  37585. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  37586. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  37587. __decorate([
  37588. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  37589. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  37590. __decorate([
  37591. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  37592. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  37593. __decorate([
  37594. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelAndMiscDirty")
  37595. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  37596. __decorate([
  37597. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  37598. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  37599. __decorate([
  37600. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  37601. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  37602. __decorate([
  37603. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  37604. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  37605. __decorate([
  37606. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  37607. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  37608. __decorate([
  37609. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  37610. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  37611. __decorate([
  37612. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  37613. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  37614. __decorate([
  37615. BABYLON.serialize("useReflectionFresnelFromSpecular")
  37616. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  37617. __decorate([
  37618. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  37619. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  37620. __decorate([
  37621. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  37622. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  37623. __decorate([
  37624. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37625. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  37626. __decorate([
  37627. BABYLON.serialize("maxSimultaneousLights")
  37628. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  37629. __decorate([
  37630. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  37631. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  37632. __decorate([
  37633. BABYLON.serialize("invertNormalMapX")
  37634. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  37635. __decorate([
  37636. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37637. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  37638. __decorate([
  37639. BABYLON.serialize("invertNormalMapY")
  37640. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  37641. __decorate([
  37642. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37643. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  37644. __decorate([
  37645. BABYLON.serialize("twoSidedLighting")
  37646. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  37647. __decorate([
  37648. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37649. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  37650. __decorate([
  37651. BABYLON.serialize()
  37652. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  37653. return StandardMaterial;
  37654. }(BABYLON.PushMaterial));
  37655. BABYLON.StandardMaterial = StandardMaterial;
  37656. })(BABYLON || (BABYLON = {}));
  37657. //# sourceMappingURL=babylon.standardMaterial.js.map
  37658. var BABYLON;
  37659. (function (BABYLON) {
  37660. var PBRMaterialDefines = /** @class */ (function (_super) {
  37661. __extends(PBRMaterialDefines, _super);
  37662. function PBRMaterialDefines() {
  37663. var _this = _super.call(this) || this;
  37664. _this.PBR = true;
  37665. _this.MAINUV1 = false;
  37666. _this.MAINUV2 = false;
  37667. _this.UV1 = false;
  37668. _this.UV2 = false;
  37669. _this.ALBEDO = false;
  37670. _this.ALBEDODIRECTUV = 0;
  37671. _this.VERTEXCOLOR = false;
  37672. _this.AMBIENT = false;
  37673. _this.AMBIENTDIRECTUV = 0;
  37674. _this.AMBIENTINGRAYSCALE = false;
  37675. _this.OPACITY = false;
  37676. _this.VERTEXALPHA = false;
  37677. _this.OPACITYDIRECTUV = 0;
  37678. _this.OPACITYRGB = false;
  37679. _this.ALPHATEST = false;
  37680. _this.DEPTHPREPASS = false;
  37681. _this.ALPHABLEND = false;
  37682. _this.ALPHAFROMALBEDO = false;
  37683. _this.ALPHATESTVALUE = 0.5;
  37684. _this.SPECULAROVERALPHA = false;
  37685. _this.RADIANCEOVERALPHA = false;
  37686. _this.ALPHAFRESNEL = false;
  37687. _this.LINEARALPHAFRESNEL = false;
  37688. _this.PREMULTIPLYALPHA = false;
  37689. _this.EMISSIVE = false;
  37690. _this.EMISSIVEDIRECTUV = 0;
  37691. _this.REFLECTIVITY = false;
  37692. _this.REFLECTIVITYDIRECTUV = 0;
  37693. _this.SPECULARTERM = false;
  37694. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  37695. _this.MICROSURFACEAUTOMATIC = false;
  37696. _this.LODBASEDMICROSFURACE = false;
  37697. _this.MICROSURFACEMAP = false;
  37698. _this.MICROSURFACEMAPDIRECTUV = 0;
  37699. _this.METALLICWORKFLOW = false;
  37700. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  37701. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  37702. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  37703. _this.AOSTOREINMETALMAPRED = false;
  37704. _this.ENVIRONMENTBRDF = false;
  37705. _this.NORMAL = false;
  37706. _this.TANGENT = false;
  37707. _this.BUMP = false;
  37708. _this.BUMPDIRECTUV = 0;
  37709. _this.PARALLAX = false;
  37710. _this.PARALLAXOCCLUSION = false;
  37711. _this.NORMALXYSCALE = true;
  37712. _this.LIGHTMAP = false;
  37713. _this.LIGHTMAPDIRECTUV = 0;
  37714. _this.USELIGHTMAPASSHADOWMAP = false;
  37715. _this.REFLECTION = false;
  37716. _this.REFLECTIONMAP_3D = false;
  37717. _this.REFLECTIONMAP_SPHERICAL = false;
  37718. _this.REFLECTIONMAP_PLANAR = false;
  37719. _this.REFLECTIONMAP_CUBIC = false;
  37720. _this.REFLECTIONMAP_PROJECTION = false;
  37721. _this.REFLECTIONMAP_SKYBOX = false;
  37722. _this.REFLECTIONMAP_EXPLICIT = false;
  37723. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  37724. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  37725. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  37726. _this.INVERTCUBICMAP = false;
  37727. _this.USESPHERICALFROMREFLECTIONMAP = false;
  37728. _this.USESPHERICALINVERTEX = false;
  37729. _this.REFLECTIONMAP_OPPOSITEZ = false;
  37730. _this.LODINREFLECTIONALPHA = false;
  37731. _this.GAMMAREFLECTION = false;
  37732. _this.RADIANCEOCCLUSION = false;
  37733. _this.HORIZONOCCLUSION = false;
  37734. _this.REFRACTION = false;
  37735. _this.REFRACTIONMAP_3D = false;
  37736. _this.REFRACTIONMAP_OPPOSITEZ = false;
  37737. _this.LODINREFRACTIONALPHA = false;
  37738. _this.GAMMAREFRACTION = false;
  37739. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  37740. _this.INSTANCES = false;
  37741. _this.NUM_BONE_INFLUENCERS = 0;
  37742. _this.BonesPerMesh = 0;
  37743. _this.NONUNIFORMSCALING = false;
  37744. _this.MORPHTARGETS = false;
  37745. _this.MORPHTARGETS_NORMAL = false;
  37746. _this.MORPHTARGETS_TANGENT = false;
  37747. _this.NUM_MORPH_INFLUENCERS = 0;
  37748. _this.IMAGEPROCESSING = false;
  37749. _this.VIGNETTE = false;
  37750. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  37751. _this.VIGNETTEBLENDMODEOPAQUE = false;
  37752. _this.TONEMAPPING = false;
  37753. _this.CONTRAST = false;
  37754. _this.COLORCURVES = false;
  37755. _this.COLORGRADING = false;
  37756. _this.COLORGRADING3D = false;
  37757. _this.SAMPLER3DGREENDEPTH = false;
  37758. _this.SAMPLER3DBGRMAP = false;
  37759. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  37760. _this.EXPOSURE = false;
  37761. _this.USEPHYSICALLIGHTFALLOFF = false;
  37762. _this.TWOSIDEDLIGHTING = false;
  37763. _this.SHADOWFLOAT = false;
  37764. _this.CLIPPLANE = false;
  37765. _this.POINTSIZE = false;
  37766. _this.FOG = false;
  37767. _this.LOGARITHMICDEPTH = false;
  37768. _this.FORCENORMALFORWARD = false;
  37769. _this.rebuild();
  37770. return _this;
  37771. }
  37772. PBRMaterialDefines.prototype.reset = function () {
  37773. _super.prototype.reset.call(this);
  37774. this.ALPHATESTVALUE = 0.5;
  37775. this.PBR = true;
  37776. };
  37777. return PBRMaterialDefines;
  37778. }(BABYLON.MaterialDefines));
  37779. /**
  37780. * The Physically based material base class of BJS.
  37781. *
  37782. * This offers the main features of a standard PBR material.
  37783. * For more information, please refer to the documentation :
  37784. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  37785. */
  37786. var PBRBaseMaterial = /** @class */ (function (_super) {
  37787. __extends(PBRBaseMaterial, _super);
  37788. /**
  37789. * Instantiates a new PBRMaterial instance.
  37790. *
  37791. * @param name The material name
  37792. * @param scene The scene the material will be use in.
  37793. */
  37794. function PBRBaseMaterial(name, scene) {
  37795. var _this = _super.call(this, name, scene) || this;
  37796. /**
  37797. * Intensity of the direct lights e.g. the four lights available in your scene.
  37798. * This impacts both the direct diffuse and specular highlights.
  37799. */
  37800. _this._directIntensity = 1.0;
  37801. /**
  37802. * Intensity of the emissive part of the material.
  37803. * This helps controlling the emissive effect without modifying the emissive color.
  37804. */
  37805. _this._emissiveIntensity = 1.0;
  37806. /**
  37807. * Intensity of the environment e.g. how much the environment will light the object
  37808. * either through harmonics for rough material or through the refelction for shiny ones.
  37809. */
  37810. _this._environmentIntensity = 1.0;
  37811. /**
  37812. * This is a special control allowing the reduction of the specular highlights coming from the
  37813. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  37814. */
  37815. _this._specularIntensity = 1.0;
  37816. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  37817. /**
  37818. * Debug Control allowing disabling the bump map on this material.
  37819. */
  37820. _this._disableBumpMap = false;
  37821. /**
  37822. * AKA Occlusion Texture Intensity in other nomenclature.
  37823. */
  37824. _this._ambientTextureStrength = 1.0;
  37825. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  37826. /**
  37827. * AKA Diffuse Color in other nomenclature.
  37828. */
  37829. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  37830. /**
  37831. * AKA Specular Color in other nomenclature.
  37832. */
  37833. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  37834. _this._reflectionColor = new BABYLON.Color3(1, 1, 1);
  37835. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  37836. /**
  37837. * AKA Glossiness in other nomenclature.
  37838. */
  37839. _this._microSurface = 0.9;
  37840. /**
  37841. * source material index of refraction (IOR)' / 'destination material IOR.
  37842. */
  37843. _this._indexOfRefraction = 0.66;
  37844. /**
  37845. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  37846. */
  37847. _this._invertRefractionY = false;
  37848. /**
  37849. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  37850. * Materials half opaque for instance using refraction could benefit from this control.
  37851. */
  37852. _this._linkRefractionWithTransparency = false;
  37853. _this._useLightmapAsShadowmap = false;
  37854. /**
  37855. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  37856. * makes the reflect vector face the model (under horizon).
  37857. */
  37858. _this._useHorizonOcclusion = true;
  37859. /**
  37860. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  37861. * too much the area relying on ambient texture to define their ambient occlusion.
  37862. */
  37863. _this._useRadianceOcclusion = true;
  37864. /**
  37865. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  37866. */
  37867. _this._useAlphaFromAlbedoTexture = false;
  37868. /**
  37869. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  37870. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  37871. */
  37872. _this._useSpecularOverAlpha = true;
  37873. /**
  37874. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  37875. */
  37876. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  37877. /**
  37878. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  37879. */
  37880. _this._useRoughnessFromMetallicTextureAlpha = true;
  37881. /**
  37882. * Specifies if the metallic texture contains the roughness information in its green channel.
  37883. */
  37884. _this._useRoughnessFromMetallicTextureGreen = false;
  37885. /**
  37886. * Specifies if the metallic texture contains the metallness information in its blue channel.
  37887. */
  37888. _this._useMetallnessFromMetallicTextureBlue = false;
  37889. /**
  37890. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  37891. */
  37892. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  37893. /**
  37894. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  37895. */
  37896. _this._useAmbientInGrayScale = false;
  37897. /**
  37898. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  37899. * The material will try to infer what glossiness each pixel should be.
  37900. */
  37901. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  37902. /**
  37903. * BJS is using an harcoded light falloff based on a manually sets up range.
  37904. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  37905. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  37906. */
  37907. _this._usePhysicalLightFalloff = true;
  37908. /**
  37909. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  37910. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  37911. */
  37912. _this._useRadianceOverAlpha = true;
  37913. /**
  37914. * Allows using the bump map in parallax mode.
  37915. */
  37916. _this._useParallax = false;
  37917. /**
  37918. * Allows using the bump map in parallax occlusion mode.
  37919. */
  37920. _this._useParallaxOcclusion = false;
  37921. /**
  37922. * Controls the scale bias of the parallax mode.
  37923. */
  37924. _this._parallaxScaleBias = 0.05;
  37925. /**
  37926. * If sets to true, disables all the lights affecting the material.
  37927. */
  37928. _this._disableLighting = false;
  37929. /**
  37930. * Number of Simultaneous lights allowed on the material.
  37931. */
  37932. _this._maxSimultaneousLights = 4;
  37933. /**
  37934. * If sets to true, x component of normal map value will be inverted (x = 1.0 - x).
  37935. */
  37936. _this._invertNormalMapX = false;
  37937. /**
  37938. * If sets to true, y component of normal map value will be inverted (y = 1.0 - y).
  37939. */
  37940. _this._invertNormalMapY = false;
  37941. /**
  37942. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  37943. */
  37944. _this._twoSidedLighting = false;
  37945. /**
  37946. * Defines the alpha limits in alpha test mode.
  37947. */
  37948. _this._alphaCutOff = 0.4;
  37949. /**
  37950. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  37951. */
  37952. _this._forceAlphaTest = false;
  37953. /**
  37954. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  37955. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  37956. */
  37957. _this._useAlphaFresnel = false;
  37958. /**
  37959. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  37960. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  37961. */
  37962. _this._useLinearAlphaFresnel = false;
  37963. /**
  37964. * The transparency mode of the material.
  37965. */
  37966. _this._transparencyMode = null;
  37967. /**
  37968. * Specifies the environment BRDF texture used to comput the scale and offset roughness values
  37969. * from cos thetav and roughness:
  37970. * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
  37971. */
  37972. _this._environmentBRDFTexture = null;
  37973. /**
  37974. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  37975. */
  37976. _this._forceIrradianceInFragment = false;
  37977. /**
  37978. * Force normal to face away from face.
  37979. */
  37980. _this._forceNormalForward = false;
  37981. /**
  37982. * Force metallic workflow.
  37983. */
  37984. _this._forceMetallicWorkflow = false;
  37985. _this._renderTargets = new BABYLON.SmartArray(16);
  37986. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  37987. // Setup the default processing configuration to the scene.
  37988. _this._attachImageProcessingConfiguration(null);
  37989. _this.getRenderTargetTextures = function () {
  37990. _this._renderTargets.reset();
  37991. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  37992. _this._renderTargets.push(_this._reflectionTexture);
  37993. }
  37994. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  37995. _this._renderTargets.push(_this._refractionTexture);
  37996. }
  37997. return _this._renderTargets;
  37998. };
  37999. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  38000. return _this;
  38001. }
  38002. /**
  38003. * Attaches a new image processing configuration to the PBR Material.
  38004. * @param configuration
  38005. */
  38006. PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  38007. var _this = this;
  38008. if (configuration === this._imageProcessingConfiguration) {
  38009. return;
  38010. }
  38011. // Detaches observer.
  38012. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  38013. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  38014. }
  38015. // Pick the scene configuration if needed.
  38016. if (!configuration) {
  38017. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  38018. }
  38019. else {
  38020. this._imageProcessingConfiguration = configuration;
  38021. }
  38022. // Attaches observer.
  38023. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  38024. _this._markAllSubMeshesAsImageProcessingDirty();
  38025. });
  38026. };
  38027. PBRBaseMaterial.prototype.getClassName = function () {
  38028. return "PBRBaseMaterial";
  38029. };
  38030. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  38031. get: function () {
  38032. return this._useLogarithmicDepth;
  38033. },
  38034. set: function (value) {
  38035. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  38036. },
  38037. enumerable: true,
  38038. configurable: true
  38039. });
  38040. Object.defineProperty(PBRBaseMaterial.prototype, "transparencyMode", {
  38041. /**
  38042. * Gets the current transparency mode.
  38043. */
  38044. get: function () {
  38045. return this._transparencyMode;
  38046. },
  38047. /**
  38048. * Sets the transparency mode of the material.
  38049. */
  38050. set: function (value) {
  38051. if (this._transparencyMode === value) {
  38052. return;
  38053. }
  38054. this._transparencyMode = value;
  38055. this._forceAlphaTest = (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND);
  38056. this._markAllSubMeshesAsTexturesAndMiscDirty();
  38057. },
  38058. enumerable: true,
  38059. configurable: true
  38060. });
  38061. Object.defineProperty(PBRBaseMaterial.prototype, "_disableAlphaBlending", {
  38062. /**
  38063. * Returns true if alpha blending should be disabled.
  38064. */
  38065. get: function () {
  38066. return (this._linkRefractionWithTransparency ||
  38067. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE ||
  38068. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  38069. },
  38070. enumerable: true,
  38071. configurable: true
  38072. });
  38073. /**
  38074. * Specifies whether or not this material should be rendered in alpha blend mode.
  38075. */
  38076. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  38077. if (this._disableAlphaBlending) {
  38078. return false;
  38079. }
  38080. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  38081. };
  38082. /**
  38083. * Specifies whether or not this material should be rendered in alpha blend mode for the given mesh.
  38084. */
  38085. PBRBaseMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  38086. if (this._disableAlphaBlending) {
  38087. return false;
  38088. }
  38089. return _super.prototype.needAlphaBlendingForMesh.call(this, mesh);
  38090. };
  38091. /**
  38092. * Specifies whether or not this material should be rendered in alpha test mode.
  38093. */
  38094. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  38095. if (this._forceAlphaTest) {
  38096. return true;
  38097. }
  38098. if (this._linkRefractionWithTransparency) {
  38099. return false;
  38100. }
  38101. return this._albedoTexture != null && this._albedoTexture.hasAlpha && (this._transparencyMode == null || this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  38102. };
  38103. /**
  38104. * Specifies whether or not the alpha value of the albedo texture should be used for alpha blending.
  38105. */
  38106. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  38107. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  38108. };
  38109. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  38110. return this._albedoTexture;
  38111. };
  38112. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  38113. var _this = this;
  38114. if (subMesh.effect && this.isFrozen) {
  38115. if (this._wasPreviouslyReady) {
  38116. return true;
  38117. }
  38118. }
  38119. if (!subMesh._materialDefines) {
  38120. subMesh._materialDefines = new PBRMaterialDefines();
  38121. }
  38122. var scene = this.getScene();
  38123. var defines = subMesh._materialDefines;
  38124. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  38125. if (defines._renderId === scene.getRenderId()) {
  38126. return true;
  38127. }
  38128. }
  38129. var engine = scene.getEngine();
  38130. // Lights
  38131. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  38132. defines._needNormals = true;
  38133. // Textures
  38134. if (defines._areTexturesDirty) {
  38135. defines._needUVs = false;
  38136. if (scene.texturesEnabled) {
  38137. if (scene.getEngine().getCaps().textureLOD) {
  38138. defines.LODBASEDMICROSFURACE = true;
  38139. }
  38140. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  38141. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  38142. return false;
  38143. }
  38144. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
  38145. }
  38146. else {
  38147. defines.ALBEDO = false;
  38148. }
  38149. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  38150. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  38151. return false;
  38152. }
  38153. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  38154. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  38155. }
  38156. else {
  38157. defines.AMBIENT = false;
  38158. }
  38159. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  38160. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  38161. return false;
  38162. }
  38163. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  38164. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  38165. }
  38166. else {
  38167. defines.OPACITY = false;
  38168. }
  38169. var reflectionTexture = this._getReflectionTexture();
  38170. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  38171. if (!reflectionTexture.isReadyOrNotBlocking()) {
  38172. return false;
  38173. }
  38174. defines.REFLECTION = true;
  38175. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  38176. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  38177. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  38178. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  38179. defines.INVERTCUBICMAP = true;
  38180. }
  38181. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  38182. switch (reflectionTexture.coordinatesMode) {
  38183. case BABYLON.Texture.CUBIC_MODE:
  38184. case BABYLON.Texture.INVCUBIC_MODE:
  38185. defines.REFLECTIONMAP_CUBIC = true;
  38186. break;
  38187. case BABYLON.Texture.EXPLICIT_MODE:
  38188. defines.REFLECTIONMAP_EXPLICIT = true;
  38189. break;
  38190. case BABYLON.Texture.PLANAR_MODE:
  38191. defines.REFLECTIONMAP_PLANAR = true;
  38192. break;
  38193. case BABYLON.Texture.PROJECTION_MODE:
  38194. defines.REFLECTIONMAP_PROJECTION = true;
  38195. break;
  38196. case BABYLON.Texture.SKYBOX_MODE:
  38197. defines.REFLECTIONMAP_SKYBOX = true;
  38198. break;
  38199. case BABYLON.Texture.SPHERICAL_MODE:
  38200. defines.REFLECTIONMAP_SPHERICAL = true;
  38201. break;
  38202. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  38203. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  38204. break;
  38205. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  38206. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  38207. break;
  38208. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  38209. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  38210. break;
  38211. }
  38212. if (reflectionTexture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) {
  38213. if (reflectionTexture.sphericalPolynomial) {
  38214. defines.USESPHERICALFROMREFLECTIONMAP = true;
  38215. if (this._forceIrradianceInFragment || scene.getEngine().getCaps().maxVaryingVectors <= 8) {
  38216. defines.USESPHERICALINVERTEX = false;
  38217. }
  38218. else {
  38219. defines.USESPHERICALINVERTEX = true;
  38220. }
  38221. }
  38222. }
  38223. }
  38224. else {
  38225. defines.REFLECTION = false;
  38226. defines.REFLECTIONMAP_3D = false;
  38227. defines.REFLECTIONMAP_SPHERICAL = false;
  38228. defines.REFLECTIONMAP_PLANAR = false;
  38229. defines.REFLECTIONMAP_CUBIC = false;
  38230. defines.REFLECTIONMAP_PROJECTION = false;
  38231. defines.REFLECTIONMAP_SKYBOX = false;
  38232. defines.REFLECTIONMAP_EXPLICIT = false;
  38233. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  38234. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  38235. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  38236. defines.INVERTCUBICMAP = false;
  38237. defines.USESPHERICALFROMREFLECTIONMAP = false;
  38238. defines.USESPHERICALINVERTEX = false;
  38239. defines.REFLECTIONMAP_OPPOSITEZ = false;
  38240. defines.LODINREFLECTIONALPHA = false;
  38241. defines.GAMMAREFLECTION = false;
  38242. }
  38243. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  38244. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  38245. return false;
  38246. }
  38247. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  38248. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  38249. }
  38250. else {
  38251. defines.LIGHTMAP = false;
  38252. }
  38253. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  38254. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  38255. return false;
  38256. }
  38257. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  38258. }
  38259. else {
  38260. defines.EMISSIVE = false;
  38261. }
  38262. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  38263. if (this._metallicTexture) {
  38264. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  38265. return false;
  38266. }
  38267. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
  38268. defines.METALLICWORKFLOW = true;
  38269. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  38270. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  38271. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  38272. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  38273. }
  38274. else if (this._reflectivityTexture) {
  38275. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  38276. return false;
  38277. }
  38278. defines.METALLICWORKFLOW = false;
  38279. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
  38280. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  38281. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  38282. }
  38283. else {
  38284. defines.METALLICWORKFLOW = false;
  38285. defines.REFLECTIVITY = false;
  38286. }
  38287. if (this._microSurfaceTexture) {
  38288. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  38289. return false;
  38290. }
  38291. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
  38292. }
  38293. else {
  38294. defines.MICROSURFACEMAP = false;
  38295. }
  38296. }
  38297. else {
  38298. defines.REFLECTIVITY = false;
  38299. defines.MICROSURFACEMAP = false;
  38300. }
  38301. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  38302. // Bump texure can not be none blocking.
  38303. if (!this._bumpTexture.isReady()) {
  38304. return false;
  38305. }
  38306. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  38307. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  38308. defines.PARALLAX = true;
  38309. defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;
  38310. }
  38311. else {
  38312. defines.PARALLAX = false;
  38313. }
  38314. }
  38315. else {
  38316. defines.BUMP = false;
  38317. }
  38318. var refractionTexture = this._getRefractionTexture();
  38319. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  38320. if (!refractionTexture.isReadyOrNotBlocking()) {
  38321. return false;
  38322. }
  38323. defines.REFRACTION = true;
  38324. defines.REFRACTIONMAP_3D = refractionTexture.isCube;
  38325. defines.GAMMAREFRACTION = refractionTexture.gammaSpace;
  38326. defines.REFRACTIONMAP_OPPOSITEZ = refractionTexture.invertZ;
  38327. defines.LODINREFRACTIONALPHA = refractionTexture.lodLevelInAlpha;
  38328. if (this._linkRefractionWithTransparency) {
  38329. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  38330. }
  38331. }
  38332. else {
  38333. defines.REFRACTION = false;
  38334. }
  38335. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  38336. // This is blocking.
  38337. if (!this._environmentBRDFTexture.isReady()) {
  38338. return false;
  38339. }
  38340. defines.ENVIRONMENTBRDF = true;
  38341. }
  38342. else {
  38343. defines.ENVIRONMENTBRDF = false;
  38344. }
  38345. if (this._shouldUseAlphaFromAlbedoTexture()) {
  38346. defines.ALPHAFROMALBEDO = true;
  38347. }
  38348. else {
  38349. defines.ALPHAFROMALBEDO = false;
  38350. }
  38351. }
  38352. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  38353. defines.USEPHYSICALLIGHTFALLOFF = this._usePhysicalLightFalloff;
  38354. defines.RADIANCEOVERALPHA = this._useRadianceOverAlpha;
  38355. if (this._forceMetallicWorkflow || (this._metallic !== undefined && this._metallic !== null) || (this._roughness !== undefined && this._roughness !== null)) {
  38356. defines.METALLICWORKFLOW = true;
  38357. }
  38358. else {
  38359. defines.METALLICWORKFLOW = false;
  38360. }
  38361. if (!this.backFaceCulling && this._twoSidedLighting) {
  38362. defines.TWOSIDEDLIGHTING = true;
  38363. }
  38364. else {
  38365. defines.TWOSIDEDLIGHTING = false;
  38366. }
  38367. defines.ALPHATESTVALUE = this._alphaCutOff;
  38368. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  38369. defines.ALPHABLEND = this.needAlphaBlendingForMesh(mesh);
  38370. defines.ALPHAFRESNEL = this._useAlphaFresnel || this._useLinearAlphaFresnel;
  38371. defines.LINEARALPHAFRESNEL = this._useLinearAlphaFresnel;
  38372. }
  38373. if (defines._areImageProcessingDirty) {
  38374. if (!this._imageProcessingConfiguration.isReady()) {
  38375. return false;
  38376. }
  38377. this._imageProcessingConfiguration.prepareDefines(defines);
  38378. }
  38379. defines.FORCENORMALFORWARD = this._forceNormalForward;
  38380. defines.RADIANCEOCCLUSION = this._useRadianceOcclusion;
  38381. defines.HORIZONOCCLUSION = this._useHorizonOcclusion;
  38382. // Misc.
  38383. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh) || this._forceAlphaTest, defines);
  38384. // Values that need to be evaluated on every frame
  38385. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances ? true : false);
  38386. // Attribs
  38387. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true, this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE) && mesh) {
  38388. var bufferMesh = null;
  38389. if (mesh instanceof BABYLON.InstancedMesh) {
  38390. bufferMesh = mesh.sourceMesh;
  38391. }
  38392. else if (mesh instanceof BABYLON.Mesh) {
  38393. bufferMesh = mesh;
  38394. }
  38395. if (bufferMesh) {
  38396. if (bufferMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  38397. // If the first normal's components is the zero vector in one of the submeshes, we have invalid normals
  38398. var normalVertexBuffer = bufferMesh.getVertexBuffer(BABYLON.VertexBuffer.NormalKind);
  38399. var normals = normalVertexBuffer.getData();
  38400. var vertexBufferOffset = normalVertexBuffer.getOffset();
  38401. var strideSize = normalVertexBuffer.getStrideSize();
  38402. var offset = vertexBufferOffset + subMesh.indexStart * strideSize;
  38403. if (normals[offset] === 0 && normals[offset + 1] === 0 && normals[offset + 2] === 0) {
  38404. defines.NORMAL = false;
  38405. }
  38406. if (bufferMesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  38407. // If the first tangent's components is the zero vector in one of the submeshes, we have invalid tangents
  38408. var tangentVertexBuffer = bufferMesh.getVertexBuffer(BABYLON.VertexBuffer.TangentKind);
  38409. var tangents = tangentVertexBuffer.getData();
  38410. var vertexBufferOffset_1 = tangentVertexBuffer.getOffset();
  38411. var strideSize_1 = tangentVertexBuffer.getStrideSize();
  38412. var offset_1 = vertexBufferOffset_1 + subMesh.indexStart * strideSize_1;
  38413. if (tangents[offset_1] === 0 && tangents[offset_1 + 1] === 0 && tangents[offset_1 + 2] === 0) {
  38414. defines.TANGENT = false;
  38415. }
  38416. }
  38417. }
  38418. else {
  38419. if (!scene.getEngine().getCaps().standardDerivatives) {
  38420. bufferMesh.createNormals(true);
  38421. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + bufferMesh.name);
  38422. }
  38423. }
  38424. }
  38425. }
  38426. // Get correct effect
  38427. if (defines.isDirty) {
  38428. defines.markAsProcessed();
  38429. scene.resetCachedMaterial();
  38430. // Fallbacks
  38431. var fallbacks = new BABYLON.EffectFallbacks();
  38432. var fallbackRank = 0;
  38433. if (defines.USESPHERICALINVERTEX) {
  38434. fallbacks.addFallback(fallbackRank++, "USESPHERICALINVERTEX");
  38435. }
  38436. if (defines.FOG) {
  38437. fallbacks.addFallback(fallbackRank, "FOG");
  38438. }
  38439. if (defines.POINTSIZE) {
  38440. fallbacks.addFallback(fallbackRank, "POINTSIZE");
  38441. }
  38442. if (defines.LOGARITHMICDEPTH) {
  38443. fallbacks.addFallback(fallbackRank, "LOGARITHMICDEPTH");
  38444. }
  38445. if (defines.PARALLAX) {
  38446. fallbacks.addFallback(fallbackRank, "PARALLAX");
  38447. }
  38448. if (defines.PARALLAXOCCLUSION) {
  38449. fallbacks.addFallback(fallbackRank++, "PARALLAXOCCLUSION");
  38450. }
  38451. if (defines.ENVIRONMENTBRDF) {
  38452. fallbacks.addFallback(fallbackRank++, "ENVIRONMENTBRDF");
  38453. }
  38454. if (defines.TANGENT) {
  38455. fallbacks.addFallback(fallbackRank++, "TANGENT");
  38456. }
  38457. if (defines.BUMP) {
  38458. fallbacks.addFallback(fallbackRank++, "BUMP");
  38459. }
  38460. fallbackRank = BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights, fallbackRank++);
  38461. if (defines.SPECULARTERM) {
  38462. fallbacks.addFallback(fallbackRank++, "SPECULARTERM");
  38463. }
  38464. if (defines.USESPHERICALFROMREFLECTIONMAP) {
  38465. fallbacks.addFallback(fallbackRank++, "USESPHERICALFROMREFLECTIONMAP");
  38466. }
  38467. if (defines.LIGHTMAP) {
  38468. fallbacks.addFallback(fallbackRank++, "LIGHTMAP");
  38469. }
  38470. if (defines.NORMAL) {
  38471. fallbacks.addFallback(fallbackRank++, "NORMAL");
  38472. }
  38473. if (defines.AMBIENT) {
  38474. fallbacks.addFallback(fallbackRank++, "AMBIENT");
  38475. }
  38476. if (defines.EMISSIVE) {
  38477. fallbacks.addFallback(fallbackRank++, "EMISSIVE");
  38478. }
  38479. if (defines.VERTEXCOLOR) {
  38480. fallbacks.addFallback(fallbackRank++, "VERTEXCOLOR");
  38481. }
  38482. if (defines.NUM_BONE_INFLUENCERS > 0) {
  38483. fallbacks.addCPUSkinningFallback(fallbackRank++, mesh);
  38484. }
  38485. if (defines.MORPHTARGETS) {
  38486. fallbacks.addFallback(fallbackRank++, "MORPHTARGETS");
  38487. }
  38488. //Attributes
  38489. var attribs = [BABYLON.VertexBuffer.PositionKind];
  38490. if (defines.NORMAL) {
  38491. attribs.push(BABYLON.VertexBuffer.NormalKind);
  38492. }
  38493. if (defines.TANGENT) {
  38494. attribs.push(BABYLON.VertexBuffer.TangentKind);
  38495. }
  38496. if (defines.UV1) {
  38497. attribs.push(BABYLON.VertexBuffer.UVKind);
  38498. }
  38499. if (defines.UV2) {
  38500. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  38501. }
  38502. if (defines.VERTEXCOLOR) {
  38503. attribs.push(BABYLON.VertexBuffer.ColorKind);
  38504. }
  38505. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  38506. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  38507. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  38508. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  38509. "vFogInfos", "vFogColor", "pointSize",
  38510. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vReflectivityInfos", "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  38511. "mBones",
  38512. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  38513. "vLightingIntensity",
  38514. "logarithmicDepthConstant",
  38515. "vSphericalX", "vSphericalY", "vSphericalZ",
  38516. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  38517. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  38518. "vReflectionMicrosurfaceInfos", "vRefractionMicrosurfaceInfos",
  38519. "vTangentSpaceParams"
  38520. ];
  38521. var samplers = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler",
  38522. "bumpSampler", "lightmapSampler", "opacitySampler",
  38523. "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh",
  38524. "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh",
  38525. "microSurfaceSampler", "environmentBrdfSampler"];
  38526. var uniformBuffers = ["Material", "Scene"];
  38527. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  38528. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  38529. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  38530. uniformsNames: uniforms,
  38531. uniformBuffersNames: uniformBuffers,
  38532. samplers: samplers,
  38533. defines: defines,
  38534. maxSimultaneousLights: this._maxSimultaneousLights
  38535. });
  38536. var onCompiled = function (effect) {
  38537. if (_this.onCompiled) {
  38538. _this.onCompiled(effect);
  38539. }
  38540. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  38541. };
  38542. var join = defines.toString();
  38543. subMesh.setEffect(scene.getEngine().createEffect("pbr", {
  38544. attributes: attribs,
  38545. uniformsNames: uniforms,
  38546. uniformBuffersNames: uniformBuffers,
  38547. samplers: samplers,
  38548. defines: join,
  38549. fallbacks: fallbacks,
  38550. onCompiled: onCompiled,
  38551. onError: this.onError,
  38552. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  38553. }, engine), defines);
  38554. this.buildUniformLayout();
  38555. }
  38556. if (!subMesh.effect || !subMesh.effect.isReady()) {
  38557. return false;
  38558. }
  38559. defines._renderId = scene.getRenderId();
  38560. this._wasPreviouslyReady = true;
  38561. return true;
  38562. };
  38563. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  38564. // Order is important !
  38565. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  38566. this._uniformBuffer.addUniform("vAmbientInfos", 3);
  38567. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  38568. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  38569. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  38570. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  38571. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  38572. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  38573. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  38574. this._uniformBuffer.addUniform("vBumpInfos", 3);
  38575. this._uniformBuffer.addUniform("albedoMatrix", 16);
  38576. this._uniformBuffer.addUniform("ambientMatrix", 16);
  38577. this._uniformBuffer.addUniform("opacityMatrix", 16);
  38578. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  38579. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  38580. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  38581. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  38582. this._uniformBuffer.addUniform("bumpMatrix", 16);
  38583. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  38584. this._uniformBuffer.addUniform("refractionMatrix", 16);
  38585. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  38586. this._uniformBuffer.addUniform("vReflectionColor", 3);
  38587. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  38588. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  38589. this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3);
  38590. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  38591. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  38592. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  38593. this._uniformBuffer.addUniform("pointSize", 1);
  38594. this._uniformBuffer.create();
  38595. };
  38596. PBRBaseMaterial.prototype.unbind = function () {
  38597. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  38598. this._uniformBuffer.setTexture("reflectionSampler", null);
  38599. }
  38600. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  38601. this._uniformBuffer.setTexture("refractionSampler", null);
  38602. }
  38603. _super.prototype.unbind.call(this);
  38604. };
  38605. PBRBaseMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  38606. this._activeEffect.setMatrix("world", world);
  38607. };
  38608. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  38609. var scene = this.getScene();
  38610. var defines = subMesh._materialDefines;
  38611. if (!defines) {
  38612. return;
  38613. }
  38614. var effect = subMesh.effect;
  38615. if (!effect) {
  38616. return;
  38617. }
  38618. this._activeEffect = effect;
  38619. // Matrices
  38620. this.bindOnlyWorldMatrix(world);
  38621. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  38622. // Bones
  38623. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  38624. var reflectionTexture = null;
  38625. if (mustRebind) {
  38626. this._uniformBuffer.bindToEffect(effect, "Material");
  38627. this.bindViewProjection(effect);
  38628. reflectionTexture = this._getReflectionTexture();
  38629. var refractionTexture = this._getRefractionTexture();
  38630. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  38631. // Texture uniforms
  38632. if (scene.texturesEnabled) {
  38633. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  38634. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  38635. BABYLON.MaterialHelper.BindTextureMatrix(this._albedoTexture, this._uniformBuffer, "albedo");
  38636. }
  38637. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  38638. this._uniformBuffer.updateFloat3("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength);
  38639. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  38640. }
  38641. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  38642. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  38643. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  38644. }
  38645. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  38646. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  38647. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  38648. var polynomials = reflectionTexture.sphericalPolynomial;
  38649. if (defines.USESPHERICALFROMREFLECTIONMAP && polynomials) {
  38650. this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
  38651. this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
  38652. this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
  38653. this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
  38654. this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
  38655. this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
  38656. this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
  38657. this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
  38658. this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
  38659. }
  38660. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  38661. }
  38662. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  38663. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  38664. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  38665. }
  38666. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  38667. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  38668. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  38669. }
  38670. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  38671. if (this._metallicTexture) {
  38672. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  38673. BABYLON.MaterialHelper.BindTextureMatrix(this._metallicTexture, this._uniformBuffer, "reflectivity");
  38674. }
  38675. else if (this._reflectivityTexture) {
  38676. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  38677. BABYLON.MaterialHelper.BindTextureMatrix(this._reflectivityTexture, this._uniformBuffer, "reflectivity");
  38678. }
  38679. if (this._microSurfaceTexture) {
  38680. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  38681. BABYLON.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, this._uniformBuffer, "microSurfaceSampler");
  38682. }
  38683. }
  38684. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  38685. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  38686. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  38687. if (scene._mirroredCameraPosition) {
  38688. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  38689. }
  38690. else {
  38691. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  38692. }
  38693. }
  38694. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  38695. this._uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix());
  38696. var depth = 1.0;
  38697. if (!refractionTexture.isCube) {
  38698. if (refractionTexture.depth) {
  38699. depth = refractionTexture.depth;
  38700. }
  38701. }
  38702. this._uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  38703. this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos", refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);
  38704. }
  38705. }
  38706. // Point size
  38707. if (this.pointsCloud) {
  38708. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  38709. }
  38710. // Colors
  38711. if (defines.METALLICWORKFLOW) {
  38712. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  38713. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  38714. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  38715. }
  38716. else {
  38717. this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  38718. }
  38719. this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
  38720. this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
  38721. this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
  38722. // Misc
  38723. this._lightingInfos.x = this._directIntensity;
  38724. this._lightingInfos.y = this._emissiveIntensity;
  38725. this._lightingInfos.z = this._environmentIntensity;
  38726. this._lightingInfos.w = this._specularIntensity;
  38727. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  38728. }
  38729. // Textures
  38730. if (scene.texturesEnabled) {
  38731. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  38732. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  38733. }
  38734. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  38735. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  38736. }
  38737. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  38738. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  38739. }
  38740. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  38741. if (defines.LODBASEDMICROSFURACE) {
  38742. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  38743. }
  38744. else {
  38745. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  38746. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  38747. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  38748. }
  38749. }
  38750. if (defines.ENVIRONMENTBRDF) {
  38751. this._uniformBuffer.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
  38752. }
  38753. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  38754. if (defines.LODBASEDMICROSFURACE) {
  38755. this._uniformBuffer.setTexture("refractionSampler", refractionTexture);
  38756. }
  38757. else {
  38758. this._uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
  38759. this._uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
  38760. this._uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
  38761. }
  38762. }
  38763. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  38764. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  38765. }
  38766. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  38767. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  38768. }
  38769. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  38770. if (this._metallicTexture) {
  38771. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  38772. }
  38773. else if (this._reflectivityTexture) {
  38774. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  38775. }
  38776. if (this._microSurfaceTexture) {
  38777. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  38778. }
  38779. }
  38780. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  38781. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  38782. }
  38783. }
  38784. // Clip plane
  38785. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  38786. // Colors
  38787. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  38788. var eyePosition = scene._forcedViewPosition ? scene._forcedViewPosition : (scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  38789. var invertNormal = (scene.useRightHandedSystem === (scene._mirroredCameraPosition != null));
  38790. effect.setFloat4("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z, invertNormal ? -1 : 1);
  38791. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  38792. }
  38793. if (mustRebind || !this.isFrozen) {
  38794. // Lights
  38795. if (scene.lightsEnabled && !this._disableLighting) {
  38796. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._usePhysicalLightFalloff);
  38797. }
  38798. // View
  38799. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  38800. this.bindView(effect);
  38801. }
  38802. // Fog
  38803. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  38804. // Morph targets
  38805. if (defines.NUM_MORPH_INFLUENCERS) {
  38806. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  38807. }
  38808. // image processing
  38809. this._imageProcessingConfiguration.bind(this._activeEffect);
  38810. // Log. depth
  38811. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  38812. }
  38813. this._uniformBuffer.update();
  38814. this._afterBind(mesh);
  38815. };
  38816. PBRBaseMaterial.prototype.getAnimatables = function () {
  38817. var results = [];
  38818. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  38819. results.push(this._albedoTexture);
  38820. }
  38821. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  38822. results.push(this._ambientTexture);
  38823. }
  38824. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  38825. results.push(this._opacityTexture);
  38826. }
  38827. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  38828. results.push(this._reflectionTexture);
  38829. }
  38830. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  38831. results.push(this._emissiveTexture);
  38832. }
  38833. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  38834. results.push(this._metallicTexture);
  38835. }
  38836. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  38837. results.push(this._reflectivityTexture);
  38838. }
  38839. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  38840. results.push(this._bumpTexture);
  38841. }
  38842. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  38843. results.push(this._lightmapTexture);
  38844. }
  38845. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  38846. results.push(this._refractionTexture);
  38847. }
  38848. return results;
  38849. };
  38850. PBRBaseMaterial.prototype._getReflectionTexture = function () {
  38851. if (this._reflectionTexture) {
  38852. return this._reflectionTexture;
  38853. }
  38854. return this.getScene().environmentTexture;
  38855. };
  38856. PBRBaseMaterial.prototype._getRefractionTexture = function () {
  38857. if (this._refractionTexture) {
  38858. return this._refractionTexture;
  38859. }
  38860. if (this._linkRefractionWithTransparency) {
  38861. return this.getScene().environmentTexture;
  38862. }
  38863. return null;
  38864. };
  38865. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  38866. if (forceDisposeTextures) {
  38867. if (this._albedoTexture) {
  38868. this._albedoTexture.dispose();
  38869. }
  38870. if (this._ambientTexture) {
  38871. this._ambientTexture.dispose();
  38872. }
  38873. if (this._opacityTexture) {
  38874. this._opacityTexture.dispose();
  38875. }
  38876. if (this._reflectionTexture) {
  38877. this._reflectionTexture.dispose();
  38878. }
  38879. if (this._environmentBRDFTexture && this.getScene()._environmentBRDFTexture !== this._environmentBRDFTexture) {
  38880. this._environmentBRDFTexture.dispose();
  38881. }
  38882. if (this._emissiveTexture) {
  38883. this._emissiveTexture.dispose();
  38884. }
  38885. if (this._metallicTexture) {
  38886. this._metallicTexture.dispose();
  38887. }
  38888. if (this._reflectivityTexture) {
  38889. this._reflectivityTexture.dispose();
  38890. }
  38891. if (this._bumpTexture) {
  38892. this._bumpTexture.dispose();
  38893. }
  38894. if (this._lightmapTexture) {
  38895. this._lightmapTexture.dispose();
  38896. }
  38897. if (this._refractionTexture) {
  38898. this._refractionTexture.dispose();
  38899. }
  38900. }
  38901. this._renderTargets.dispose();
  38902. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  38903. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  38904. }
  38905. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  38906. };
  38907. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  38908. __decorate([
  38909. BABYLON.serializeAsImageProcessingConfiguration()
  38910. ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
  38911. __decorate([
  38912. BABYLON.serialize()
  38913. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  38914. __decorate([
  38915. BABYLON.serialize()
  38916. ], PBRBaseMaterial.prototype, "transparencyMode", null);
  38917. return PBRBaseMaterial;
  38918. }(BABYLON.PushMaterial));
  38919. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  38920. })(BABYLON || (BABYLON = {}));
  38921. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  38922. var BABYLON;
  38923. (function (BABYLON) {
  38924. /**
  38925. * The Physically based simple base material of BJS.
  38926. *
  38927. * This enables better naming and convention enforcements on top of the pbrMaterial.
  38928. * It is used as the base class for both the specGloss and metalRough conventions.
  38929. */
  38930. var PBRBaseSimpleMaterial = /** @class */ (function (_super) {
  38931. __extends(PBRBaseSimpleMaterial, _super);
  38932. /**
  38933. * Instantiates a new PBRMaterial instance.
  38934. *
  38935. * @param name The material name
  38936. * @param scene The scene the material will be use in.
  38937. */
  38938. function PBRBaseSimpleMaterial(name, scene) {
  38939. var _this = _super.call(this, name, scene) || this;
  38940. /**
  38941. * Number of Simultaneous lights allowed on the material.
  38942. */
  38943. _this.maxSimultaneousLights = 4;
  38944. /**
  38945. * If sets to true, disables all the lights affecting the material.
  38946. */
  38947. _this.disableLighting = false;
  38948. /**
  38949. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  38950. */
  38951. _this.invertNormalMapX = false;
  38952. /**
  38953. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  38954. */
  38955. _this.invertNormalMapY = false;
  38956. /**
  38957. * Emissivie color used to self-illuminate the model.
  38958. */
  38959. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  38960. /**
  38961. * Occlusion Channel Strenght.
  38962. */
  38963. _this.occlusionStrength = 1.0;
  38964. _this.useLightmapAsShadowmap = false;
  38965. _this._useAlphaFromAlbedoTexture = true;
  38966. _this._useAmbientInGrayScale = true;
  38967. return _this;
  38968. }
  38969. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  38970. /**
  38971. * Gets the current double sided mode.
  38972. */
  38973. get: function () {
  38974. return this._twoSidedLighting;
  38975. },
  38976. /**
  38977. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  38978. */
  38979. set: function (value) {
  38980. if (this._twoSidedLighting === value) {
  38981. return;
  38982. }
  38983. this._twoSidedLighting = value;
  38984. this.backFaceCulling = !value;
  38985. this._markAllSubMeshesAsTexturesDirty();
  38986. },
  38987. enumerable: true,
  38988. configurable: true
  38989. });
  38990. /**
  38991. * Return the active textures of the material.
  38992. */
  38993. PBRBaseSimpleMaterial.prototype.getActiveTextures = function () {
  38994. var activeTextures = _super.prototype.getActiveTextures.call(this);
  38995. if (this.environmentTexture) {
  38996. activeTextures.push(this.environmentTexture);
  38997. }
  38998. if (this.normalTexture) {
  38999. activeTextures.push(this.normalTexture);
  39000. }
  39001. if (this.emissiveTexture) {
  39002. activeTextures.push(this.emissiveTexture);
  39003. }
  39004. if (this.occlusionTexture) {
  39005. activeTextures.push(this.occlusionTexture);
  39006. }
  39007. if (this.lightmapTexture) {
  39008. activeTextures.push(this.lightmapTexture);
  39009. }
  39010. return activeTextures;
  39011. };
  39012. PBRBaseSimpleMaterial.prototype.hasTexture = function (texture) {
  39013. if (_super.prototype.hasTexture.call(this, texture)) {
  39014. return true;
  39015. }
  39016. if (this.lightmapTexture === texture) {
  39017. return true;
  39018. }
  39019. return false;
  39020. };
  39021. PBRBaseSimpleMaterial.prototype.getClassName = function () {
  39022. return "PBRBaseSimpleMaterial";
  39023. };
  39024. __decorate([
  39025. BABYLON.serialize(),
  39026. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  39027. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  39028. __decorate([
  39029. BABYLON.serialize(),
  39030. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  39031. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  39032. __decorate([
  39033. BABYLON.serializeAsTexture(),
  39034. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  39035. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  39036. __decorate([
  39037. BABYLON.serialize(),
  39038. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39039. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  39040. __decorate([
  39041. BABYLON.serialize(),
  39042. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39043. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  39044. __decorate([
  39045. BABYLON.serializeAsTexture(),
  39046. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  39047. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  39048. __decorate([
  39049. BABYLON.serializeAsColor3("emissive"),
  39050. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39051. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  39052. __decorate([
  39053. BABYLON.serializeAsTexture(),
  39054. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39055. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  39056. __decorate([
  39057. BABYLON.serialize(),
  39058. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  39059. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  39060. __decorate([
  39061. BABYLON.serializeAsTexture(),
  39062. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  39063. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  39064. __decorate([
  39065. BABYLON.serialize(),
  39066. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  39067. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  39068. __decorate([
  39069. BABYLON.serialize()
  39070. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  39071. __decorate([
  39072. BABYLON.serializeAsTexture(),
  39073. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  39074. ], PBRBaseSimpleMaterial.prototype, "lightmapTexture", void 0);
  39075. __decorate([
  39076. BABYLON.serialize(),
  39077. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39078. ], PBRBaseSimpleMaterial.prototype, "useLightmapAsShadowmap", void 0);
  39079. return PBRBaseSimpleMaterial;
  39080. }(BABYLON.PBRBaseMaterial));
  39081. BABYLON.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  39082. })(BABYLON || (BABYLON = {}));
  39083. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  39084. var BABYLON;
  39085. (function (BABYLON) {
  39086. /**
  39087. * The Physically based material of BJS.
  39088. *
  39089. * This offers the main features of a standard PBR material.
  39090. * For more information, please refer to the documentation :
  39091. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  39092. */
  39093. var PBRMaterial = /** @class */ (function (_super) {
  39094. __extends(PBRMaterial, _super);
  39095. /**
  39096. * Instantiates a new PBRMaterial instance.
  39097. *
  39098. * @param name The material name
  39099. * @param scene The scene the material will be use in.
  39100. */
  39101. function PBRMaterial(name, scene) {
  39102. var _this = _super.call(this, name, scene) || this;
  39103. /**
  39104. * Intensity of the direct lights e.g. the four lights available in your scene.
  39105. * This impacts both the direct diffuse and specular highlights.
  39106. */
  39107. _this.directIntensity = 1.0;
  39108. /**
  39109. * Intensity of the emissive part of the material.
  39110. * This helps controlling the emissive effect without modifying the emissive color.
  39111. */
  39112. _this.emissiveIntensity = 1.0;
  39113. /**
  39114. * Intensity of the environment e.g. how much the environment will light the object
  39115. * either through harmonics for rough material or through the refelction for shiny ones.
  39116. */
  39117. _this.environmentIntensity = 1.0;
  39118. /**
  39119. * This is a special control allowing the reduction of the specular highlights coming from the
  39120. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  39121. */
  39122. _this.specularIntensity = 1.0;
  39123. /**
  39124. * Debug Control allowing disabling the bump map on this material.
  39125. */
  39126. _this.disableBumpMap = false;
  39127. /**
  39128. * AKA Occlusion Texture Intensity in other nomenclature.
  39129. */
  39130. _this.ambientTextureStrength = 1.0;
  39131. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  39132. /**
  39133. * AKA Diffuse Color in other nomenclature.
  39134. */
  39135. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  39136. /**
  39137. * AKA Specular Color in other nomenclature.
  39138. */
  39139. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  39140. _this.reflectionColor = new BABYLON.Color3(1.0, 1.0, 1.0);
  39141. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  39142. /**
  39143. * AKA Glossiness in other nomenclature.
  39144. */
  39145. _this.microSurface = 1.0;
  39146. /**
  39147. * source material index of refraction (IOR)' / 'destination material IOR.
  39148. */
  39149. _this.indexOfRefraction = 0.66;
  39150. /**
  39151. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  39152. */
  39153. _this.invertRefractionY = false;
  39154. /**
  39155. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  39156. * Materials half opaque for instance using refraction could benefit from this control.
  39157. */
  39158. _this.linkRefractionWithTransparency = false;
  39159. _this.useLightmapAsShadowmap = false;
  39160. /**
  39161. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  39162. */
  39163. _this.useAlphaFromAlbedoTexture = false;
  39164. /**
  39165. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  39166. */
  39167. _this.forceAlphaTest = false;
  39168. /**
  39169. * Defines the alpha limits in alpha test mode.
  39170. */
  39171. _this.alphaCutOff = 0.4;
  39172. /**
  39173. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  39174. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  39175. */
  39176. _this.useSpecularOverAlpha = true;
  39177. /**
  39178. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  39179. */
  39180. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  39181. /**
  39182. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  39183. */
  39184. _this.useRoughnessFromMetallicTextureAlpha = true;
  39185. /**
  39186. * Specifies if the metallic texture contains the roughness information in its green channel.
  39187. */
  39188. _this.useRoughnessFromMetallicTextureGreen = false;
  39189. /**
  39190. * Specifies if the metallic texture contains the metallness information in its blue channel.
  39191. */
  39192. _this.useMetallnessFromMetallicTextureBlue = false;
  39193. /**
  39194. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  39195. */
  39196. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  39197. /**
  39198. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  39199. */
  39200. _this.useAmbientInGrayScale = false;
  39201. /**
  39202. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  39203. * The material will try to infer what glossiness each pixel should be.
  39204. */
  39205. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  39206. /**
  39207. * BJS is using an harcoded light falloff based on a manually sets up range.
  39208. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  39209. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  39210. */
  39211. _this.usePhysicalLightFalloff = true;
  39212. /**
  39213. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  39214. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  39215. */
  39216. _this.useRadianceOverAlpha = true;
  39217. /**
  39218. * Allows using the bump map in parallax mode.
  39219. */
  39220. _this.useParallax = false;
  39221. /**
  39222. * Allows using the bump map in parallax occlusion mode.
  39223. */
  39224. _this.useParallaxOcclusion = false;
  39225. /**
  39226. * Controls the scale bias of the parallax mode.
  39227. */
  39228. _this.parallaxScaleBias = 0.05;
  39229. /**
  39230. * If sets to true, disables all the lights affecting the material.
  39231. */
  39232. _this.disableLighting = false;
  39233. /**
  39234. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  39235. */
  39236. _this.forceIrradianceInFragment = false;
  39237. /**
  39238. * Number of Simultaneous lights allowed on the material.
  39239. */
  39240. _this.maxSimultaneousLights = 4;
  39241. /**
  39242. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  39243. */
  39244. _this.invertNormalMapX = false;
  39245. /**
  39246. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  39247. */
  39248. _this.invertNormalMapY = false;
  39249. /**
  39250. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  39251. */
  39252. _this.twoSidedLighting = false;
  39253. /**
  39254. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  39255. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  39256. */
  39257. _this.useAlphaFresnel = false;
  39258. /**
  39259. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  39260. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  39261. */
  39262. _this.useLinearAlphaFresnel = false;
  39263. /**
  39264. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  39265. * And/Or occlude the blended part.
  39266. */
  39267. _this.environmentBRDFTexture = null;
  39268. /**
  39269. * Force normal to face away from face.
  39270. */
  39271. _this.forceNormalForward = false;
  39272. /**
  39273. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  39274. * makes the reflect vector face the model (under horizon).
  39275. */
  39276. _this.useHorizonOcclusion = true;
  39277. /**
  39278. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  39279. * too much the area relying on ambient texture to define their ambient occlusion.
  39280. */
  39281. _this.useRadianceOcclusion = true;
  39282. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  39283. return _this;
  39284. }
  39285. Object.defineProperty(PBRMaterial, "PBRMATERIAL_OPAQUE", {
  39286. /**
  39287. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  39288. */
  39289. get: function () {
  39290. return this._PBRMATERIAL_OPAQUE;
  39291. },
  39292. enumerable: true,
  39293. configurable: true
  39294. });
  39295. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATEST", {
  39296. /**
  39297. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  39298. */
  39299. get: function () {
  39300. return this._PBRMATERIAL_ALPHATEST;
  39301. },
  39302. enumerable: true,
  39303. configurable: true
  39304. });
  39305. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHABLEND", {
  39306. /**
  39307. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  39308. */
  39309. get: function () {
  39310. return this._PBRMATERIAL_ALPHABLEND;
  39311. },
  39312. enumerable: true,
  39313. configurable: true
  39314. });
  39315. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATESTANDBLEND", {
  39316. /**
  39317. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  39318. * They are also discarded below the alpha cutoff threshold to improve performances.
  39319. */
  39320. get: function () {
  39321. return this._PBRMATERIAL_ALPHATESTANDBLEND;
  39322. },
  39323. enumerable: true,
  39324. configurable: true
  39325. });
  39326. Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
  39327. /**
  39328. * Gets the image processing configuration used either in this material.
  39329. */
  39330. get: function () {
  39331. return this._imageProcessingConfiguration;
  39332. },
  39333. /**
  39334. * Sets the Default image processing configuration used either in the this material.
  39335. *
  39336. * If sets to null, the scene one is in use.
  39337. */
  39338. set: function (value) {
  39339. this._attachImageProcessingConfiguration(value);
  39340. // Ensure the effect will be rebuilt.
  39341. this._markAllSubMeshesAsTexturesDirty();
  39342. },
  39343. enumerable: true,
  39344. configurable: true
  39345. });
  39346. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
  39347. /**
  39348. * Gets wether the color curves effect is enabled.
  39349. */
  39350. get: function () {
  39351. return this.imageProcessingConfiguration.colorCurvesEnabled;
  39352. },
  39353. /**
  39354. * Sets wether the color curves effect is enabled.
  39355. */
  39356. set: function (value) {
  39357. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  39358. },
  39359. enumerable: true,
  39360. configurable: true
  39361. });
  39362. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
  39363. /**
  39364. * Gets wether the color grading effect is enabled.
  39365. */
  39366. get: function () {
  39367. return this.imageProcessingConfiguration.colorGradingEnabled;
  39368. },
  39369. /**
  39370. * Gets wether the color grading effect is enabled.
  39371. */
  39372. set: function (value) {
  39373. this.imageProcessingConfiguration.colorGradingEnabled = value;
  39374. },
  39375. enumerable: true,
  39376. configurable: true
  39377. });
  39378. Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
  39379. /**
  39380. * Gets wether tonemapping is enabled or not.
  39381. */
  39382. get: function () {
  39383. return this._imageProcessingConfiguration.toneMappingEnabled;
  39384. },
  39385. /**
  39386. * Sets wether tonemapping is enabled or not
  39387. */
  39388. set: function (value) {
  39389. this._imageProcessingConfiguration.toneMappingEnabled = value;
  39390. },
  39391. enumerable: true,
  39392. configurable: true
  39393. });
  39394. ;
  39395. ;
  39396. Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
  39397. /**
  39398. * The camera exposure used on this material.
  39399. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  39400. * This corresponds to a photographic exposure.
  39401. */
  39402. get: function () {
  39403. return this._imageProcessingConfiguration.exposure;
  39404. },
  39405. /**
  39406. * The camera exposure used on this material.
  39407. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  39408. * This corresponds to a photographic exposure.
  39409. */
  39410. set: function (value) {
  39411. this._imageProcessingConfiguration.exposure = value;
  39412. },
  39413. enumerable: true,
  39414. configurable: true
  39415. });
  39416. ;
  39417. ;
  39418. Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
  39419. /**
  39420. * Gets The camera contrast used on this material.
  39421. */
  39422. get: function () {
  39423. return this._imageProcessingConfiguration.contrast;
  39424. },
  39425. /**
  39426. * Sets The camera contrast used on this material.
  39427. */
  39428. set: function (value) {
  39429. this._imageProcessingConfiguration.contrast = value;
  39430. },
  39431. enumerable: true,
  39432. configurable: true
  39433. });
  39434. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
  39435. /**
  39436. * Gets the Color Grading 2D Lookup Texture.
  39437. */
  39438. get: function () {
  39439. return this._imageProcessingConfiguration.colorGradingTexture;
  39440. },
  39441. /**
  39442. * Sets the Color Grading 2D Lookup Texture.
  39443. */
  39444. set: function (value) {
  39445. this._imageProcessingConfiguration.colorGradingTexture = value;
  39446. },
  39447. enumerable: true,
  39448. configurable: true
  39449. });
  39450. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
  39451. /**
  39452. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  39453. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  39454. * 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;
  39455. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  39456. */
  39457. get: function () {
  39458. return this._imageProcessingConfiguration.colorCurves;
  39459. },
  39460. /**
  39461. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  39462. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  39463. * 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;
  39464. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  39465. */
  39466. set: function (value) {
  39467. this._imageProcessingConfiguration.colorCurves = value;
  39468. },
  39469. enumerable: true,
  39470. configurable: true
  39471. });
  39472. PBRMaterial.prototype.getClassName = function () {
  39473. return "PBRMaterial";
  39474. };
  39475. PBRMaterial.prototype.getActiveTextures = function () {
  39476. var activeTextures = _super.prototype.getActiveTextures.call(this);
  39477. if (this._albedoTexture) {
  39478. activeTextures.push(this._albedoTexture);
  39479. }
  39480. if (this._ambientTexture) {
  39481. activeTextures.push(this._ambientTexture);
  39482. }
  39483. if (this._opacityTexture) {
  39484. activeTextures.push(this._opacityTexture);
  39485. }
  39486. if (this._reflectionTexture) {
  39487. activeTextures.push(this._reflectionTexture);
  39488. }
  39489. if (this._emissiveTexture) {
  39490. activeTextures.push(this._emissiveTexture);
  39491. }
  39492. if (this._reflectivityTexture) {
  39493. activeTextures.push(this._reflectivityTexture);
  39494. }
  39495. if (this._metallicTexture) {
  39496. activeTextures.push(this._metallicTexture);
  39497. }
  39498. if (this._microSurfaceTexture) {
  39499. activeTextures.push(this._microSurfaceTexture);
  39500. }
  39501. if (this._bumpTexture) {
  39502. activeTextures.push(this._bumpTexture);
  39503. }
  39504. if (this._lightmapTexture) {
  39505. activeTextures.push(this._lightmapTexture);
  39506. }
  39507. if (this._refractionTexture) {
  39508. activeTextures.push(this._refractionTexture);
  39509. }
  39510. return activeTextures;
  39511. };
  39512. PBRMaterial.prototype.hasTexture = function (texture) {
  39513. if (_super.prototype.hasTexture.call(this, texture)) {
  39514. return true;
  39515. }
  39516. if (this._albedoTexture === texture) {
  39517. return true;
  39518. }
  39519. if (this._ambientTexture === texture) {
  39520. return true;
  39521. }
  39522. if (this._opacityTexture === texture) {
  39523. return true;
  39524. }
  39525. if (this._reflectionTexture === texture) {
  39526. return true;
  39527. }
  39528. if (this._reflectivityTexture === texture) {
  39529. return true;
  39530. }
  39531. if (this._metallicTexture === texture) {
  39532. return true;
  39533. }
  39534. if (this._microSurfaceTexture === texture) {
  39535. return true;
  39536. }
  39537. if (this._bumpTexture === texture) {
  39538. return true;
  39539. }
  39540. if (this._lightmapTexture === texture) {
  39541. return true;
  39542. }
  39543. if (this._refractionTexture === texture) {
  39544. return true;
  39545. }
  39546. return false;
  39547. };
  39548. PBRMaterial.prototype.clone = function (name) {
  39549. var _this = this;
  39550. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  39551. clone.id = name;
  39552. clone.name = name;
  39553. return clone;
  39554. };
  39555. PBRMaterial.prototype.serialize = function () {
  39556. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  39557. serializationObject.customType = "BABYLON.PBRMaterial";
  39558. return serializationObject;
  39559. };
  39560. // Statics
  39561. PBRMaterial.Parse = function (source, scene, rootUrl) {
  39562. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  39563. };
  39564. PBRMaterial._PBRMATERIAL_OPAQUE = 0;
  39565. PBRMaterial._PBRMATERIAL_ALPHATEST = 1;
  39566. PBRMaterial._PBRMATERIAL_ALPHABLEND = 2;
  39567. PBRMaterial._PBRMATERIAL_ALPHATESTANDBLEND = 3;
  39568. __decorate([
  39569. BABYLON.serialize(),
  39570. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39571. ], PBRMaterial.prototype, "directIntensity", void 0);
  39572. __decorate([
  39573. BABYLON.serialize(),
  39574. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39575. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  39576. __decorate([
  39577. BABYLON.serialize(),
  39578. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39579. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  39580. __decorate([
  39581. BABYLON.serialize(),
  39582. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39583. ], PBRMaterial.prototype, "specularIntensity", void 0);
  39584. __decorate([
  39585. BABYLON.serialize(),
  39586. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39587. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  39588. __decorate([
  39589. BABYLON.serializeAsTexture(),
  39590. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39591. ], PBRMaterial.prototype, "albedoTexture", void 0);
  39592. __decorate([
  39593. BABYLON.serializeAsTexture(),
  39594. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39595. ], PBRMaterial.prototype, "ambientTexture", void 0);
  39596. __decorate([
  39597. BABYLON.serialize(),
  39598. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39599. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  39600. __decorate([
  39601. BABYLON.serializeAsTexture(),
  39602. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  39603. ], PBRMaterial.prototype, "opacityTexture", void 0);
  39604. __decorate([
  39605. BABYLON.serializeAsTexture(),
  39606. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39607. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  39608. __decorate([
  39609. BABYLON.serializeAsTexture(),
  39610. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39611. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  39612. __decorate([
  39613. BABYLON.serializeAsTexture(),
  39614. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39615. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  39616. __decorate([
  39617. BABYLON.serializeAsTexture(),
  39618. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39619. ], PBRMaterial.prototype, "metallicTexture", void 0);
  39620. __decorate([
  39621. BABYLON.serialize(),
  39622. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39623. ], PBRMaterial.prototype, "metallic", void 0);
  39624. __decorate([
  39625. BABYLON.serialize(),
  39626. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39627. ], PBRMaterial.prototype, "roughness", void 0);
  39628. __decorate([
  39629. BABYLON.serializeAsTexture(),
  39630. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39631. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  39632. __decorate([
  39633. BABYLON.serializeAsTexture(),
  39634. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39635. ], PBRMaterial.prototype, "bumpTexture", void 0);
  39636. __decorate([
  39637. BABYLON.serializeAsTexture(),
  39638. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  39639. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  39640. __decorate([
  39641. BABYLON.serializeAsTexture(),
  39642. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39643. ], PBRMaterial.prototype, "refractionTexture", void 0);
  39644. __decorate([
  39645. BABYLON.serializeAsColor3("ambient"),
  39646. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39647. ], PBRMaterial.prototype, "ambientColor", void 0);
  39648. __decorate([
  39649. BABYLON.serializeAsColor3("albedo"),
  39650. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39651. ], PBRMaterial.prototype, "albedoColor", void 0);
  39652. __decorate([
  39653. BABYLON.serializeAsColor3("reflectivity"),
  39654. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39655. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  39656. __decorate([
  39657. BABYLON.serializeAsColor3("reflection"),
  39658. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39659. ], PBRMaterial.prototype, "reflectionColor", void 0);
  39660. __decorate([
  39661. BABYLON.serializeAsColor3("emissive"),
  39662. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39663. ], PBRMaterial.prototype, "emissiveColor", void 0);
  39664. __decorate([
  39665. BABYLON.serialize(),
  39666. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39667. ], PBRMaterial.prototype, "microSurface", void 0);
  39668. __decorate([
  39669. BABYLON.serialize(),
  39670. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39671. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  39672. __decorate([
  39673. BABYLON.serialize(),
  39674. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39675. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  39676. __decorate([
  39677. BABYLON.serialize(),
  39678. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39679. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  39680. __decorate([
  39681. BABYLON.serialize(),
  39682. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39683. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  39684. __decorate([
  39685. BABYLON.serialize(),
  39686. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  39687. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  39688. __decorate([
  39689. BABYLON.serialize(),
  39690. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  39691. ], PBRMaterial.prototype, "forceAlphaTest", void 0);
  39692. __decorate([
  39693. BABYLON.serialize(),
  39694. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  39695. ], PBRMaterial.prototype, "alphaCutOff", void 0);
  39696. __decorate([
  39697. BABYLON.serialize(),
  39698. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39699. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  39700. __decorate([
  39701. BABYLON.serialize(),
  39702. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39703. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  39704. __decorate([
  39705. BABYLON.serialize(),
  39706. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39707. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  39708. __decorate([
  39709. BABYLON.serialize(),
  39710. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39711. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  39712. __decorate([
  39713. BABYLON.serialize(),
  39714. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39715. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  39716. __decorate([
  39717. BABYLON.serialize(),
  39718. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39719. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  39720. __decorate([
  39721. BABYLON.serialize(),
  39722. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39723. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  39724. __decorate([
  39725. BABYLON.serialize(),
  39726. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39727. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  39728. __decorate([
  39729. BABYLON.serialize(),
  39730. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39731. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  39732. __decorate([
  39733. BABYLON.serialize(),
  39734. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39735. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  39736. __decorate([
  39737. BABYLON.serialize(),
  39738. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39739. ], PBRMaterial.prototype, "useParallax", void 0);
  39740. __decorate([
  39741. BABYLON.serialize(),
  39742. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39743. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  39744. __decorate([
  39745. BABYLON.serialize(),
  39746. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39747. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  39748. __decorate([
  39749. BABYLON.serialize(),
  39750. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  39751. ], PBRMaterial.prototype, "disableLighting", void 0);
  39752. __decorate([
  39753. BABYLON.serialize(),
  39754. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39755. ], PBRMaterial.prototype, "forceIrradianceInFragment", void 0);
  39756. __decorate([
  39757. BABYLON.serialize(),
  39758. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  39759. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  39760. __decorate([
  39761. BABYLON.serialize(),
  39762. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39763. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  39764. __decorate([
  39765. BABYLON.serialize(),
  39766. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39767. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  39768. __decorate([
  39769. BABYLON.serialize(),
  39770. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39771. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  39772. __decorate([
  39773. BABYLON.serialize(),
  39774. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39775. ], PBRMaterial.prototype, "useAlphaFresnel", void 0);
  39776. __decorate([
  39777. BABYLON.serialize(),
  39778. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39779. ], PBRMaterial.prototype, "useLinearAlphaFresnel", void 0);
  39780. __decorate([
  39781. BABYLON.serializeAsTexture(),
  39782. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39783. ], PBRMaterial.prototype, "environmentBRDFTexture", void 0);
  39784. __decorate([
  39785. BABYLON.serialize(),
  39786. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39787. ], PBRMaterial.prototype, "forceNormalForward", void 0);
  39788. __decorate([
  39789. BABYLON.serialize(),
  39790. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39791. ], PBRMaterial.prototype, "useHorizonOcclusion", void 0);
  39792. __decorate([
  39793. BABYLON.serialize(),
  39794. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39795. ], PBRMaterial.prototype, "useRadianceOcclusion", void 0);
  39796. return PBRMaterial;
  39797. }(BABYLON.PBRBaseMaterial));
  39798. BABYLON.PBRMaterial = PBRMaterial;
  39799. })(BABYLON || (BABYLON = {}));
  39800. //# sourceMappingURL=babylon.pbrMaterial.js.map
  39801. var BABYLON;
  39802. (function (BABYLON) {
  39803. /**
  39804. * The PBR material of BJS following the metal roughness convention.
  39805. *
  39806. * This fits to the PBR convention in the GLTF definition:
  39807. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  39808. */
  39809. var PBRMetallicRoughnessMaterial = /** @class */ (function (_super) {
  39810. __extends(PBRMetallicRoughnessMaterial, _super);
  39811. /**
  39812. * Instantiates a new PBRMetalRoughnessMaterial instance.
  39813. *
  39814. * @param name The material name
  39815. * @param scene The scene the material will be use in.
  39816. */
  39817. function PBRMetallicRoughnessMaterial(name, scene) {
  39818. var _this = _super.call(this, name, scene) || this;
  39819. _this._useRoughnessFromMetallicTextureAlpha = false;
  39820. _this._useRoughnessFromMetallicTextureGreen = true;
  39821. _this._useMetallnessFromMetallicTextureBlue = true;
  39822. _this._forceMetallicWorkflow = true;
  39823. return _this;
  39824. }
  39825. /**
  39826. * Return the currrent class name of the material.
  39827. */
  39828. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  39829. return "PBRMetallicRoughnessMaterial";
  39830. };
  39831. /**
  39832. * Return the active textures of the material.
  39833. */
  39834. PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
  39835. var activeTextures = _super.prototype.getActiveTextures.call(this);
  39836. if (this.baseTexture) {
  39837. activeTextures.push(this.baseTexture);
  39838. }
  39839. if (this.metallicRoughnessTexture) {
  39840. activeTextures.push(this.metallicRoughnessTexture);
  39841. }
  39842. return activeTextures;
  39843. };
  39844. PBRMetallicRoughnessMaterial.prototype.hasTexture = function (texture) {
  39845. if (_super.prototype.hasTexture.call(this, texture)) {
  39846. return true;
  39847. }
  39848. if (this.baseTexture === texture) {
  39849. return true;
  39850. }
  39851. if (this.metallicRoughnessTexture === texture) {
  39852. return true;
  39853. }
  39854. return false;
  39855. };
  39856. PBRMetallicRoughnessMaterial.prototype.clone = function (name) {
  39857. var _this = this;
  39858. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);
  39859. clone.id = name;
  39860. clone.name = name;
  39861. return clone;
  39862. };
  39863. /**
  39864. * Serialize the material to a parsable JSON object.
  39865. */
  39866. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  39867. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  39868. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  39869. return serializationObject;
  39870. };
  39871. /**
  39872. * Parses a JSON object correponding to the serialize function.
  39873. */
  39874. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  39875. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  39876. };
  39877. __decorate([
  39878. BABYLON.serializeAsColor3(),
  39879. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  39880. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  39881. __decorate([
  39882. BABYLON.serializeAsTexture(),
  39883. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  39884. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  39885. __decorate([
  39886. BABYLON.serialize(),
  39887. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39888. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  39889. __decorate([
  39890. BABYLON.serialize(),
  39891. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39892. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  39893. __decorate([
  39894. BABYLON.serializeAsTexture(),
  39895. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  39896. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  39897. return PBRMetallicRoughnessMaterial;
  39898. }(BABYLON.PBRBaseSimpleMaterial));
  39899. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  39900. })(BABYLON || (BABYLON = {}));
  39901. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  39902. var BABYLON;
  39903. (function (BABYLON) {
  39904. /**
  39905. * The PBR material of BJS following the specular glossiness convention.
  39906. *
  39907. * This fits to the PBR convention in the GLTF definition:
  39908. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  39909. */
  39910. var PBRSpecularGlossinessMaterial = /** @class */ (function (_super) {
  39911. __extends(PBRSpecularGlossinessMaterial, _super);
  39912. /**
  39913. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  39914. *
  39915. * @param name The material name
  39916. * @param scene The scene the material will be use in.
  39917. */
  39918. function PBRSpecularGlossinessMaterial(name, scene) {
  39919. var _this = _super.call(this, name, scene) || this;
  39920. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  39921. return _this;
  39922. }
  39923. /**
  39924. * Return the currrent class name of the material.
  39925. */
  39926. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  39927. return "PBRSpecularGlossinessMaterial";
  39928. };
  39929. /**
  39930. * Return the active textures of the material.
  39931. */
  39932. PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
  39933. var activeTextures = _super.prototype.getActiveTextures.call(this);
  39934. if (this.diffuseTexture) {
  39935. activeTextures.push(this.diffuseTexture);
  39936. }
  39937. if (this.specularGlossinessTexture) {
  39938. activeTextures.push(this.specularGlossinessTexture);
  39939. }
  39940. return activeTextures;
  39941. };
  39942. PBRSpecularGlossinessMaterial.prototype.hasTexture = function (texture) {
  39943. if (_super.prototype.hasTexture.call(this, texture)) {
  39944. return true;
  39945. }
  39946. if (this.diffuseTexture === texture) {
  39947. return true;
  39948. }
  39949. if (this.specularGlossinessTexture === texture) {
  39950. return true;
  39951. }
  39952. return false;
  39953. };
  39954. PBRSpecularGlossinessMaterial.prototype.clone = function (name) {
  39955. var _this = this;
  39956. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);
  39957. clone.id = name;
  39958. clone.name = name;
  39959. return clone;
  39960. };
  39961. /**
  39962. * Serialize the material to a parsable JSON object.
  39963. */
  39964. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  39965. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  39966. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  39967. return serializationObject;
  39968. };
  39969. /**
  39970. * Parses a JSON object correponding to the serialize function.
  39971. */
  39972. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  39973. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  39974. };
  39975. __decorate([
  39976. BABYLON.serializeAsColor3("diffuse"),
  39977. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  39978. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  39979. __decorate([
  39980. BABYLON.serializeAsTexture(),
  39981. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  39982. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  39983. __decorate([
  39984. BABYLON.serializeAsColor3("specular"),
  39985. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  39986. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  39987. __decorate([
  39988. BABYLON.serialize(),
  39989. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  39990. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  39991. __decorate([
  39992. BABYLON.serializeAsTexture(),
  39993. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  39994. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  39995. return PBRSpecularGlossinessMaterial;
  39996. }(BABYLON.PBRBaseSimpleMaterial));
  39997. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  39998. })(BABYLON || (BABYLON = {}));
  39999. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  40000. var BABYLON;
  40001. (function (BABYLON) {
  40002. BABYLON.CameraInputTypes = {};
  40003. var CameraInputsManager = /** @class */ (function () {
  40004. function CameraInputsManager(camera) {
  40005. this.attached = {};
  40006. this.camera = camera;
  40007. this.checkInputs = function () { };
  40008. }
  40009. /**
  40010. * Add an input method to a camera.
  40011. * builtin inputs example: camera.inputs.addGamepad();
  40012. * custom inputs example: camera.inputs.add(new BABYLON.FreeCameraGamepadInput());
  40013. * @param input camera input method
  40014. */
  40015. CameraInputsManager.prototype.add = function (input) {
  40016. var type = input.getSimpleName();
  40017. if (this.attached[type]) {
  40018. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  40019. return;
  40020. }
  40021. this.attached[type] = input;
  40022. input.camera = this.camera;
  40023. //for checkInputs, we are dynamically creating a function
  40024. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  40025. if (input.checkInputs) {
  40026. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  40027. }
  40028. if (this.attachedElement) {
  40029. input.attachControl(this.attachedElement);
  40030. }
  40031. };
  40032. /**
  40033. * Remove a specific input method from a camera
  40034. * example: camera.inputs.remove(camera.inputs.attached.mouse);
  40035. * @param inputToRemove camera input method
  40036. */
  40037. CameraInputsManager.prototype.remove = function (inputToRemove) {
  40038. for (var cam in this.attached) {
  40039. var input = this.attached[cam];
  40040. if (input === inputToRemove) {
  40041. input.detachControl(this.attachedElement);
  40042. input.camera = null;
  40043. delete this.attached[cam];
  40044. this.rebuildInputCheck();
  40045. }
  40046. }
  40047. };
  40048. CameraInputsManager.prototype.removeByType = function (inputType) {
  40049. for (var cam in this.attached) {
  40050. var input = this.attached[cam];
  40051. if (input.getClassName() === inputType) {
  40052. input.detachControl(this.attachedElement);
  40053. input.camera = null;
  40054. delete this.attached[cam];
  40055. this.rebuildInputCheck();
  40056. }
  40057. }
  40058. };
  40059. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  40060. var current = this.checkInputs;
  40061. return function () {
  40062. current();
  40063. fn();
  40064. };
  40065. };
  40066. CameraInputsManager.prototype.attachInput = function (input) {
  40067. if (this.attachedElement) {
  40068. input.attachControl(this.attachedElement, this.noPreventDefault);
  40069. }
  40070. };
  40071. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  40072. if (noPreventDefault === void 0) { noPreventDefault = false; }
  40073. if (this.attachedElement) {
  40074. return;
  40075. }
  40076. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  40077. this.attachedElement = element;
  40078. this.noPreventDefault = noPreventDefault;
  40079. for (var cam in this.attached) {
  40080. this.attached[cam].attachControl(element, noPreventDefault);
  40081. }
  40082. };
  40083. CameraInputsManager.prototype.detachElement = function (element, disconnect) {
  40084. if (disconnect === void 0) { disconnect = false; }
  40085. if (this.attachedElement !== element) {
  40086. return;
  40087. }
  40088. for (var cam in this.attached) {
  40089. this.attached[cam].detachControl(element);
  40090. if (disconnect) {
  40091. this.attached[cam].camera = null;
  40092. }
  40093. }
  40094. this.attachedElement = null;
  40095. };
  40096. CameraInputsManager.prototype.rebuildInputCheck = function () {
  40097. this.checkInputs = function () { };
  40098. for (var cam in this.attached) {
  40099. var input = this.attached[cam];
  40100. if (input.checkInputs) {
  40101. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  40102. }
  40103. }
  40104. };
  40105. /**
  40106. * Remove all attached input methods from a camera
  40107. */
  40108. CameraInputsManager.prototype.clear = function () {
  40109. if (this.attachedElement) {
  40110. this.detachElement(this.attachedElement, true);
  40111. }
  40112. this.attached = {};
  40113. this.attachedElement = null;
  40114. this.checkInputs = function () { };
  40115. };
  40116. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  40117. var inputs = {};
  40118. for (var cam in this.attached) {
  40119. var input = this.attached[cam];
  40120. var res = BABYLON.SerializationHelper.Serialize(input);
  40121. inputs[input.getClassName()] = res;
  40122. }
  40123. serializedCamera.inputsmgr = inputs;
  40124. };
  40125. CameraInputsManager.prototype.parse = function (parsedCamera) {
  40126. var parsedInputs = parsedCamera.inputsmgr;
  40127. if (parsedInputs) {
  40128. this.clear();
  40129. for (var n in parsedInputs) {
  40130. var construct = BABYLON.CameraInputTypes[n];
  40131. if (construct) {
  40132. var parsedinput = parsedInputs[n];
  40133. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  40134. this.add(input);
  40135. }
  40136. }
  40137. }
  40138. else {
  40139. //2016-03-08 this part is for managing backward compatibility
  40140. for (var n in this.attached) {
  40141. var construct = BABYLON.CameraInputTypes[this.attached[n].getClassName()];
  40142. if (construct) {
  40143. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  40144. this.remove(this.attached[n]);
  40145. this.add(input);
  40146. }
  40147. }
  40148. }
  40149. };
  40150. return CameraInputsManager;
  40151. }());
  40152. BABYLON.CameraInputsManager = CameraInputsManager;
  40153. })(BABYLON || (BABYLON = {}));
  40154. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  40155. var BABYLON;
  40156. (function (BABYLON) {
  40157. var TargetCamera = /** @class */ (function (_super) {
  40158. __extends(TargetCamera, _super);
  40159. function TargetCamera(name, position, scene) {
  40160. var _this = _super.call(this, name, position, scene) || this;
  40161. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  40162. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  40163. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  40164. _this.speed = 2.0;
  40165. _this.noRotationConstraint = false;
  40166. _this.lockedTarget = null;
  40167. _this._currentTarget = BABYLON.Vector3.Zero();
  40168. _this._viewMatrix = BABYLON.Matrix.Zero();
  40169. _this._camMatrix = BABYLON.Matrix.Zero();
  40170. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  40171. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  40172. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  40173. _this._currentUpVector = new BABYLON.Vector3(0, 1, 0);
  40174. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  40175. _this._lookAtTemp = BABYLON.Matrix.Zero();
  40176. _this._tempMatrix = BABYLON.Matrix.Zero();
  40177. return _this;
  40178. }
  40179. TargetCamera.prototype.getFrontPosition = function (distance) {
  40180. this.getWorldMatrix();
  40181. var direction = this.getTarget().subtract(this.position);
  40182. direction.normalize();
  40183. direction.scaleInPlace(distance);
  40184. return this.globalPosition.add(direction);
  40185. };
  40186. TargetCamera.prototype._getLockedTargetPosition = function () {
  40187. if (!this.lockedTarget) {
  40188. return null;
  40189. }
  40190. if (this.lockedTarget.absolutePosition) {
  40191. this.lockedTarget.computeWorldMatrix();
  40192. }
  40193. return this.lockedTarget.absolutePosition || this.lockedTarget;
  40194. };
  40195. TargetCamera.prototype.storeState = function () {
  40196. this._storedPosition = this.position.clone();
  40197. this._storedRotation = this.rotation.clone();
  40198. if (this.rotationQuaternion) {
  40199. this._storedRotationQuaternion = this.rotationQuaternion.clone();
  40200. }
  40201. return _super.prototype.storeState.call(this);
  40202. };
  40203. /**
  40204. * Restored camera state. You must call storeState() first
  40205. */
  40206. TargetCamera.prototype._restoreStateValues = function () {
  40207. if (!_super.prototype._restoreStateValues.call(this)) {
  40208. return false;
  40209. }
  40210. this.position = this._storedPosition.clone();
  40211. this.rotation = this._storedRotation.clone();
  40212. if (this.rotationQuaternion) {
  40213. this.rotationQuaternion = this._storedRotationQuaternion.clone();
  40214. }
  40215. this.cameraDirection.copyFromFloats(0, 0, 0);
  40216. this.cameraRotation.copyFromFloats(0, 0);
  40217. return true;
  40218. };
  40219. // Cache
  40220. TargetCamera.prototype._initCache = function () {
  40221. _super.prototype._initCache.call(this);
  40222. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  40223. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  40224. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  40225. };
  40226. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  40227. if (!ignoreParentClass) {
  40228. _super.prototype._updateCache.call(this);
  40229. }
  40230. var lockedTargetPosition = this._getLockedTargetPosition();
  40231. if (!lockedTargetPosition) {
  40232. this._cache.lockedTarget = null;
  40233. }
  40234. else {
  40235. if (!this._cache.lockedTarget) {
  40236. this._cache.lockedTarget = lockedTargetPosition.clone();
  40237. }
  40238. else {
  40239. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  40240. }
  40241. }
  40242. this._cache.rotation.copyFrom(this.rotation);
  40243. if (this.rotationQuaternion)
  40244. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  40245. };
  40246. // Synchronized
  40247. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  40248. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  40249. return false;
  40250. }
  40251. var lockedTargetPosition = this._getLockedTargetPosition();
  40252. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  40253. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  40254. };
  40255. // Methods
  40256. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  40257. var engine = this.getEngine();
  40258. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  40259. };
  40260. // Target
  40261. TargetCamera.prototype.setTarget = function (target) {
  40262. this.upVector.normalize();
  40263. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  40264. this._camMatrix.invert();
  40265. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  40266. var vDir = target.subtract(this.position);
  40267. if (vDir.x >= 0.0) {
  40268. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  40269. }
  40270. else {
  40271. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  40272. }
  40273. this.rotation.z = 0;
  40274. if (isNaN(this.rotation.x)) {
  40275. this.rotation.x = 0;
  40276. }
  40277. if (isNaN(this.rotation.y)) {
  40278. this.rotation.y = 0;
  40279. }
  40280. if (isNaN(this.rotation.z)) {
  40281. this.rotation.z = 0;
  40282. }
  40283. if (this.rotationQuaternion) {
  40284. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  40285. }
  40286. };
  40287. /**
  40288. * Return the current target position of the camera. This value is expressed in local space.
  40289. */
  40290. TargetCamera.prototype.getTarget = function () {
  40291. return this._currentTarget;
  40292. };
  40293. TargetCamera.prototype._decideIfNeedsToMove = function () {
  40294. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  40295. };
  40296. TargetCamera.prototype._updatePosition = function () {
  40297. if (this.parent) {
  40298. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  40299. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  40300. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  40301. return;
  40302. }
  40303. this.position.addInPlace(this.cameraDirection);
  40304. };
  40305. TargetCamera.prototype._checkInputs = function () {
  40306. var needToMove = this._decideIfNeedsToMove();
  40307. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  40308. // Move
  40309. if (needToMove) {
  40310. this._updatePosition();
  40311. }
  40312. // Rotate
  40313. if (needToRotate) {
  40314. this.rotation.x += this.cameraRotation.x;
  40315. this.rotation.y += this.cameraRotation.y;
  40316. //rotate, if quaternion is set and rotation was used
  40317. if (this.rotationQuaternion) {
  40318. var len = this.rotation.lengthSquared();
  40319. if (len) {
  40320. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  40321. }
  40322. }
  40323. if (!this.noRotationConstraint) {
  40324. var limit = (Math.PI / 2) * 0.95;
  40325. if (this.rotation.x > limit)
  40326. this.rotation.x = limit;
  40327. if (this.rotation.x < -limit)
  40328. this.rotation.x = -limit;
  40329. }
  40330. }
  40331. // Inertia
  40332. if (needToMove) {
  40333. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  40334. this.cameraDirection.x = 0;
  40335. }
  40336. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  40337. this.cameraDirection.y = 0;
  40338. }
  40339. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  40340. this.cameraDirection.z = 0;
  40341. }
  40342. this.cameraDirection.scaleInPlace(this.inertia);
  40343. }
  40344. if (needToRotate) {
  40345. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  40346. this.cameraRotation.x = 0;
  40347. }
  40348. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  40349. this.cameraRotation.y = 0;
  40350. }
  40351. this.cameraRotation.scaleInPlace(this.inertia);
  40352. }
  40353. _super.prototype._checkInputs.call(this);
  40354. };
  40355. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  40356. if (this.rotationQuaternion) {
  40357. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  40358. }
  40359. else {
  40360. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  40361. }
  40362. //update the up vector!
  40363. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._currentUpVector);
  40364. };
  40365. TargetCamera.prototype._getViewMatrix = function () {
  40366. if (this.lockedTarget) {
  40367. this.setTarget(this._getLockedTargetPosition());
  40368. }
  40369. // Compute
  40370. this._updateCameraRotationMatrix();
  40371. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  40372. // Computing target and final matrix
  40373. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  40374. if (this.getScene().useRightHandedSystem) {
  40375. BABYLON.Matrix.LookAtRHToRef(this.position, this._currentTarget, this._currentUpVector, this._viewMatrix);
  40376. }
  40377. else {
  40378. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._currentUpVector, this._viewMatrix);
  40379. }
  40380. return this._viewMatrix;
  40381. };
  40382. /**
  40383. * @override
  40384. * Override Camera.createRigCamera
  40385. */
  40386. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  40387. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  40388. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  40389. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  40390. if (!this.rotationQuaternion) {
  40391. this.rotationQuaternion = new BABYLON.Quaternion();
  40392. }
  40393. rigCamera._cameraRigParams = {};
  40394. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  40395. }
  40396. return rigCamera;
  40397. }
  40398. return null;
  40399. };
  40400. /**
  40401. * @override
  40402. * Override Camera._updateRigCameras
  40403. */
  40404. TargetCamera.prototype._updateRigCameras = function () {
  40405. var camLeft = this._rigCameras[0];
  40406. var camRight = this._rigCameras[1];
  40407. switch (this.cameraRigMode) {
  40408. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  40409. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  40410. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  40411. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  40412. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  40413. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  40414. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  40415. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  40416. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  40417. camLeft.setTarget(this.getTarget());
  40418. camRight.setTarget(this.getTarget());
  40419. break;
  40420. case BABYLON.Camera.RIG_MODE_VR:
  40421. if (camLeft.rotationQuaternion) {
  40422. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  40423. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  40424. }
  40425. else {
  40426. camLeft.rotation.copyFrom(this.rotation);
  40427. camRight.rotation.copyFrom(this.rotation);
  40428. }
  40429. camLeft.position.copyFrom(this.position);
  40430. camRight.position.copyFrom(this.position);
  40431. break;
  40432. }
  40433. _super.prototype._updateRigCameras.call(this);
  40434. };
  40435. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  40436. if (!this._rigCamTransformMatrix) {
  40437. this._rigCamTransformMatrix = new BABYLON.Matrix();
  40438. }
  40439. var target = this.getTarget();
  40440. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  40441. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  40442. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  40443. };
  40444. TargetCamera.prototype.getClassName = function () {
  40445. return "TargetCamera";
  40446. };
  40447. __decorate([
  40448. BABYLON.serializeAsVector3()
  40449. ], TargetCamera.prototype, "rotation", void 0);
  40450. __decorate([
  40451. BABYLON.serialize()
  40452. ], TargetCamera.prototype, "speed", void 0);
  40453. __decorate([
  40454. BABYLON.serializeAsMeshReference("lockedTargetId")
  40455. ], TargetCamera.prototype, "lockedTarget", void 0);
  40456. return TargetCamera;
  40457. }(BABYLON.Camera));
  40458. BABYLON.TargetCamera = TargetCamera;
  40459. })(BABYLON || (BABYLON = {}));
  40460. //# sourceMappingURL=babylon.targetCamera.js.map
  40461. var BABYLON;
  40462. (function (BABYLON) {
  40463. var FreeCameraMouseInput = /** @class */ (function () {
  40464. function FreeCameraMouseInput(touchEnabled) {
  40465. if (touchEnabled === void 0) { touchEnabled = true; }
  40466. this.touchEnabled = touchEnabled;
  40467. this.buttons = [0, 1, 2];
  40468. this.angularSensibility = 2000.0;
  40469. this.previousPosition = null;
  40470. }
  40471. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  40472. var _this = this;
  40473. var engine = this.camera.getEngine();
  40474. if (!this._pointerInput) {
  40475. this._pointerInput = function (p, s) {
  40476. var evt = p.event;
  40477. if (engine.isInVRExclusivePointerMode) {
  40478. return;
  40479. }
  40480. if (!_this.touchEnabled && evt.pointerType === "touch") {
  40481. return;
  40482. }
  40483. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  40484. return;
  40485. }
  40486. var srcElement = (evt.srcElement || evt.target);
  40487. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  40488. try {
  40489. srcElement.setPointerCapture(evt.pointerId);
  40490. }
  40491. catch (e) {
  40492. //Nothing to do with the error. Execution will continue.
  40493. }
  40494. _this.previousPosition = {
  40495. x: evt.clientX,
  40496. y: evt.clientY
  40497. };
  40498. if (!noPreventDefault) {
  40499. evt.preventDefault();
  40500. element.focus();
  40501. }
  40502. }
  40503. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  40504. try {
  40505. srcElement.releasePointerCapture(evt.pointerId);
  40506. }
  40507. catch (e) {
  40508. //Nothing to do with the error.
  40509. }
  40510. _this.previousPosition = null;
  40511. if (!noPreventDefault) {
  40512. evt.preventDefault();
  40513. }
  40514. }
  40515. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  40516. if (!_this.previousPosition || engine.isPointerLock) {
  40517. return;
  40518. }
  40519. var offsetX = evt.clientX - _this.previousPosition.x;
  40520. var offsetY = evt.clientY - _this.previousPosition.y;
  40521. if (_this.camera.getScene().useRightHandedSystem) {
  40522. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  40523. }
  40524. else {
  40525. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  40526. }
  40527. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  40528. _this.previousPosition = {
  40529. x: evt.clientX,
  40530. y: evt.clientY
  40531. };
  40532. if (!noPreventDefault) {
  40533. evt.preventDefault();
  40534. }
  40535. }
  40536. };
  40537. }
  40538. this._onMouseMove = function (evt) {
  40539. if (!engine.isPointerLock) {
  40540. return;
  40541. }
  40542. if (engine.isInVRExclusivePointerMode) {
  40543. return;
  40544. }
  40545. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  40546. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  40547. if (_this.camera.getScene().useRightHandedSystem) {
  40548. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  40549. }
  40550. else {
  40551. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  40552. }
  40553. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  40554. _this.previousPosition = null;
  40555. if (!noPreventDefault) {
  40556. evt.preventDefault();
  40557. }
  40558. };
  40559. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  40560. element.addEventListener("mousemove", this._onMouseMove, false);
  40561. };
  40562. FreeCameraMouseInput.prototype.detachControl = function (element) {
  40563. if (this._observer && element) {
  40564. this.camera.getScene().onPointerObservable.remove(this._observer);
  40565. if (this._onMouseMove) {
  40566. element.removeEventListener("mousemove", this._onMouseMove);
  40567. }
  40568. this._observer = null;
  40569. this._onMouseMove = null;
  40570. this.previousPosition = null;
  40571. }
  40572. };
  40573. FreeCameraMouseInput.prototype.getClassName = function () {
  40574. return "FreeCameraMouseInput";
  40575. };
  40576. FreeCameraMouseInput.prototype.getSimpleName = function () {
  40577. return "mouse";
  40578. };
  40579. __decorate([
  40580. BABYLON.serialize()
  40581. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  40582. __decorate([
  40583. BABYLON.serialize()
  40584. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  40585. return FreeCameraMouseInput;
  40586. }());
  40587. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  40588. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  40589. })(BABYLON || (BABYLON = {}));
  40590. //# sourceMappingURL=babylon.freeCameraMouseInput.js.map
  40591. var BABYLON;
  40592. (function (BABYLON) {
  40593. var FreeCameraKeyboardMoveInput = /** @class */ (function () {
  40594. function FreeCameraKeyboardMoveInput() {
  40595. this._keys = new Array();
  40596. this.keysUp = [38];
  40597. this.keysDown = [40];
  40598. this.keysLeft = [37];
  40599. this.keysRight = [39];
  40600. }
  40601. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  40602. var _this = this;
  40603. if (this._onCanvasBlurObserver) {
  40604. return;
  40605. }
  40606. this._scene = this.camera.getScene();
  40607. this._engine = this._scene.getEngine();
  40608. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  40609. _this._keys = [];
  40610. });
  40611. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  40612. var evt = info.event;
  40613. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  40614. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  40615. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  40616. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  40617. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  40618. var index = _this._keys.indexOf(evt.keyCode);
  40619. if (index === -1) {
  40620. _this._keys.push(evt.keyCode);
  40621. }
  40622. if (!noPreventDefault) {
  40623. evt.preventDefault();
  40624. }
  40625. }
  40626. }
  40627. else {
  40628. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  40629. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  40630. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  40631. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  40632. var index = _this._keys.indexOf(evt.keyCode);
  40633. if (index >= 0) {
  40634. _this._keys.splice(index, 1);
  40635. }
  40636. if (!noPreventDefault) {
  40637. evt.preventDefault();
  40638. }
  40639. }
  40640. }
  40641. });
  40642. };
  40643. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  40644. if (this._scene) {
  40645. if (this._onKeyboardObserver) {
  40646. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  40647. }
  40648. if (this._onCanvasBlurObserver) {
  40649. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  40650. }
  40651. this._onKeyboardObserver = null;
  40652. this._onCanvasBlurObserver = null;
  40653. }
  40654. this._keys = [];
  40655. };
  40656. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  40657. if (this._onKeyboardObserver) {
  40658. var camera = this.camera;
  40659. // Keyboard
  40660. for (var index = 0; index < this._keys.length; index++) {
  40661. var keyCode = this._keys[index];
  40662. var speed = camera._computeLocalCameraSpeed();
  40663. if (this.keysLeft.indexOf(keyCode) !== -1) {
  40664. camera._localDirection.copyFromFloats(-speed, 0, 0);
  40665. }
  40666. else if (this.keysUp.indexOf(keyCode) !== -1) {
  40667. camera._localDirection.copyFromFloats(0, 0, speed);
  40668. }
  40669. else if (this.keysRight.indexOf(keyCode) !== -1) {
  40670. camera._localDirection.copyFromFloats(speed, 0, 0);
  40671. }
  40672. else if (this.keysDown.indexOf(keyCode) !== -1) {
  40673. camera._localDirection.copyFromFloats(0, 0, -speed);
  40674. }
  40675. if (camera.getScene().useRightHandedSystem) {
  40676. camera._localDirection.z *= -1;
  40677. }
  40678. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  40679. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  40680. camera.cameraDirection.addInPlace(camera._transformedDirection);
  40681. }
  40682. }
  40683. };
  40684. FreeCameraKeyboardMoveInput.prototype.getClassName = function () {
  40685. return "FreeCameraKeyboardMoveInput";
  40686. };
  40687. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  40688. this._keys = [];
  40689. };
  40690. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  40691. return "keyboard";
  40692. };
  40693. __decorate([
  40694. BABYLON.serialize()
  40695. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  40696. __decorate([
  40697. BABYLON.serialize()
  40698. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  40699. __decorate([
  40700. BABYLON.serialize()
  40701. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  40702. __decorate([
  40703. BABYLON.serialize()
  40704. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  40705. return FreeCameraKeyboardMoveInput;
  40706. }());
  40707. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  40708. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  40709. })(BABYLON || (BABYLON = {}));
  40710. //# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map
  40711. var BABYLON;
  40712. (function (BABYLON) {
  40713. var FreeCameraInputsManager = /** @class */ (function (_super) {
  40714. __extends(FreeCameraInputsManager, _super);
  40715. function FreeCameraInputsManager(camera) {
  40716. return _super.call(this, camera) || this;
  40717. }
  40718. FreeCameraInputsManager.prototype.addKeyboard = function () {
  40719. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  40720. return this;
  40721. };
  40722. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  40723. if (touchEnabled === void 0) { touchEnabled = true; }
  40724. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  40725. return this;
  40726. };
  40727. FreeCameraInputsManager.prototype.addGamepad = function () {
  40728. this.add(new BABYLON.FreeCameraGamepadInput());
  40729. return this;
  40730. };
  40731. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  40732. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  40733. return this;
  40734. };
  40735. FreeCameraInputsManager.prototype.addTouch = function () {
  40736. this.add(new BABYLON.FreeCameraTouchInput());
  40737. return this;
  40738. };
  40739. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  40740. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  40741. return this;
  40742. };
  40743. return FreeCameraInputsManager;
  40744. }(BABYLON.CameraInputsManager));
  40745. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  40746. })(BABYLON || (BABYLON = {}));
  40747. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  40748. var BABYLON;
  40749. (function (BABYLON) {
  40750. var FreeCamera = /** @class */ (function (_super) {
  40751. __extends(FreeCamera, _super);
  40752. function FreeCamera(name, position, scene) {
  40753. var _this = _super.call(this, name, position, scene) || this;
  40754. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  40755. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  40756. _this.checkCollisions = false;
  40757. _this.applyGravity = false;
  40758. _this._needMoveForGravity = false;
  40759. _this._oldPosition = BABYLON.Vector3.Zero();
  40760. _this._diffPosition = BABYLON.Vector3.Zero();
  40761. _this._newPosition = BABYLON.Vector3.Zero();
  40762. // Collisions
  40763. _this._collisionMask = -1;
  40764. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  40765. if (collidedMesh === void 0) { collidedMesh = null; }
  40766. //TODO move this to the collision coordinator!
  40767. if (_this.getScene().workerCollisions)
  40768. newPosition.multiplyInPlace(_this._collider._radius);
  40769. var updatePosition = function (newPos) {
  40770. _this._newPosition.copyFrom(newPos);
  40771. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  40772. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  40773. _this.position.addInPlace(_this._diffPosition);
  40774. if (_this.onCollide && collidedMesh) {
  40775. _this.onCollide(collidedMesh);
  40776. }
  40777. }
  40778. };
  40779. updatePosition(newPosition);
  40780. };
  40781. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  40782. _this.inputs.addKeyboard().addMouse();
  40783. return _this;
  40784. }
  40785. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  40786. //-- begin properties for backward compatibility for inputs
  40787. /**
  40788. * Gets the input sensibility for a mouse input. (default is 2000.0)
  40789. * Higher values reduce sensitivity.
  40790. */
  40791. get: function () {
  40792. var mouse = this.inputs.attached["mouse"];
  40793. if (mouse)
  40794. return mouse.angularSensibility;
  40795. return 0;
  40796. },
  40797. /**
  40798. * Sets the input sensibility for a mouse input. (default is 2000.0)
  40799. * Higher values reduce sensitivity.
  40800. */
  40801. set: function (value) {
  40802. var mouse = this.inputs.attached["mouse"];
  40803. if (mouse)
  40804. mouse.angularSensibility = value;
  40805. },
  40806. enumerable: true,
  40807. configurable: true
  40808. });
  40809. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  40810. get: function () {
  40811. var keyboard = this.inputs.attached["keyboard"];
  40812. if (keyboard)
  40813. return keyboard.keysUp;
  40814. return [];
  40815. },
  40816. set: function (value) {
  40817. var keyboard = this.inputs.attached["keyboard"];
  40818. if (keyboard)
  40819. keyboard.keysUp = value;
  40820. },
  40821. enumerable: true,
  40822. configurable: true
  40823. });
  40824. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  40825. get: function () {
  40826. var keyboard = this.inputs.attached["keyboard"];
  40827. if (keyboard)
  40828. return keyboard.keysDown;
  40829. return [];
  40830. },
  40831. set: function (value) {
  40832. var keyboard = this.inputs.attached["keyboard"];
  40833. if (keyboard)
  40834. keyboard.keysDown = value;
  40835. },
  40836. enumerable: true,
  40837. configurable: true
  40838. });
  40839. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  40840. get: function () {
  40841. var keyboard = this.inputs.attached["keyboard"];
  40842. if (keyboard)
  40843. return keyboard.keysLeft;
  40844. return [];
  40845. },
  40846. set: function (value) {
  40847. var keyboard = this.inputs.attached["keyboard"];
  40848. if (keyboard)
  40849. keyboard.keysLeft = value;
  40850. },
  40851. enumerable: true,
  40852. configurable: true
  40853. });
  40854. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  40855. get: function () {
  40856. var keyboard = this.inputs.attached["keyboard"];
  40857. if (keyboard)
  40858. return keyboard.keysRight;
  40859. return [];
  40860. },
  40861. set: function (value) {
  40862. var keyboard = this.inputs.attached["keyboard"];
  40863. if (keyboard)
  40864. keyboard.keysRight = value;
  40865. },
  40866. enumerable: true,
  40867. configurable: true
  40868. });
  40869. // Controls
  40870. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  40871. this.inputs.attachElement(element, noPreventDefault);
  40872. };
  40873. FreeCamera.prototype.detachControl = function (element) {
  40874. this.inputs.detachElement(element);
  40875. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  40876. this.cameraRotation = new BABYLON.Vector2(0, 0);
  40877. };
  40878. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  40879. get: function () {
  40880. return this._collisionMask;
  40881. },
  40882. set: function (mask) {
  40883. this._collisionMask = !isNaN(mask) ? mask : -1;
  40884. },
  40885. enumerable: true,
  40886. configurable: true
  40887. });
  40888. FreeCamera.prototype._collideWithWorld = function (displacement) {
  40889. var globalPosition;
  40890. if (this.parent) {
  40891. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  40892. }
  40893. else {
  40894. globalPosition = this.position;
  40895. }
  40896. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  40897. this._oldPosition.addInPlace(this.ellipsoidOffset);
  40898. if (!this._collider) {
  40899. this._collider = new BABYLON.Collider();
  40900. }
  40901. this._collider._radius = this.ellipsoid;
  40902. this._collider.collisionMask = this._collisionMask;
  40903. //no need for clone, as long as gravity is not on.
  40904. var actualDisplacement = displacement;
  40905. //add gravity to the direction to prevent the dual-collision checking
  40906. if (this.applyGravity) {
  40907. //this prevents mending with cameraDirection, a global variable of the free camera class.
  40908. actualDisplacement = displacement.add(this.getScene().gravity);
  40909. }
  40910. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  40911. };
  40912. FreeCamera.prototype._checkInputs = function () {
  40913. if (!this._localDirection) {
  40914. this._localDirection = BABYLON.Vector3.Zero();
  40915. this._transformedDirection = BABYLON.Vector3.Zero();
  40916. }
  40917. this.inputs.checkInputs();
  40918. _super.prototype._checkInputs.call(this);
  40919. };
  40920. FreeCamera.prototype._decideIfNeedsToMove = function () {
  40921. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  40922. };
  40923. FreeCamera.prototype._updatePosition = function () {
  40924. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  40925. this._collideWithWorld(this.cameraDirection);
  40926. }
  40927. else {
  40928. _super.prototype._updatePosition.call(this);
  40929. }
  40930. };
  40931. FreeCamera.prototype.dispose = function () {
  40932. this.inputs.clear();
  40933. _super.prototype.dispose.call(this);
  40934. };
  40935. FreeCamera.prototype.getClassName = function () {
  40936. return "FreeCamera";
  40937. };
  40938. __decorate([
  40939. BABYLON.serializeAsVector3()
  40940. ], FreeCamera.prototype, "ellipsoid", void 0);
  40941. __decorate([
  40942. BABYLON.serializeAsVector3()
  40943. ], FreeCamera.prototype, "ellipsoidOffset", void 0);
  40944. __decorate([
  40945. BABYLON.serialize()
  40946. ], FreeCamera.prototype, "checkCollisions", void 0);
  40947. __decorate([
  40948. BABYLON.serialize()
  40949. ], FreeCamera.prototype, "applyGravity", void 0);
  40950. return FreeCamera;
  40951. }(BABYLON.TargetCamera));
  40952. BABYLON.FreeCamera = FreeCamera;
  40953. })(BABYLON || (BABYLON = {}));
  40954. //# sourceMappingURL=babylon.freeCamera.js.map
  40955. var BABYLON;
  40956. (function (BABYLON) {
  40957. var ArcRotateCameraKeyboardMoveInput = /** @class */ (function () {
  40958. function ArcRotateCameraKeyboardMoveInput() {
  40959. this._keys = new Array();
  40960. this.keysUp = [38];
  40961. this.keysDown = [40];
  40962. this.keysLeft = [37];
  40963. this.keysRight = [39];
  40964. this.keysReset = [220];
  40965. this.panningSensibility = 50.0;
  40966. this.zoomingSensibility = 25.0;
  40967. this.useAltToZoom = true;
  40968. }
  40969. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  40970. var _this = this;
  40971. if (this._onCanvasBlurObserver) {
  40972. return;
  40973. }
  40974. this._scene = this.camera.getScene();
  40975. this._engine = this._scene.getEngine();
  40976. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  40977. _this._keys = [];
  40978. });
  40979. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  40980. var evt = info.event;
  40981. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  40982. _this._ctrlPressed = evt.ctrlKey;
  40983. _this._altPressed = evt.altKey;
  40984. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  40985. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  40986. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  40987. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  40988. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  40989. var index = _this._keys.indexOf(evt.keyCode);
  40990. if (index === -1) {
  40991. _this._keys.push(evt.keyCode);
  40992. }
  40993. if (evt.preventDefault) {
  40994. if (!noPreventDefault) {
  40995. evt.preventDefault();
  40996. }
  40997. }
  40998. }
  40999. }
  41000. else {
  41001. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  41002. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  41003. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  41004. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  41005. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  41006. var index = _this._keys.indexOf(evt.keyCode);
  41007. if (index >= 0) {
  41008. _this._keys.splice(index, 1);
  41009. }
  41010. if (evt.preventDefault) {
  41011. if (!noPreventDefault) {
  41012. evt.preventDefault();
  41013. }
  41014. }
  41015. }
  41016. }
  41017. });
  41018. };
  41019. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  41020. if (this._scene) {
  41021. if (this._onKeyboardObserver) {
  41022. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  41023. }
  41024. if (this._onCanvasBlurObserver) {
  41025. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  41026. }
  41027. this._onKeyboardObserver = null;
  41028. this._onCanvasBlurObserver = null;
  41029. }
  41030. this._keys = [];
  41031. };
  41032. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  41033. if (this._onKeyboardObserver) {
  41034. var camera = this.camera;
  41035. for (var index = 0; index < this._keys.length; index++) {
  41036. var keyCode = this._keys[index];
  41037. if (this.keysLeft.indexOf(keyCode) !== -1) {
  41038. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  41039. camera.inertialPanningX -= 1 / this.panningSensibility;
  41040. }
  41041. else {
  41042. camera.inertialAlphaOffset -= 0.01;
  41043. }
  41044. }
  41045. else if (this.keysUp.indexOf(keyCode) !== -1) {
  41046. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  41047. camera.inertialPanningY += 1 / this.panningSensibility;
  41048. }
  41049. else if (this._altPressed && this.useAltToZoom) {
  41050. camera.inertialRadiusOffset += 1 / this.zoomingSensibility;
  41051. }
  41052. else {
  41053. camera.inertialBetaOffset -= 0.01;
  41054. }
  41055. }
  41056. else if (this.keysRight.indexOf(keyCode) !== -1) {
  41057. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  41058. camera.inertialPanningX += 1 / this.panningSensibility;
  41059. }
  41060. else {
  41061. camera.inertialAlphaOffset += 0.01;
  41062. }
  41063. }
  41064. else if (this.keysDown.indexOf(keyCode) !== -1) {
  41065. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  41066. camera.inertialPanningY -= 1 / this.panningSensibility;
  41067. }
  41068. else if (this._altPressed && this.useAltToZoom) {
  41069. camera.inertialRadiusOffset -= 1 / this.zoomingSensibility;
  41070. }
  41071. else {
  41072. camera.inertialBetaOffset += 0.01;
  41073. }
  41074. }
  41075. else if (this.keysReset.indexOf(keyCode) !== -1) {
  41076. camera.restoreState();
  41077. }
  41078. }
  41079. }
  41080. };
  41081. ArcRotateCameraKeyboardMoveInput.prototype.getClassName = function () {
  41082. return "ArcRotateCameraKeyboardMoveInput";
  41083. };
  41084. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  41085. return "keyboard";
  41086. };
  41087. __decorate([
  41088. BABYLON.serialize()
  41089. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  41090. __decorate([
  41091. BABYLON.serialize()
  41092. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  41093. __decorate([
  41094. BABYLON.serialize()
  41095. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  41096. __decorate([
  41097. BABYLON.serialize()
  41098. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  41099. __decorate([
  41100. BABYLON.serialize()
  41101. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysReset", void 0);
  41102. __decorate([
  41103. BABYLON.serialize()
  41104. ], ArcRotateCameraKeyboardMoveInput.prototype, "panningSensibility", void 0);
  41105. __decorate([
  41106. BABYLON.serialize()
  41107. ], ArcRotateCameraKeyboardMoveInput.prototype, "zoomingSensibility", void 0);
  41108. __decorate([
  41109. BABYLON.serialize()
  41110. ], ArcRotateCameraKeyboardMoveInput.prototype, "useAltToZoom", void 0);
  41111. return ArcRotateCameraKeyboardMoveInput;
  41112. }());
  41113. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  41114. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  41115. })(BABYLON || (BABYLON = {}));
  41116. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  41117. var BABYLON;
  41118. (function (BABYLON) {
  41119. var ArcRotateCameraMouseWheelInput = /** @class */ (function () {
  41120. function ArcRotateCameraMouseWheelInput() {
  41121. this.wheelPrecision = 3.0;
  41122. /**
  41123. * wheelDeltaPercentage will be used instead of wheelPrecision if different from 0.
  41124. * It defines the percentage of current camera.radius to use as delta when wheel is used.
  41125. */
  41126. this.wheelDeltaPercentage = 0;
  41127. }
  41128. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  41129. var _this = this;
  41130. this._wheel = function (p, s) {
  41131. //sanity check - this should be a PointerWheel event.
  41132. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  41133. return;
  41134. var event = p.event;
  41135. var delta = 0;
  41136. if (event.wheelDelta) {
  41137. delta = _this.wheelDeltaPercentage ? (event.wheelDelta * 0.01) * _this.camera.radius * _this.wheelDeltaPercentage : event.wheelDelta / (_this.wheelPrecision * 40);
  41138. }
  41139. else if (event.detail) {
  41140. delta = -event.detail / _this.wheelPrecision;
  41141. }
  41142. if (delta)
  41143. _this.camera.inertialRadiusOffset += delta;
  41144. if (event.preventDefault) {
  41145. if (!noPreventDefault) {
  41146. event.preventDefault();
  41147. }
  41148. }
  41149. };
  41150. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  41151. };
  41152. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  41153. if (this._observer && element) {
  41154. this.camera.getScene().onPointerObservable.remove(this._observer);
  41155. this._observer = null;
  41156. this._wheel = null;
  41157. }
  41158. };
  41159. ArcRotateCameraMouseWheelInput.prototype.getClassName = function () {
  41160. return "ArcRotateCameraMouseWheelInput";
  41161. };
  41162. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  41163. return "mousewheel";
  41164. };
  41165. __decorate([
  41166. BABYLON.serialize()
  41167. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  41168. __decorate([
  41169. BABYLON.serialize()
  41170. ], ArcRotateCameraMouseWheelInput.prototype, "wheelDeltaPercentage", void 0);
  41171. return ArcRotateCameraMouseWheelInput;
  41172. }());
  41173. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  41174. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  41175. })(BABYLON || (BABYLON = {}));
  41176. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  41177. var BABYLON;
  41178. (function (BABYLON) {
  41179. var ArcRotateCameraPointersInput = /** @class */ (function () {
  41180. function ArcRotateCameraPointersInput() {
  41181. this.buttons = [0, 1, 2];
  41182. this.angularSensibilityX = 1000.0;
  41183. this.angularSensibilityY = 1000.0;
  41184. this.pinchPrecision = 12.0;
  41185. /**
  41186. * pinchDeltaPercentage will be used instead of pinchPrecision if different from 0.
  41187. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  41188. */
  41189. this.pinchDeltaPercentage = 0;
  41190. this.panningSensibility = 1000.0;
  41191. this.multiTouchPanning = true;
  41192. this.multiTouchPanAndZoom = true;
  41193. this._isPanClick = false;
  41194. this.pinchInwards = true;
  41195. }
  41196. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  41197. var _this = this;
  41198. var engine = this.camera.getEngine();
  41199. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  41200. var pointA = null;
  41201. var pointB = null;
  41202. var previousPinchSquaredDistance = 0;
  41203. var initialDistance = 0;
  41204. var twoFingerActivityCount = 0;
  41205. var previousMultiTouchPanPosition = { x: 0, y: 0, isPaning: false, isPinching: false };
  41206. this._pointerInput = function (p, s) {
  41207. var evt = p.event;
  41208. var isTouch = p.event.pointerType === "touch";
  41209. if (engine.isInVRExclusivePointerMode) {
  41210. return;
  41211. }
  41212. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  41213. return;
  41214. }
  41215. var srcElement = (evt.srcElement || evt.target);
  41216. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  41217. try {
  41218. srcElement.setPointerCapture(evt.pointerId);
  41219. }
  41220. catch (e) {
  41221. //Nothing to do with the error. Execution will continue.
  41222. }
  41223. // Manage panning with pan button click
  41224. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  41225. // manage pointers
  41226. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  41227. if (pointA === null) {
  41228. pointA = cacheSoloPointer;
  41229. }
  41230. else if (pointB === null) {
  41231. pointB = cacheSoloPointer;
  41232. }
  41233. if (!noPreventDefault) {
  41234. evt.preventDefault();
  41235. element.focus();
  41236. }
  41237. }
  41238. else if (p.type === BABYLON.PointerEventTypes.POINTERDOUBLETAP) {
  41239. _this.camera.restoreState();
  41240. }
  41241. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  41242. try {
  41243. srcElement.releasePointerCapture(evt.pointerId);
  41244. }
  41245. catch (e) {
  41246. //Nothing to do with the error.
  41247. }
  41248. cacheSoloPointer = null;
  41249. previousPinchSquaredDistance = 0;
  41250. previousMultiTouchPanPosition.isPaning = false;
  41251. previousMultiTouchPanPosition.isPinching = false;
  41252. twoFingerActivityCount = 0;
  41253. initialDistance = 0;
  41254. if (!isTouch) {
  41255. pointB = null; // Mouse and pen are mono pointer
  41256. }
  41257. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  41258. //but emptying completly pointers collection is required to fix a bug on iPhone :
  41259. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  41260. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  41261. if (engine.badOS) {
  41262. pointA = pointB = null;
  41263. }
  41264. else {
  41265. //only remove the impacted pointer in case of multitouch allowing on most
  41266. //platforms switching from rotate to zoom and pan seamlessly.
  41267. if (pointB && pointA && pointA.pointerId == evt.pointerId) {
  41268. pointA = pointB;
  41269. pointB = null;
  41270. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  41271. }
  41272. else if (pointA && pointB && pointB.pointerId == evt.pointerId) {
  41273. pointB = null;
  41274. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  41275. }
  41276. else {
  41277. pointA = pointB = null;
  41278. }
  41279. }
  41280. if (!noPreventDefault) {
  41281. evt.preventDefault();
  41282. }
  41283. }
  41284. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  41285. if (!noPreventDefault) {
  41286. evt.preventDefault();
  41287. }
  41288. // One button down
  41289. if (pointA && pointB === null && cacheSoloPointer) {
  41290. if (_this.panningSensibility !== 0 &&
  41291. ((evt.ctrlKey && _this.camera._useCtrlForPanning) || _this._isPanClick)) {
  41292. _this.camera.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  41293. _this.camera.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  41294. }
  41295. else {
  41296. var offsetX = evt.clientX - cacheSoloPointer.x;
  41297. var offsetY = evt.clientY - cacheSoloPointer.y;
  41298. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  41299. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  41300. }
  41301. cacheSoloPointer.x = evt.clientX;
  41302. cacheSoloPointer.y = evt.clientY;
  41303. }
  41304. else if (pointA && pointB) {
  41305. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  41306. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  41307. ed.x = evt.clientX;
  41308. ed.y = evt.clientY;
  41309. var direction = _this.pinchInwards ? 1 : -1;
  41310. var distX = pointA.x - pointB.x;
  41311. var distY = pointA.y - pointB.y;
  41312. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  41313. var pinchDistance = Math.sqrt(pinchSquaredDistance);
  41314. if (previousPinchSquaredDistance === 0) {
  41315. initialDistance = pinchDistance;
  41316. previousPinchSquaredDistance = pinchSquaredDistance;
  41317. previousMultiTouchPanPosition.x = (pointA.x + pointB.x) / 2;
  41318. previousMultiTouchPanPosition.y = (pointA.y + pointB.y) / 2;
  41319. return;
  41320. }
  41321. if (_this.multiTouchPanAndZoom) {
  41322. if (_this.pinchDeltaPercentage) {
  41323. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  41324. }
  41325. else {
  41326. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  41327. (_this.pinchPrecision *
  41328. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  41329. direction);
  41330. }
  41331. if (_this.panningSensibility !== 0) {
  41332. var pointersCenterX = (pointA.x + pointB.x) / 2;
  41333. var pointersCenterY = (pointA.y + pointB.y) / 2;
  41334. var pointersCenterDistX = pointersCenterX - previousMultiTouchPanPosition.x;
  41335. var pointersCenterDistY = pointersCenterY - previousMultiTouchPanPosition.y;
  41336. previousMultiTouchPanPosition.x = pointersCenterX;
  41337. previousMultiTouchPanPosition.y = pointersCenterY;
  41338. _this.camera.inertialPanningX += -(pointersCenterDistX) / (_this.panningSensibility);
  41339. _this.camera.inertialPanningY += (pointersCenterDistY) / (_this.panningSensibility);
  41340. }
  41341. }
  41342. else {
  41343. twoFingerActivityCount++;
  41344. if (previousMultiTouchPanPosition.isPinching || (twoFingerActivityCount < 20 && Math.abs(pinchDistance - initialDistance) > _this.camera.pinchToPanMaxDistance)) {
  41345. if (_this.pinchDeltaPercentage) {
  41346. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  41347. }
  41348. else {
  41349. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  41350. (_this.pinchPrecision *
  41351. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  41352. direction);
  41353. }
  41354. previousMultiTouchPanPosition.isPaning = false;
  41355. previousMultiTouchPanPosition.isPinching = true;
  41356. }
  41357. else {
  41358. if (cacheSoloPointer && cacheSoloPointer.pointerId === ed.pointerId && _this.panningSensibility !== 0 && _this.multiTouchPanning) {
  41359. if (!previousMultiTouchPanPosition.isPaning) {
  41360. previousMultiTouchPanPosition.isPaning = true;
  41361. previousMultiTouchPanPosition.isPinching = false;
  41362. previousMultiTouchPanPosition.x = ed.x;
  41363. previousMultiTouchPanPosition.y = ed.y;
  41364. return;
  41365. }
  41366. _this.camera.inertialPanningX += -(ed.x - previousMultiTouchPanPosition.x) / (_this.panningSensibility);
  41367. _this.camera.inertialPanningY += (ed.y - previousMultiTouchPanPosition.y) / (_this.panningSensibility);
  41368. }
  41369. }
  41370. if (cacheSoloPointer && cacheSoloPointer.pointerId === evt.pointerId) {
  41371. previousMultiTouchPanPosition.x = ed.x;
  41372. previousMultiTouchPanPosition.y = ed.y;
  41373. }
  41374. }
  41375. previousPinchSquaredDistance = pinchSquaredDistance;
  41376. }
  41377. }
  41378. };
  41379. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE | BABYLON.PointerEventTypes._POINTERDOUBLETAP);
  41380. this._onContextMenu = function (evt) {
  41381. evt.preventDefault();
  41382. };
  41383. if (!this.camera._useCtrlForPanning) {
  41384. element.addEventListener("contextmenu", this._onContextMenu, false);
  41385. }
  41386. this._onLostFocus = function () {
  41387. //this._keys = [];
  41388. pointA = pointB = null;
  41389. previousPinchSquaredDistance = 0;
  41390. previousMultiTouchPanPosition.isPaning = false;
  41391. previousMultiTouchPanPosition.isPinching = false;
  41392. twoFingerActivityCount = 0;
  41393. cacheSoloPointer = null;
  41394. initialDistance = 0;
  41395. };
  41396. this._onMouseMove = function (evt) {
  41397. if (!engine.isPointerLock) {
  41398. return;
  41399. }
  41400. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  41401. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  41402. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  41403. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  41404. if (!noPreventDefault) {
  41405. evt.preventDefault();
  41406. }
  41407. };
  41408. this._onGestureStart = function (e) {
  41409. if (window.MSGesture === undefined) {
  41410. return;
  41411. }
  41412. if (!_this._MSGestureHandler) {
  41413. _this._MSGestureHandler = new MSGesture();
  41414. _this._MSGestureHandler.target = element;
  41415. }
  41416. _this._MSGestureHandler.addPointer(e.pointerId);
  41417. };
  41418. this._onGesture = function (e) {
  41419. _this.camera.radius *= e.scale;
  41420. if (e.preventDefault) {
  41421. if (!noPreventDefault) {
  41422. e.stopPropagation();
  41423. e.preventDefault();
  41424. }
  41425. }
  41426. };
  41427. element.addEventListener("mousemove", this._onMouseMove, false);
  41428. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  41429. element.addEventListener("MSGestureChange", this._onGesture, false);
  41430. BABYLON.Tools.RegisterTopRootEvents([
  41431. { name: "blur", handler: this._onLostFocus }
  41432. ]);
  41433. };
  41434. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  41435. if (this._onLostFocus) {
  41436. BABYLON.Tools.UnregisterTopRootEvents([
  41437. { name: "blur", handler: this._onLostFocus }
  41438. ]);
  41439. }
  41440. if (element && this._observer) {
  41441. this.camera.getScene().onPointerObservable.remove(this._observer);
  41442. this._observer = null;
  41443. if (this._onContextMenu) {
  41444. element.removeEventListener("contextmenu", this._onContextMenu);
  41445. }
  41446. if (this._onMouseMove) {
  41447. element.removeEventListener("mousemove", this._onMouseMove);
  41448. }
  41449. if (this._onGestureStart) {
  41450. element.removeEventListener("MSPointerDown", this._onGestureStart);
  41451. }
  41452. if (this._onGesture) {
  41453. element.removeEventListener("MSGestureChange", this._onGesture);
  41454. }
  41455. this._isPanClick = false;
  41456. this.pinchInwards = true;
  41457. this._onMouseMove = null;
  41458. this._onGestureStart = null;
  41459. this._onGesture = null;
  41460. this._MSGestureHandler = null;
  41461. this._onLostFocus = null;
  41462. this._onContextMenu = null;
  41463. }
  41464. };
  41465. ArcRotateCameraPointersInput.prototype.getClassName = function () {
  41466. return "ArcRotateCameraPointersInput";
  41467. };
  41468. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  41469. return "pointers";
  41470. };
  41471. __decorate([
  41472. BABYLON.serialize()
  41473. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  41474. __decorate([
  41475. BABYLON.serialize()
  41476. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  41477. __decorate([
  41478. BABYLON.serialize()
  41479. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  41480. __decorate([
  41481. BABYLON.serialize()
  41482. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  41483. __decorate([
  41484. BABYLON.serialize()
  41485. ], ArcRotateCameraPointersInput.prototype, "pinchDeltaPercentage", void 0);
  41486. __decorate([
  41487. BABYLON.serialize()
  41488. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  41489. __decorate([
  41490. BABYLON.serialize()
  41491. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanning", void 0);
  41492. __decorate([
  41493. BABYLON.serialize()
  41494. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanAndZoom", void 0);
  41495. return ArcRotateCameraPointersInput;
  41496. }());
  41497. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  41498. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  41499. })(BABYLON || (BABYLON = {}));
  41500. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  41501. var BABYLON;
  41502. (function (BABYLON) {
  41503. var ArcRotateCameraInputsManager = /** @class */ (function (_super) {
  41504. __extends(ArcRotateCameraInputsManager, _super);
  41505. function ArcRotateCameraInputsManager(camera) {
  41506. return _super.call(this, camera) || this;
  41507. }
  41508. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  41509. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  41510. return this;
  41511. };
  41512. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  41513. this.add(new BABYLON.ArcRotateCameraPointersInput());
  41514. return this;
  41515. };
  41516. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  41517. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  41518. return this;
  41519. };
  41520. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  41521. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  41522. return this;
  41523. };
  41524. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  41525. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  41526. return this;
  41527. };
  41528. return ArcRotateCameraInputsManager;
  41529. }(BABYLON.CameraInputsManager));
  41530. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  41531. })(BABYLON || (BABYLON = {}));
  41532. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  41533. var BABYLON;
  41534. (function (BABYLON) {
  41535. var ArcRotateCamera = /** @class */ (function (_super) {
  41536. __extends(ArcRotateCamera, _super);
  41537. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  41538. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  41539. _this.inertialAlphaOffset = 0;
  41540. _this.inertialBetaOffset = 0;
  41541. _this.inertialRadiusOffset = 0;
  41542. _this.lowerAlphaLimit = null;
  41543. _this.upperAlphaLimit = null;
  41544. _this.lowerBetaLimit = 0.01;
  41545. _this.upperBetaLimit = Math.PI;
  41546. _this.lowerRadiusLimit = null;
  41547. _this.upperRadiusLimit = null;
  41548. _this.inertialPanningX = 0;
  41549. _this.inertialPanningY = 0;
  41550. _this.pinchToPanMaxDistance = 20;
  41551. _this.panningDistanceLimit = null;
  41552. _this.panningOriginTarget = BABYLON.Vector3.Zero();
  41553. _this.panningInertia = 0.9;
  41554. //-- end properties for backward compatibility for inputs
  41555. _this.zoomOnFactor = 1;
  41556. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  41557. _this.allowUpsideDown = true;
  41558. _this._viewMatrix = new BABYLON.Matrix();
  41559. // Panning
  41560. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  41561. _this.onMeshTargetChangedObservable = new BABYLON.Observable();
  41562. _this.checkCollisions = false;
  41563. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  41564. _this._previousPosition = BABYLON.Vector3.Zero();
  41565. _this._collisionVelocity = BABYLON.Vector3.Zero();
  41566. _this._newPosition = BABYLON.Vector3.Zero();
  41567. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  41568. if (collidedMesh === void 0) { collidedMesh = null; }
  41569. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  41570. newPosition.multiplyInPlace(_this._collider._radius);
  41571. }
  41572. if (!collidedMesh) {
  41573. _this._previousPosition.copyFrom(_this.position);
  41574. }
  41575. else {
  41576. _this.setPosition(newPosition);
  41577. if (_this.onCollide) {
  41578. _this.onCollide(collidedMesh);
  41579. }
  41580. }
  41581. // Recompute because of constraints
  41582. var cosa = Math.cos(_this.alpha);
  41583. var sina = Math.sin(_this.alpha);
  41584. var cosb = Math.cos(_this.beta);
  41585. var sinb = Math.sin(_this.beta);
  41586. if (sinb === 0) {
  41587. sinb = 0.0001;
  41588. }
  41589. var target = _this._getTargetPosition();
  41590. target.addToRef(new BABYLON.Vector3(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb), _this._newPosition);
  41591. _this.position.copyFrom(_this._newPosition);
  41592. var up = _this.upVector;
  41593. if (_this.allowUpsideDown && _this.beta < 0) {
  41594. up = up.clone();
  41595. up = up.negate();
  41596. }
  41597. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  41598. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  41599. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  41600. _this._collisionTriggered = false;
  41601. };
  41602. _this._target = BABYLON.Vector3.Zero();
  41603. if (target) {
  41604. _this.setTarget(target);
  41605. }
  41606. _this.alpha = alpha;
  41607. _this.beta = beta;
  41608. _this.radius = radius;
  41609. _this.getViewMatrix();
  41610. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  41611. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  41612. return _this;
  41613. }
  41614. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  41615. get: function () {
  41616. return this._target;
  41617. },
  41618. set: function (value) {
  41619. this.setTarget(value);
  41620. },
  41621. enumerable: true,
  41622. configurable: true
  41623. });
  41624. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  41625. //-- begin properties for backward compatibility for inputs
  41626. get: function () {
  41627. var pointers = this.inputs.attached["pointers"];
  41628. if (pointers)
  41629. return pointers.angularSensibilityX;
  41630. return 0;
  41631. },
  41632. set: function (value) {
  41633. var pointers = this.inputs.attached["pointers"];
  41634. if (pointers) {
  41635. pointers.angularSensibilityX = value;
  41636. }
  41637. },
  41638. enumerable: true,
  41639. configurable: true
  41640. });
  41641. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  41642. get: function () {
  41643. var pointers = this.inputs.attached["pointers"];
  41644. if (pointers)
  41645. return pointers.angularSensibilityY;
  41646. return 0;
  41647. },
  41648. set: function (value) {
  41649. var pointers = this.inputs.attached["pointers"];
  41650. if (pointers) {
  41651. pointers.angularSensibilityY = value;
  41652. }
  41653. },
  41654. enumerable: true,
  41655. configurable: true
  41656. });
  41657. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  41658. get: function () {
  41659. var pointers = this.inputs.attached["pointers"];
  41660. if (pointers)
  41661. return pointers.pinchPrecision;
  41662. return 0;
  41663. },
  41664. set: function (value) {
  41665. var pointers = this.inputs.attached["pointers"];
  41666. if (pointers) {
  41667. pointers.pinchPrecision = value;
  41668. }
  41669. },
  41670. enumerable: true,
  41671. configurable: true
  41672. });
  41673. Object.defineProperty(ArcRotateCamera.prototype, "pinchDeltaPercentage", {
  41674. get: function () {
  41675. var pointers = this.inputs.attached["pointers"];
  41676. if (pointers)
  41677. return pointers.pinchDeltaPercentage;
  41678. return 0;
  41679. },
  41680. set: function (value) {
  41681. var pointers = this.inputs.attached["pointers"];
  41682. if (pointers) {
  41683. pointers.pinchDeltaPercentage = value;
  41684. }
  41685. },
  41686. enumerable: true,
  41687. configurable: true
  41688. });
  41689. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  41690. get: function () {
  41691. var pointers = this.inputs.attached["pointers"];
  41692. if (pointers)
  41693. return pointers.panningSensibility;
  41694. return 0;
  41695. },
  41696. set: function (value) {
  41697. var pointers = this.inputs.attached["pointers"];
  41698. if (pointers) {
  41699. pointers.panningSensibility = value;
  41700. }
  41701. },
  41702. enumerable: true,
  41703. configurable: true
  41704. });
  41705. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  41706. get: function () {
  41707. var keyboard = this.inputs.attached["keyboard"];
  41708. if (keyboard)
  41709. return keyboard.keysUp;
  41710. return [];
  41711. },
  41712. set: function (value) {
  41713. var keyboard = this.inputs.attached["keyboard"];
  41714. if (keyboard)
  41715. keyboard.keysUp = value;
  41716. },
  41717. enumerable: true,
  41718. configurable: true
  41719. });
  41720. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  41721. get: function () {
  41722. var keyboard = this.inputs.attached["keyboard"];
  41723. if (keyboard)
  41724. return keyboard.keysDown;
  41725. return [];
  41726. },
  41727. set: function (value) {
  41728. var keyboard = this.inputs.attached["keyboard"];
  41729. if (keyboard)
  41730. keyboard.keysDown = value;
  41731. },
  41732. enumerable: true,
  41733. configurable: true
  41734. });
  41735. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  41736. get: function () {
  41737. var keyboard = this.inputs.attached["keyboard"];
  41738. if (keyboard)
  41739. return keyboard.keysLeft;
  41740. return [];
  41741. },
  41742. set: function (value) {
  41743. var keyboard = this.inputs.attached["keyboard"];
  41744. if (keyboard)
  41745. keyboard.keysLeft = value;
  41746. },
  41747. enumerable: true,
  41748. configurable: true
  41749. });
  41750. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  41751. get: function () {
  41752. var keyboard = this.inputs.attached["keyboard"];
  41753. if (keyboard)
  41754. return keyboard.keysRight;
  41755. return [];
  41756. },
  41757. set: function (value) {
  41758. var keyboard = this.inputs.attached["keyboard"];
  41759. if (keyboard)
  41760. keyboard.keysRight = value;
  41761. },
  41762. enumerable: true,
  41763. configurable: true
  41764. });
  41765. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  41766. get: function () {
  41767. var mousewheel = this.inputs.attached["mousewheel"];
  41768. if (mousewheel)
  41769. return mousewheel.wheelPrecision;
  41770. return 0;
  41771. },
  41772. set: function (value) {
  41773. var mousewheel = this.inputs.attached["mousewheel"];
  41774. if (mousewheel)
  41775. mousewheel.wheelPrecision = value;
  41776. },
  41777. enumerable: true,
  41778. configurable: true
  41779. });
  41780. Object.defineProperty(ArcRotateCamera.prototype, "wheelDeltaPercentage", {
  41781. get: function () {
  41782. var mousewheel = this.inputs.attached["mousewheel"];
  41783. if (mousewheel)
  41784. return mousewheel.wheelDeltaPercentage;
  41785. return 0;
  41786. },
  41787. set: function (value) {
  41788. var mousewheel = this.inputs.attached["mousewheel"];
  41789. if (mousewheel)
  41790. mousewheel.wheelDeltaPercentage = value;
  41791. },
  41792. enumerable: true,
  41793. configurable: true
  41794. });
  41795. Object.defineProperty(ArcRotateCamera.prototype, "bouncingBehavior", {
  41796. get: function () {
  41797. return this._bouncingBehavior;
  41798. },
  41799. enumerable: true,
  41800. configurable: true
  41801. });
  41802. Object.defineProperty(ArcRotateCamera.prototype, "useBouncingBehavior", {
  41803. get: function () {
  41804. return this._bouncingBehavior != null;
  41805. },
  41806. set: function (value) {
  41807. if (value === this.useBouncingBehavior) {
  41808. return;
  41809. }
  41810. if (value) {
  41811. this._bouncingBehavior = new BABYLON.BouncingBehavior();
  41812. this.addBehavior(this._bouncingBehavior);
  41813. }
  41814. else if (this._bouncingBehavior) {
  41815. this.removeBehavior(this._bouncingBehavior);
  41816. this._bouncingBehavior = null;
  41817. }
  41818. },
  41819. enumerable: true,
  41820. configurable: true
  41821. });
  41822. Object.defineProperty(ArcRotateCamera.prototype, "framingBehavior", {
  41823. get: function () {
  41824. return this._framingBehavior;
  41825. },
  41826. enumerable: true,
  41827. configurable: true
  41828. });
  41829. Object.defineProperty(ArcRotateCamera.prototype, "useFramingBehavior", {
  41830. get: function () {
  41831. return this._framingBehavior != null;
  41832. },
  41833. set: function (value) {
  41834. if (value === this.useFramingBehavior) {
  41835. return;
  41836. }
  41837. if (value) {
  41838. this._framingBehavior = new BABYLON.FramingBehavior();
  41839. this.addBehavior(this._framingBehavior);
  41840. }
  41841. else if (this._framingBehavior) {
  41842. this.removeBehavior(this._framingBehavior);
  41843. this._framingBehavior = null;
  41844. }
  41845. },
  41846. enumerable: true,
  41847. configurable: true
  41848. });
  41849. Object.defineProperty(ArcRotateCamera.prototype, "autoRotationBehavior", {
  41850. get: function () {
  41851. return this._autoRotationBehavior;
  41852. },
  41853. enumerable: true,
  41854. configurable: true
  41855. });
  41856. Object.defineProperty(ArcRotateCamera.prototype, "useAutoRotationBehavior", {
  41857. get: function () {
  41858. return this._autoRotationBehavior != null;
  41859. },
  41860. set: function (value) {
  41861. if (value === this.useAutoRotationBehavior) {
  41862. return;
  41863. }
  41864. if (value) {
  41865. this._autoRotationBehavior = new BABYLON.AutoRotationBehavior();
  41866. this.addBehavior(this._autoRotationBehavior);
  41867. }
  41868. else if (this._autoRotationBehavior) {
  41869. this.removeBehavior(this._autoRotationBehavior);
  41870. this._autoRotationBehavior = null;
  41871. }
  41872. },
  41873. enumerable: true,
  41874. configurable: true
  41875. });
  41876. // Cache
  41877. ArcRotateCamera.prototype._initCache = function () {
  41878. _super.prototype._initCache.call(this);
  41879. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  41880. this._cache.alpha = undefined;
  41881. this._cache.beta = undefined;
  41882. this._cache.radius = undefined;
  41883. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  41884. };
  41885. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  41886. if (!ignoreParentClass) {
  41887. _super.prototype._updateCache.call(this);
  41888. }
  41889. this._cache._target.copyFrom(this._getTargetPosition());
  41890. this._cache.alpha = this.alpha;
  41891. this._cache.beta = this.beta;
  41892. this._cache.radius = this.radius;
  41893. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  41894. };
  41895. ArcRotateCamera.prototype._getTargetPosition = function () {
  41896. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  41897. var pos = this._targetHost.getAbsolutePosition();
  41898. if (this._targetBoundingCenter) {
  41899. pos.addToRef(this._targetBoundingCenter, this._target);
  41900. }
  41901. else {
  41902. this._target.copyFrom(pos);
  41903. }
  41904. }
  41905. var lockedTargetPosition = this._getLockedTargetPosition();
  41906. if (lockedTargetPosition) {
  41907. return lockedTargetPosition;
  41908. }
  41909. return this._target;
  41910. };
  41911. ArcRotateCamera.prototype.storeState = function () {
  41912. this._storedAlpha = this.alpha;
  41913. this._storedBeta = this.beta;
  41914. this._storedRadius = this.radius;
  41915. this._storedTarget = this._getTargetPosition().clone();
  41916. return _super.prototype.storeState.call(this);
  41917. };
  41918. /**
  41919. * Restored camera state. You must call storeState() first
  41920. */
  41921. ArcRotateCamera.prototype._restoreStateValues = function () {
  41922. if (!_super.prototype._restoreStateValues.call(this)) {
  41923. return false;
  41924. }
  41925. this.alpha = this._storedAlpha;
  41926. this.beta = this._storedBeta;
  41927. this.radius = this._storedRadius;
  41928. this.setTarget(this._storedTarget.clone());
  41929. this.inertialAlphaOffset = 0;
  41930. this.inertialBetaOffset = 0;
  41931. this.inertialRadiusOffset = 0;
  41932. this.inertialPanningX = 0;
  41933. this.inertialPanningY = 0;
  41934. return true;
  41935. };
  41936. // Synchronized
  41937. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  41938. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  41939. return false;
  41940. return this._cache._target.equals(this._getTargetPosition())
  41941. && this._cache.alpha === this.alpha
  41942. && this._cache.beta === this.beta
  41943. && this._cache.radius === this.radius
  41944. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  41945. };
  41946. // Methods
  41947. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  41948. var _this = this;
  41949. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  41950. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  41951. this._useCtrlForPanning = useCtrlForPanning;
  41952. this._panningMouseButton = panningMouseButton;
  41953. this.inputs.attachElement(element, noPreventDefault);
  41954. this._reset = function () {
  41955. _this.inertialAlphaOffset = 0;
  41956. _this.inertialBetaOffset = 0;
  41957. _this.inertialRadiusOffset = 0;
  41958. _this.inertialPanningX = 0;
  41959. _this.inertialPanningY = 0;
  41960. };
  41961. };
  41962. ArcRotateCamera.prototype.detachControl = function (element) {
  41963. this.inputs.detachElement(element);
  41964. if (this._reset) {
  41965. this._reset();
  41966. }
  41967. };
  41968. ArcRotateCamera.prototype._checkInputs = function () {
  41969. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  41970. if (this._collisionTriggered) {
  41971. return;
  41972. }
  41973. this.inputs.checkInputs();
  41974. // Inertia
  41975. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  41976. if (this.getScene().useRightHandedSystem) {
  41977. this.alpha -= this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  41978. }
  41979. else {
  41980. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  41981. }
  41982. this.beta += this.inertialBetaOffset;
  41983. this.radius -= this.inertialRadiusOffset;
  41984. this.inertialAlphaOffset *= this.inertia;
  41985. this.inertialBetaOffset *= this.inertia;
  41986. this.inertialRadiusOffset *= this.inertia;
  41987. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  41988. this.inertialAlphaOffset = 0;
  41989. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  41990. this.inertialBetaOffset = 0;
  41991. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
  41992. this.inertialRadiusOffset = 0;
  41993. }
  41994. // Panning inertia
  41995. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  41996. if (!this._localDirection) {
  41997. this._localDirection = BABYLON.Vector3.Zero();
  41998. this._transformedDirection = BABYLON.Vector3.Zero();
  41999. }
  42000. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  42001. this._localDirection.multiplyInPlace(this.panningAxis);
  42002. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  42003. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  42004. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  42005. if (!this.panningAxis.y) {
  42006. this._transformedDirection.y = 0;
  42007. }
  42008. if (!this._targetHost) {
  42009. if (this.panningDistanceLimit) {
  42010. this._transformedDirection.addInPlace(this._target);
  42011. var distanceSquared = BABYLON.Vector3.DistanceSquared(this._transformedDirection, this.panningOriginTarget);
  42012. if (distanceSquared <= (this.panningDistanceLimit * this.panningDistanceLimit)) {
  42013. this._target.copyFrom(this._transformedDirection);
  42014. }
  42015. }
  42016. else {
  42017. this._target.addInPlace(this._transformedDirection);
  42018. }
  42019. }
  42020. this.inertialPanningX *= this.panningInertia;
  42021. this.inertialPanningY *= this.panningInertia;
  42022. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
  42023. this.inertialPanningX = 0;
  42024. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
  42025. this.inertialPanningY = 0;
  42026. }
  42027. // Limits
  42028. this._checkLimits();
  42029. _super.prototype._checkInputs.call(this);
  42030. };
  42031. ArcRotateCamera.prototype._checkLimits = function () {
  42032. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  42033. if (this.allowUpsideDown && this.beta > Math.PI) {
  42034. this.beta = this.beta - (2 * Math.PI);
  42035. }
  42036. }
  42037. else {
  42038. if (this.beta < this.lowerBetaLimit) {
  42039. this.beta = this.lowerBetaLimit;
  42040. }
  42041. }
  42042. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  42043. if (this.allowUpsideDown && this.beta < -Math.PI) {
  42044. this.beta = this.beta + (2 * Math.PI);
  42045. }
  42046. }
  42047. else {
  42048. if (this.beta > this.upperBetaLimit) {
  42049. this.beta = this.upperBetaLimit;
  42050. }
  42051. }
  42052. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  42053. this.alpha = this.lowerAlphaLimit;
  42054. }
  42055. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  42056. this.alpha = this.upperAlphaLimit;
  42057. }
  42058. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  42059. this.radius = this.lowerRadiusLimit;
  42060. }
  42061. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  42062. this.radius = this.upperRadiusLimit;
  42063. }
  42064. };
  42065. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  42066. var radiusv3 = this.position.subtract(this._getTargetPosition());
  42067. this.radius = radiusv3.length();
  42068. if (this.radius === 0) {
  42069. this.radius = 0.0001; // Just to avoid division by zero
  42070. }
  42071. // Alpha
  42072. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  42073. if (radiusv3.z < 0) {
  42074. this.alpha = 2 * Math.PI - this.alpha;
  42075. }
  42076. // Beta
  42077. this.beta = Math.acos(radiusv3.y / this.radius);
  42078. this._checkLimits();
  42079. };
  42080. ArcRotateCamera.prototype.setPosition = function (position) {
  42081. if (this.position.equals(position)) {
  42082. return;
  42083. }
  42084. this.position.copyFrom(position);
  42085. this.rebuildAnglesAndRadius();
  42086. };
  42087. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  42088. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  42089. if (allowSamePosition === void 0) { allowSamePosition = false; }
  42090. if (target.getBoundingInfo) {
  42091. if (toBoundingCenter) {
  42092. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  42093. }
  42094. else {
  42095. this._targetBoundingCenter = null;
  42096. }
  42097. this._targetHost = target;
  42098. this._target = this._getTargetPosition();
  42099. this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);
  42100. }
  42101. else {
  42102. var newTarget = target;
  42103. var currentTarget = this._getTargetPosition();
  42104. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  42105. return;
  42106. }
  42107. this._targetHost = null;
  42108. this._target = newTarget;
  42109. this._targetBoundingCenter = null;
  42110. this.onMeshTargetChangedObservable.notifyObservers(null);
  42111. }
  42112. this.rebuildAnglesAndRadius();
  42113. };
  42114. ArcRotateCamera.prototype._getViewMatrix = function () {
  42115. // Compute
  42116. var cosa = Math.cos(this.alpha);
  42117. var sina = Math.sin(this.alpha);
  42118. var cosb = Math.cos(this.beta);
  42119. var sinb = Math.sin(this.beta);
  42120. if (sinb === 0) {
  42121. sinb = 0.0001;
  42122. }
  42123. var target = this._getTargetPosition();
  42124. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this._newPosition);
  42125. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  42126. if (!this._collider) {
  42127. this._collider = new BABYLON.Collider();
  42128. }
  42129. this._collider._radius = this.collisionRadius;
  42130. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  42131. this._collisionTriggered = true;
  42132. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  42133. }
  42134. else {
  42135. this.position.copyFrom(this._newPosition);
  42136. var up = this.upVector;
  42137. if (this.allowUpsideDown && sinb < 0) {
  42138. up = up.clone();
  42139. up = up.negate();
  42140. }
  42141. if (this.getScene().useRightHandedSystem) {
  42142. BABYLON.Matrix.LookAtRHToRef(this.position, target, up, this._viewMatrix);
  42143. }
  42144. else {
  42145. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  42146. }
  42147. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  42148. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  42149. }
  42150. this._currentTarget = target;
  42151. return this._viewMatrix;
  42152. };
  42153. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  42154. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  42155. meshes = meshes || this.getScene().meshes;
  42156. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  42157. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  42158. this.radius = distance * this.zoomOnFactor;
  42159. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  42160. };
  42161. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  42162. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  42163. var meshesOrMinMaxVector;
  42164. var distance;
  42165. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  42166. var meshes = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  42167. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshes);
  42168. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  42169. }
  42170. else {
  42171. var minMaxVectorAndDistance = meshesOrMinMaxVectorAndDistance;
  42172. meshesOrMinMaxVector = minMaxVectorAndDistance;
  42173. distance = minMaxVectorAndDistance.distance;
  42174. }
  42175. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  42176. if (!doNotUpdateMaxZ) {
  42177. this.maxZ = distance * 2;
  42178. }
  42179. };
  42180. /**
  42181. * @override
  42182. * Override Camera.createRigCamera
  42183. */
  42184. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  42185. var alphaShift = 0;
  42186. switch (this.cameraRigMode) {
  42187. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  42188. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  42189. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  42190. case BABYLON.Camera.RIG_MODE_VR:
  42191. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  42192. break;
  42193. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  42194. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  42195. break;
  42196. }
  42197. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  42198. rigCam._cameraRigParams = {};
  42199. return rigCam;
  42200. };
  42201. /**
  42202. * @override
  42203. * Override Camera._updateRigCameras
  42204. */
  42205. ArcRotateCamera.prototype._updateRigCameras = function () {
  42206. var camLeft = this._rigCameras[0];
  42207. var camRight = this._rigCameras[1];
  42208. camLeft.beta = camRight.beta = this.beta;
  42209. camLeft.radius = camRight.radius = this.radius;
  42210. switch (this.cameraRigMode) {
  42211. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  42212. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  42213. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  42214. case BABYLON.Camera.RIG_MODE_VR:
  42215. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  42216. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  42217. break;
  42218. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  42219. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  42220. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  42221. break;
  42222. }
  42223. _super.prototype._updateRigCameras.call(this);
  42224. };
  42225. ArcRotateCamera.prototype.dispose = function () {
  42226. this.inputs.clear();
  42227. _super.prototype.dispose.call(this);
  42228. };
  42229. ArcRotateCamera.prototype.getClassName = function () {
  42230. return "ArcRotateCamera";
  42231. };
  42232. __decorate([
  42233. BABYLON.serialize()
  42234. ], ArcRotateCamera.prototype, "alpha", void 0);
  42235. __decorate([
  42236. BABYLON.serialize()
  42237. ], ArcRotateCamera.prototype, "beta", void 0);
  42238. __decorate([
  42239. BABYLON.serialize()
  42240. ], ArcRotateCamera.prototype, "radius", void 0);
  42241. __decorate([
  42242. BABYLON.serializeAsVector3("target")
  42243. ], ArcRotateCamera.prototype, "_target", void 0);
  42244. __decorate([
  42245. BABYLON.serialize()
  42246. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  42247. __decorate([
  42248. BABYLON.serialize()
  42249. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  42250. __decorate([
  42251. BABYLON.serialize()
  42252. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  42253. __decorate([
  42254. BABYLON.serialize()
  42255. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  42256. __decorate([
  42257. BABYLON.serialize()
  42258. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  42259. __decorate([
  42260. BABYLON.serialize()
  42261. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  42262. __decorate([
  42263. BABYLON.serialize()
  42264. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  42265. __decorate([
  42266. BABYLON.serialize()
  42267. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  42268. __decorate([
  42269. BABYLON.serialize()
  42270. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  42271. __decorate([
  42272. BABYLON.serialize()
  42273. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  42274. __decorate([
  42275. BABYLON.serialize()
  42276. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  42277. __decorate([
  42278. BABYLON.serialize()
  42279. ], ArcRotateCamera.prototype, "pinchToPanMaxDistance", void 0);
  42280. __decorate([
  42281. BABYLON.serialize()
  42282. ], ArcRotateCamera.prototype, "panningDistanceLimit", void 0);
  42283. __decorate([
  42284. BABYLON.serializeAsVector3()
  42285. ], ArcRotateCamera.prototype, "panningOriginTarget", void 0);
  42286. __decorate([
  42287. BABYLON.serialize()
  42288. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  42289. __decorate([
  42290. BABYLON.serialize()
  42291. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  42292. __decorate([
  42293. BABYLON.serialize()
  42294. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  42295. return ArcRotateCamera;
  42296. }(BABYLON.TargetCamera));
  42297. BABYLON.ArcRotateCamera = ArcRotateCamera;
  42298. })(BABYLON || (BABYLON = {}));
  42299. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  42300. var BABYLON;
  42301. (function (BABYLON) {
  42302. var HemisphericLight = /** @class */ (function (_super) {
  42303. __extends(HemisphericLight, _super);
  42304. /**
  42305. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  42306. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  42307. * The HemisphericLight can't cast shadows.
  42308. * Documentation : http://doc.babylonjs.com/tutorials/lights
  42309. */
  42310. function HemisphericLight(name, direction, scene) {
  42311. var _this = _super.call(this, name, scene) || this;
  42312. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  42313. _this.direction = direction || BABYLON.Vector3.Up();
  42314. return _this;
  42315. }
  42316. HemisphericLight.prototype._buildUniformLayout = function () {
  42317. this._uniformBuffer.addUniform("vLightData", 4);
  42318. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  42319. this._uniformBuffer.addUniform("vLightSpecular", 3);
  42320. this._uniformBuffer.addUniform("vLightGround", 3);
  42321. this._uniformBuffer.addUniform("shadowsInfo", 3);
  42322. this._uniformBuffer.addUniform("depthValues", 2);
  42323. this._uniformBuffer.create();
  42324. };
  42325. /**
  42326. * Returns the string "HemisphericLight".
  42327. */
  42328. HemisphericLight.prototype.getClassName = function () {
  42329. return "HemisphericLight";
  42330. };
  42331. /**
  42332. * Sets the HemisphericLight direction towards the passed target (Vector3).
  42333. * Returns the updated direction.
  42334. */
  42335. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  42336. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  42337. return this.direction;
  42338. };
  42339. HemisphericLight.prototype.getShadowGenerator = function () {
  42340. return null;
  42341. };
  42342. /**
  42343. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  42344. * Returns the HemisphericLight.
  42345. */
  42346. HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) {
  42347. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  42348. this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);
  42349. this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
  42350. return this;
  42351. };
  42352. HemisphericLight.prototype._getWorldMatrix = function () {
  42353. if (!this._worldMatrix) {
  42354. this._worldMatrix = BABYLON.Matrix.Identity();
  42355. }
  42356. return this._worldMatrix;
  42357. };
  42358. /**
  42359. * Returns the integer 3.
  42360. */
  42361. HemisphericLight.prototype.getTypeID = function () {
  42362. return BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT;
  42363. };
  42364. __decorate([
  42365. BABYLON.serializeAsColor3()
  42366. ], HemisphericLight.prototype, "groundColor", void 0);
  42367. __decorate([
  42368. BABYLON.serializeAsVector3()
  42369. ], HemisphericLight.prototype, "direction", void 0);
  42370. return HemisphericLight;
  42371. }(BABYLON.Light));
  42372. BABYLON.HemisphericLight = HemisphericLight;
  42373. })(BABYLON || (BABYLON = {}));
  42374. //# sourceMappingURL=babylon.hemisphericLight.js.map
  42375. var BABYLON;
  42376. (function (BABYLON) {
  42377. var ShadowLight = /** @class */ (function (_super) {
  42378. __extends(ShadowLight, _super);
  42379. function ShadowLight() {
  42380. var _this = _super !== null && _super.apply(this, arguments) || this;
  42381. _this._needProjectionMatrixCompute = true;
  42382. return _this;
  42383. }
  42384. Object.defineProperty(ShadowLight.prototype, "direction", {
  42385. get: function () {
  42386. return this._direction;
  42387. },
  42388. set: function (value) {
  42389. this._direction = value;
  42390. },
  42391. enumerable: true,
  42392. configurable: true
  42393. });
  42394. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  42395. get: function () {
  42396. return this._shadowMinZ;
  42397. },
  42398. set: function (value) {
  42399. this._shadowMinZ = value;
  42400. this.forceProjectionMatrixCompute();
  42401. },
  42402. enumerable: true,
  42403. configurable: true
  42404. });
  42405. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  42406. get: function () {
  42407. return this._shadowMaxZ;
  42408. },
  42409. set: function (value) {
  42410. this._shadowMaxZ = value;
  42411. this.forceProjectionMatrixCompute();
  42412. },
  42413. enumerable: true,
  42414. configurable: true
  42415. });
  42416. /**
  42417. * Computes the light transformed position/direction in case the light is parented. Returns true if parented, else false.
  42418. */
  42419. ShadowLight.prototype.computeTransformedInformation = function () {
  42420. if (this.parent && this.parent.getWorldMatrix) {
  42421. if (!this.transformedPosition) {
  42422. this.transformedPosition = BABYLON.Vector3.Zero();
  42423. }
  42424. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  42425. // In case the direction is present.
  42426. if (this.direction) {
  42427. if (!this.transformedDirection) {
  42428. this.transformedDirection = BABYLON.Vector3.Zero();
  42429. }
  42430. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  42431. }
  42432. return true;
  42433. }
  42434. return false;
  42435. };
  42436. /**
  42437. * Return the depth scale used for the shadow map.
  42438. */
  42439. ShadowLight.prototype.getDepthScale = function () {
  42440. return 50.0;
  42441. };
  42442. /**
  42443. * Returns the light direction (Vector3) for any passed face index.
  42444. */
  42445. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  42446. return this.transformedDirection ? this.transformedDirection : this.direction;
  42447. };
  42448. /**
  42449. * Returns the ShadowLight absolute position in the World.
  42450. */
  42451. ShadowLight.prototype.getAbsolutePosition = function () {
  42452. return this.transformedPosition ? this.transformedPosition : this.position;
  42453. };
  42454. /**
  42455. * Sets the ShadowLight direction toward the passed target (Vector3).
  42456. * Returns the updated ShadowLight direction (Vector3).
  42457. */
  42458. ShadowLight.prototype.setDirectionToTarget = function (target) {
  42459. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  42460. return this.direction;
  42461. };
  42462. /**
  42463. * Returns the light rotation (Vector3).
  42464. */
  42465. ShadowLight.prototype.getRotation = function () {
  42466. this.direction.normalize();
  42467. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  42468. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  42469. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  42470. };
  42471. /**
  42472. * Boolean : false by default.
  42473. */
  42474. ShadowLight.prototype.needCube = function () {
  42475. return false;
  42476. };
  42477. /**
  42478. * Specifies wether or not the projection matrix should be recomputed this frame.
  42479. */
  42480. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  42481. return this._needProjectionMatrixCompute;
  42482. };
  42483. /**
  42484. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  42485. */
  42486. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  42487. this._needProjectionMatrixCompute = true;
  42488. };
  42489. /**
  42490. * Get the world matrix of the sahdow lights.
  42491. */
  42492. ShadowLight.prototype._getWorldMatrix = function () {
  42493. if (!this._worldMatrix) {
  42494. this._worldMatrix = BABYLON.Matrix.Identity();
  42495. }
  42496. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  42497. return this._worldMatrix;
  42498. };
  42499. /**
  42500. * Gets the minZ used for shadow according to both the scene and the light.
  42501. * @param activeCamera
  42502. */
  42503. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  42504. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  42505. };
  42506. /**
  42507. * Gets the maxZ used for shadow according to both the scene and the light.
  42508. * @param activeCamera
  42509. */
  42510. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  42511. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  42512. };
  42513. /**
  42514. * Sets the projection matrix according to the type of light and custom projection matrix definition.
  42515. * Returns the light.
  42516. */
  42517. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  42518. if (this.customProjectionMatrixBuilder) {
  42519. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  42520. }
  42521. else {
  42522. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  42523. }
  42524. return this;
  42525. };
  42526. __decorate([
  42527. BABYLON.serializeAsVector3()
  42528. ], ShadowLight.prototype, "position", void 0);
  42529. __decorate([
  42530. BABYLON.serializeAsVector3()
  42531. ], ShadowLight.prototype, "direction", null);
  42532. __decorate([
  42533. BABYLON.serialize()
  42534. ], ShadowLight.prototype, "shadowMinZ", null);
  42535. __decorate([
  42536. BABYLON.serialize()
  42537. ], ShadowLight.prototype, "shadowMaxZ", null);
  42538. return ShadowLight;
  42539. }(BABYLON.Light));
  42540. BABYLON.ShadowLight = ShadowLight;
  42541. })(BABYLON || (BABYLON = {}));
  42542. //# sourceMappingURL=babylon.shadowLight.js.map
  42543. var BABYLON;
  42544. (function (BABYLON) {
  42545. var PointLight = /** @class */ (function (_super) {
  42546. __extends(PointLight, _super);
  42547. /**
  42548. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  42549. * A PointLight emits the light in every direction.
  42550. * It can cast shadows.
  42551. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  42552. * ```javascript
  42553. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  42554. * ```
  42555. * Documentation : http://doc.babylonjs.com/tutorials/lights
  42556. */
  42557. function PointLight(name, position, scene) {
  42558. var _this = _super.call(this, name, scene) || this;
  42559. _this._shadowAngle = Math.PI / 2;
  42560. _this.position = position;
  42561. return _this;
  42562. }
  42563. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  42564. /**
  42565. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  42566. * This specifies what angle the shadow will use to be created.
  42567. *
  42568. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  42569. */
  42570. get: function () {
  42571. return this._shadowAngle;
  42572. },
  42573. /**
  42574. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  42575. * This specifies what angle the shadow will use to be created.
  42576. *
  42577. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  42578. */
  42579. set: function (value) {
  42580. this._shadowAngle = value;
  42581. this.forceProjectionMatrixCompute();
  42582. },
  42583. enumerable: true,
  42584. configurable: true
  42585. });
  42586. Object.defineProperty(PointLight.prototype, "direction", {
  42587. get: function () {
  42588. return this._direction;
  42589. },
  42590. /**
  42591. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  42592. */
  42593. set: function (value) {
  42594. var previousNeedCube = this.needCube();
  42595. this._direction = value;
  42596. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  42597. this._shadowGenerator.recreateShadowMap();
  42598. }
  42599. },
  42600. enumerable: true,
  42601. configurable: true
  42602. });
  42603. /**
  42604. * Returns the string "PointLight"
  42605. */
  42606. PointLight.prototype.getClassName = function () {
  42607. return "PointLight";
  42608. };
  42609. /**
  42610. * Returns the integer 0.
  42611. */
  42612. PointLight.prototype.getTypeID = function () {
  42613. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  42614. };
  42615. /**
  42616. * Specifies wether or not the shadowmap should be a cube texture.
  42617. */
  42618. PointLight.prototype.needCube = function () {
  42619. return !this.direction;
  42620. };
  42621. /**
  42622. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  42623. */
  42624. PointLight.prototype.getShadowDirection = function (faceIndex) {
  42625. if (this.direction) {
  42626. return _super.prototype.getShadowDirection.call(this, faceIndex);
  42627. }
  42628. else {
  42629. switch (faceIndex) {
  42630. case 0:
  42631. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  42632. case 1:
  42633. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  42634. case 2:
  42635. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  42636. case 3:
  42637. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  42638. case 4:
  42639. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  42640. case 5:
  42641. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  42642. }
  42643. }
  42644. return BABYLON.Vector3.Zero();
  42645. };
  42646. /**
  42647. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  42648. * - fov = PI / 2
  42649. * - aspect ratio : 1.0
  42650. * - z-near and far equal to the active camera minZ and maxZ.
  42651. * Returns the PointLight.
  42652. */
  42653. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  42654. var activeCamera = this.getScene().activeCamera;
  42655. if (!activeCamera) {
  42656. return;
  42657. }
  42658. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  42659. };
  42660. PointLight.prototype._buildUniformLayout = function () {
  42661. this._uniformBuffer.addUniform("vLightData", 4);
  42662. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  42663. this._uniformBuffer.addUniform("vLightSpecular", 3);
  42664. this._uniformBuffer.addUniform("shadowsInfo", 3);
  42665. this._uniformBuffer.addUniform("depthValues", 2);
  42666. this._uniformBuffer.create();
  42667. };
  42668. /**
  42669. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  42670. * Returns the PointLight.
  42671. */
  42672. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  42673. if (this.computeTransformedInformation()) {
  42674. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  42675. return this;
  42676. }
  42677. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  42678. return this;
  42679. };
  42680. __decorate([
  42681. BABYLON.serialize()
  42682. ], PointLight.prototype, "shadowAngle", null);
  42683. return PointLight;
  42684. }(BABYLON.ShadowLight));
  42685. BABYLON.PointLight = PointLight;
  42686. })(BABYLON || (BABYLON = {}));
  42687. //# sourceMappingURL=babylon.pointLight.js.map
  42688. var BABYLON;
  42689. (function (BABYLON) {
  42690. var DirectionalLight = /** @class */ (function (_super) {
  42691. __extends(DirectionalLight, _super);
  42692. /**
  42693. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  42694. * The directional light is emitted from everywhere in the given direction.
  42695. * It can cast shawdows.
  42696. * Documentation : http://doc.babylonjs.com/tutorials/lights
  42697. */
  42698. function DirectionalLight(name, direction, scene) {
  42699. var _this = _super.call(this, name, scene) || this;
  42700. _this._shadowFrustumSize = 0;
  42701. _this._shadowOrthoScale = 0.5;
  42702. _this.autoUpdateExtends = true;
  42703. // Cache
  42704. _this._orthoLeft = Number.MAX_VALUE;
  42705. _this._orthoRight = Number.MIN_VALUE;
  42706. _this._orthoTop = Number.MIN_VALUE;
  42707. _this._orthoBottom = Number.MAX_VALUE;
  42708. _this.position = direction.scale(-1.0);
  42709. _this.direction = direction;
  42710. return _this;
  42711. }
  42712. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  42713. /**
  42714. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  42715. */
  42716. get: function () {
  42717. return this._shadowFrustumSize;
  42718. },
  42719. /**
  42720. * Specifies a fix frustum size for the shadow generation.
  42721. */
  42722. set: function (value) {
  42723. this._shadowFrustumSize = value;
  42724. this.forceProjectionMatrixCompute();
  42725. },
  42726. enumerable: true,
  42727. configurable: true
  42728. });
  42729. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  42730. get: function () {
  42731. return this._shadowOrthoScale;
  42732. },
  42733. set: function (value) {
  42734. this._shadowOrthoScale = value;
  42735. this.forceProjectionMatrixCompute();
  42736. },
  42737. enumerable: true,
  42738. configurable: true
  42739. });
  42740. /**
  42741. * Returns the string "DirectionalLight".
  42742. */
  42743. DirectionalLight.prototype.getClassName = function () {
  42744. return "DirectionalLight";
  42745. };
  42746. /**
  42747. * Returns the integer 1.
  42748. */
  42749. DirectionalLight.prototype.getTypeID = function () {
  42750. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  42751. };
  42752. /**
  42753. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  42754. * Returns the DirectionalLight Shadow projection matrix.
  42755. */
  42756. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  42757. if (this.shadowFrustumSize > 0) {
  42758. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  42759. }
  42760. else {
  42761. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  42762. }
  42763. };
  42764. /**
  42765. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  42766. * Returns the DirectionalLight Shadow projection matrix.
  42767. */
  42768. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  42769. var activeCamera = this.getScene().activeCamera;
  42770. if (!activeCamera) {
  42771. return;
  42772. }
  42773. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  42774. };
  42775. /**
  42776. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  42777. * Returns the DirectionalLight Shadow projection matrix.
  42778. */
  42779. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  42780. var activeCamera = this.getScene().activeCamera;
  42781. if (!activeCamera) {
  42782. return;
  42783. }
  42784. // Check extends
  42785. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  42786. var tempVector3 = BABYLON.Vector3.Zero();
  42787. this._orthoLeft = Number.MAX_VALUE;
  42788. this._orthoRight = Number.MIN_VALUE;
  42789. this._orthoTop = Number.MIN_VALUE;
  42790. this._orthoBottom = Number.MAX_VALUE;
  42791. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  42792. var mesh = renderList[meshIndex];
  42793. if (!mesh) {
  42794. continue;
  42795. }
  42796. var boundingInfo = mesh.getBoundingInfo();
  42797. var boundingBox = boundingInfo.boundingBox;
  42798. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  42799. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  42800. if (tempVector3.x < this._orthoLeft)
  42801. this._orthoLeft = tempVector3.x;
  42802. if (tempVector3.y < this._orthoBottom)
  42803. this._orthoBottom = tempVector3.y;
  42804. if (tempVector3.x > this._orthoRight)
  42805. this._orthoRight = tempVector3.x;
  42806. if (tempVector3.y > this._orthoTop)
  42807. this._orthoTop = tempVector3.y;
  42808. }
  42809. }
  42810. }
  42811. var xOffset = this._orthoRight - this._orthoLeft;
  42812. var yOffset = this._orthoTop - this._orthoBottom;
  42813. 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);
  42814. };
  42815. DirectionalLight.prototype._buildUniformLayout = function () {
  42816. this._uniformBuffer.addUniform("vLightData", 4);
  42817. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  42818. this._uniformBuffer.addUniform("vLightSpecular", 3);
  42819. this._uniformBuffer.addUniform("shadowsInfo", 3);
  42820. this._uniformBuffer.addUniform("depthValues", 2);
  42821. this._uniformBuffer.create();
  42822. };
  42823. /**
  42824. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  42825. * Returns the DirectionalLight.
  42826. */
  42827. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  42828. if (this.computeTransformedInformation()) {
  42829. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  42830. return this;
  42831. }
  42832. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  42833. return this;
  42834. };
  42835. /**
  42836. * Gets the minZ used for shadow according to both the scene and the light.
  42837. *
  42838. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  42839. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  42840. * @param activeCamera
  42841. */
  42842. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  42843. return 1;
  42844. };
  42845. /**
  42846. * Gets the maxZ used for shadow according to both the scene and the light.
  42847. *
  42848. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  42849. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  42850. * @param activeCamera
  42851. */
  42852. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  42853. return 1;
  42854. };
  42855. __decorate([
  42856. BABYLON.serialize()
  42857. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  42858. __decorate([
  42859. BABYLON.serialize()
  42860. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  42861. __decorate([
  42862. BABYLON.serialize()
  42863. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  42864. return DirectionalLight;
  42865. }(BABYLON.ShadowLight));
  42866. BABYLON.DirectionalLight = DirectionalLight;
  42867. })(BABYLON || (BABYLON = {}));
  42868. //# sourceMappingURL=babylon.directionalLight.js.map
  42869. var BABYLON;
  42870. (function (BABYLON) {
  42871. var SpotLight = /** @class */ (function (_super) {
  42872. __extends(SpotLight, _super);
  42873. /**
  42874. * Creates a SpotLight object in the scene with the passed parameters :
  42875. * - `position` (Vector3) is the initial SpotLight position,
  42876. * - `direction` (Vector3) is the initial SpotLight direction,
  42877. * - `angle` (float, in radians) is the spot light cone angle,
  42878. * - `exponent` (float) is the light decay speed with the distance from the emission spot.
  42879. * A spot light is a simply light oriented cone.
  42880. * It can cast shadows.
  42881. * Documentation : http://doc.babylonjs.com/tutorials/lights
  42882. */
  42883. function SpotLight(name, position, direction, angle, exponent, scene) {
  42884. var _this = _super.call(this, name, scene) || this;
  42885. _this.position = position;
  42886. _this.direction = direction;
  42887. _this.angle = angle;
  42888. _this.exponent = exponent;
  42889. return _this;
  42890. }
  42891. Object.defineProperty(SpotLight.prototype, "angle", {
  42892. get: function () {
  42893. return this._angle;
  42894. },
  42895. set: function (value) {
  42896. this._angle = value;
  42897. this.forceProjectionMatrixCompute();
  42898. },
  42899. enumerable: true,
  42900. configurable: true
  42901. });
  42902. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  42903. get: function () {
  42904. return this._shadowAngleScale;
  42905. },
  42906. /**
  42907. * Allows scaling the angle of the light for shadow generation only.
  42908. */
  42909. set: function (value) {
  42910. this._shadowAngleScale = value;
  42911. this.forceProjectionMatrixCompute();
  42912. },
  42913. enumerable: true,
  42914. configurable: true
  42915. });
  42916. /**
  42917. * Returns the string "SpotLight".
  42918. */
  42919. SpotLight.prototype.getClassName = function () {
  42920. return "SpotLight";
  42921. };
  42922. /**
  42923. * Returns the integer 2.
  42924. */
  42925. SpotLight.prototype.getTypeID = function () {
  42926. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  42927. };
  42928. /**
  42929. * 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.
  42930. * Returns the SpotLight.
  42931. */
  42932. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  42933. var activeCamera = this.getScene().activeCamera;
  42934. if (!activeCamera) {
  42935. return;
  42936. }
  42937. this._shadowAngleScale = this._shadowAngleScale || 1;
  42938. var angle = this._shadowAngleScale * this._angle;
  42939. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  42940. };
  42941. SpotLight.prototype._buildUniformLayout = function () {
  42942. this._uniformBuffer.addUniform("vLightData", 4);
  42943. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  42944. this._uniformBuffer.addUniform("vLightSpecular", 3);
  42945. this._uniformBuffer.addUniform("vLightDirection", 3);
  42946. this._uniformBuffer.addUniform("shadowsInfo", 3);
  42947. this._uniformBuffer.addUniform("depthValues", 2);
  42948. this._uniformBuffer.create();
  42949. };
  42950. /**
  42951. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  42952. * Return the SpotLight.
  42953. */
  42954. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  42955. var normalizeDirection;
  42956. if (this.computeTransformedInformation()) {
  42957. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  42958. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  42959. }
  42960. else {
  42961. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  42962. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  42963. }
  42964. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5), lightIndex);
  42965. return this;
  42966. };
  42967. __decorate([
  42968. BABYLON.serialize()
  42969. ], SpotLight.prototype, "angle", null);
  42970. __decorate([
  42971. BABYLON.serialize()
  42972. /**
  42973. * Allows scaling the angle of the light for shadow generation only.
  42974. */
  42975. ], SpotLight.prototype, "shadowAngleScale", null);
  42976. __decorate([
  42977. BABYLON.serialize()
  42978. ], SpotLight.prototype, "exponent", void 0);
  42979. return SpotLight;
  42980. }(BABYLON.ShadowLight));
  42981. BABYLON.SpotLight = SpotLight;
  42982. })(BABYLON || (BABYLON = {}));
  42983. //# sourceMappingURL=babylon.spotLight.js.map
  42984. var BABYLON;
  42985. (function (BABYLON) {
  42986. var AnimationRange = /** @class */ (function () {
  42987. function AnimationRange(name, from, to) {
  42988. this.name = name;
  42989. this.from = from;
  42990. this.to = to;
  42991. }
  42992. AnimationRange.prototype.clone = function () {
  42993. return new AnimationRange(this.name, this.from, this.to);
  42994. };
  42995. return AnimationRange;
  42996. }());
  42997. BABYLON.AnimationRange = AnimationRange;
  42998. /**
  42999. * Composed of a frame, and an action function
  43000. */
  43001. var AnimationEvent = /** @class */ (function () {
  43002. function AnimationEvent(frame, action, onlyOnce) {
  43003. this.frame = frame;
  43004. this.action = action;
  43005. this.onlyOnce = onlyOnce;
  43006. this.isDone = false;
  43007. }
  43008. return AnimationEvent;
  43009. }());
  43010. BABYLON.AnimationEvent = AnimationEvent;
  43011. var PathCursor = /** @class */ (function () {
  43012. function PathCursor(path) {
  43013. this.path = path;
  43014. this._onchange = new Array();
  43015. this.value = 0;
  43016. this.animations = new Array();
  43017. }
  43018. PathCursor.prototype.getPoint = function () {
  43019. var point = this.path.getPointAtLengthPosition(this.value);
  43020. return new BABYLON.Vector3(point.x, 0, point.y);
  43021. };
  43022. PathCursor.prototype.moveAhead = function (step) {
  43023. if (step === void 0) { step = 0.002; }
  43024. this.move(step);
  43025. return this;
  43026. };
  43027. PathCursor.prototype.moveBack = function (step) {
  43028. if (step === void 0) { step = 0.002; }
  43029. this.move(-step);
  43030. return this;
  43031. };
  43032. PathCursor.prototype.move = function (step) {
  43033. if (Math.abs(step) > 1) {
  43034. throw "step size should be less than 1.";
  43035. }
  43036. this.value += step;
  43037. this.ensureLimits();
  43038. this.raiseOnChange();
  43039. return this;
  43040. };
  43041. PathCursor.prototype.ensureLimits = function () {
  43042. while (this.value > 1) {
  43043. this.value -= 1;
  43044. }
  43045. while (this.value < 0) {
  43046. this.value += 1;
  43047. }
  43048. return this;
  43049. };
  43050. // used by animation engine
  43051. PathCursor.prototype.raiseOnChange = function () {
  43052. var _this = this;
  43053. this._onchange.forEach(function (f) { return f(_this); });
  43054. return this;
  43055. };
  43056. PathCursor.prototype.onchange = function (f) {
  43057. this._onchange.push(f);
  43058. return this;
  43059. };
  43060. return PathCursor;
  43061. }());
  43062. BABYLON.PathCursor = PathCursor;
  43063. var AnimationKeyInterpolation;
  43064. (function (AnimationKeyInterpolation) {
  43065. /**
  43066. * Do not interpolate between keys and use the start key value only. Tangents are ignored.
  43067. */
  43068. AnimationKeyInterpolation[AnimationKeyInterpolation["STEP"] = 1] = "STEP";
  43069. })(AnimationKeyInterpolation = BABYLON.AnimationKeyInterpolation || (BABYLON.AnimationKeyInterpolation = {}));
  43070. var Animation = /** @class */ (function () {
  43071. function Animation(name, targetProperty, framePerSecond, dataType, loopMode, enableBlending) {
  43072. this.name = name;
  43073. this.targetProperty = targetProperty;
  43074. this.framePerSecond = framePerSecond;
  43075. this.dataType = dataType;
  43076. this.loopMode = loopMode;
  43077. this.enableBlending = enableBlending;
  43078. this._runtimeAnimations = new Array();
  43079. // The set of event that will be linked to this animation
  43080. this._events = new Array();
  43081. this.blendingSpeed = 0.01;
  43082. this._ranges = {};
  43083. this.targetPropertyPath = targetProperty.split(".");
  43084. this.dataType = dataType;
  43085. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  43086. }
  43087. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  43088. var dataType = undefined;
  43089. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  43090. dataType = Animation.ANIMATIONTYPE_FLOAT;
  43091. }
  43092. else if (from instanceof BABYLON.Quaternion) {
  43093. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  43094. }
  43095. else if (from instanceof BABYLON.Vector3) {
  43096. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  43097. }
  43098. else if (from instanceof BABYLON.Vector2) {
  43099. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  43100. }
  43101. else if (from instanceof BABYLON.Color3) {
  43102. dataType = Animation.ANIMATIONTYPE_COLOR3;
  43103. }
  43104. else if (from instanceof BABYLON.Size) {
  43105. dataType = Animation.ANIMATIONTYPE_SIZE;
  43106. }
  43107. if (dataType == undefined) {
  43108. return null;
  43109. }
  43110. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  43111. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  43112. animation.setKeys(keys);
  43113. if (easingFunction !== undefined) {
  43114. animation.setEasingFunction(easingFunction);
  43115. }
  43116. return animation;
  43117. };
  43118. /**
  43119. * Sets up an animation.
  43120. * @param property the property to animate
  43121. * @param animationType the animation type to apply
  43122. * @param easingFunction the easing function used in the animation
  43123. * @returns The created animation
  43124. */
  43125. Animation.CreateAnimation = function (property, animationType, framePerSecond, easingFunction) {
  43126. var animation = new Animation(property + "Animation", property, framePerSecond, animationType, Animation.ANIMATIONLOOPMODE_CONSTANT);
  43127. animation.setEasingFunction(easingFunction);
  43128. return animation;
  43129. };
  43130. /**
  43131. * Create and start an animation on a node
  43132. * @param {string} name defines the name of the global animation that will be run on all nodes
  43133. * @param {BABYLON.Node} node defines the root node where the animation will take place
  43134. * @param {string} targetProperty defines property to animate
  43135. * @param {number} framePerSecond defines the number of frame per second yo use
  43136. * @param {number} totalFrame defines the number of frames in total
  43137. * @param {any} from defines the initial value
  43138. * @param {any} to defines the final value
  43139. * @param {number} loopMode defines which loop mode you want to use (off by default)
  43140. * @param {BABYLON.EasingFunction} easingFunction defines the easing function to use (linear by default)
  43141. * @param onAnimationEnd defines the callback to call when animation end
  43142. * @returns the animatable created for this animation
  43143. */
  43144. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  43145. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  43146. if (!animation) {
  43147. return null;
  43148. }
  43149. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  43150. };
  43151. /**
  43152. * Create and start an animation on a node and its descendants
  43153. * @param {string} name defines the name of the global animation that will be run on all nodes
  43154. * @param {BABYLON.Node} node defines the root node where the animation will take place
  43155. * @param {boolean} directDescendantsOnly if true only direct descendants will be used, if false direct and also indirect (children of children, an so on in a recursive manner) descendants will be used.
  43156. * @param {string} targetProperty defines property to animate
  43157. * @param {number} framePerSecond defines the number of frame per second yo use
  43158. * @param {number} totalFrame defines the number of frames in total
  43159. * @param {any} from defines the initial value
  43160. * @param {any} to defines the final value
  43161. * @param {number} loopMode defines which loop mode you want to use (off by default)
  43162. * @param {BABYLON.EasingFunction} easingFunction defines the easing function to use (linear by default)
  43163. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  43164. * @returns the list of animatables created for all nodes
  43165. * @example https://www.babylonjs-playground.com/#MH0VLI
  43166. */
  43167. Animation.CreateAndStartHierarchyAnimation = function (name, node, directDescendantsOnly, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  43168. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  43169. if (!animation) {
  43170. return null;
  43171. }
  43172. var scene = node.getScene();
  43173. return scene.beginDirectHierarchyAnimation(node, directDescendantsOnly, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  43174. };
  43175. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  43176. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  43177. if (!animation) {
  43178. return null;
  43179. }
  43180. node.animations.push(animation);
  43181. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  43182. };
  43183. /**
  43184. * Transition property of the Camera to the target Value.
  43185. * @param property The property to transition
  43186. * @param targetValue The target Value of the property
  43187. * @param host The object where the property to animate belongs
  43188. * @param scene Scene used to run the animation
  43189. * @param frameRate Framerate (in frame/s) to use
  43190. * @param transition The transition type we want to use
  43191. * @param duration The duration of the animation, in milliseconds
  43192. * @param onAnimationEnd Call back trigger at the end of the animation.
  43193. */
  43194. Animation.TransitionTo = function (property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd) {
  43195. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  43196. if (duration <= 0) {
  43197. host[property] = targetValue;
  43198. if (onAnimationEnd) {
  43199. onAnimationEnd();
  43200. }
  43201. return null;
  43202. }
  43203. var endFrame = frameRate * (duration / 1000);
  43204. transition.setKeys([{
  43205. frame: 0,
  43206. value: host[property].clone ? host[property].clone() : host[property]
  43207. },
  43208. {
  43209. frame: endFrame,
  43210. value: targetValue
  43211. }]);
  43212. if (!host.animations) {
  43213. host.animations = [];
  43214. }
  43215. host.animations.push(transition);
  43216. var animation = scene.beginAnimation(host, 0, endFrame, false);
  43217. animation.onAnimationEnd = onAnimationEnd;
  43218. return animation;
  43219. };
  43220. Object.defineProperty(Animation.prototype, "runtimeAnimations", {
  43221. /**
  43222. * Return the array of runtime animations currently using this animation
  43223. */
  43224. get: function () {
  43225. return this._runtimeAnimations;
  43226. },
  43227. enumerable: true,
  43228. configurable: true
  43229. });
  43230. Object.defineProperty(Animation.prototype, "hasRunningRuntimeAnimations", {
  43231. get: function () {
  43232. for (var _i = 0, _a = this._runtimeAnimations; _i < _a.length; _i++) {
  43233. var runtimeAnimation = _a[_i];
  43234. if (!runtimeAnimation.isStopped) {
  43235. return true;
  43236. }
  43237. }
  43238. return false;
  43239. },
  43240. enumerable: true,
  43241. configurable: true
  43242. });
  43243. // Methods
  43244. /**
  43245. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  43246. */
  43247. Animation.prototype.toString = function (fullDetails) {
  43248. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  43249. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  43250. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  43251. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  43252. if (fullDetails) {
  43253. ret += ", Ranges: {";
  43254. var first = true;
  43255. for (var name in this._ranges) {
  43256. if (first) {
  43257. ret += ", ";
  43258. first = false;
  43259. }
  43260. ret += name;
  43261. }
  43262. ret += "}";
  43263. }
  43264. return ret;
  43265. };
  43266. /**
  43267. * Add an event to this animation.
  43268. */
  43269. Animation.prototype.addEvent = function (event) {
  43270. this._events.push(event);
  43271. };
  43272. /**
  43273. * Remove all events found at the given frame
  43274. * @param frame
  43275. */
  43276. Animation.prototype.removeEvents = function (frame) {
  43277. for (var index = 0; index < this._events.length; index++) {
  43278. if (this._events[index].frame === frame) {
  43279. this._events.splice(index, 1);
  43280. index--;
  43281. }
  43282. }
  43283. };
  43284. Animation.prototype.getEvents = function () {
  43285. return this._events;
  43286. };
  43287. Animation.prototype.createRange = function (name, from, to) {
  43288. // check name not already in use; could happen for bones after serialized
  43289. if (!this._ranges[name]) {
  43290. this._ranges[name] = new AnimationRange(name, from, to);
  43291. }
  43292. };
  43293. Animation.prototype.deleteRange = function (name, deleteFrames) {
  43294. if (deleteFrames === void 0) { deleteFrames = true; }
  43295. var range = this._ranges[name];
  43296. if (!range) {
  43297. return;
  43298. }
  43299. if (deleteFrames) {
  43300. var from = range.from;
  43301. var to = range.to;
  43302. // this loop MUST go high to low for multiple splices to work
  43303. for (var key = this._keys.length - 1; key >= 0; key--) {
  43304. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  43305. this._keys.splice(key, 1);
  43306. }
  43307. }
  43308. }
  43309. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  43310. };
  43311. Animation.prototype.getRange = function (name) {
  43312. return this._ranges[name];
  43313. };
  43314. Animation.prototype.getKeys = function () {
  43315. return this._keys;
  43316. };
  43317. Animation.prototype.getHighestFrame = function () {
  43318. var ret = 0;
  43319. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  43320. if (ret < this._keys[key].frame) {
  43321. ret = this._keys[key].frame;
  43322. }
  43323. }
  43324. return ret;
  43325. };
  43326. Animation.prototype.getEasingFunction = function () {
  43327. return this._easingFunction;
  43328. };
  43329. Animation.prototype.setEasingFunction = function (easingFunction) {
  43330. this._easingFunction = easingFunction;
  43331. };
  43332. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  43333. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  43334. };
  43335. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  43336. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  43337. };
  43338. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  43339. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  43340. };
  43341. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  43342. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  43343. };
  43344. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  43345. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  43346. };
  43347. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  43348. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  43349. };
  43350. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  43351. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  43352. };
  43353. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  43354. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  43355. };
  43356. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  43357. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  43358. };
  43359. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  43360. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  43361. };
  43362. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  43363. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  43364. };
  43365. Animation.prototype.clone = function () {
  43366. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  43367. clone.enableBlending = this.enableBlending;
  43368. clone.blendingSpeed = this.blendingSpeed;
  43369. if (this._keys) {
  43370. clone.setKeys(this._keys);
  43371. }
  43372. if (this._ranges) {
  43373. clone._ranges = {};
  43374. for (var name in this._ranges) {
  43375. var range = this._ranges[name];
  43376. if (!range) {
  43377. continue;
  43378. }
  43379. clone._ranges[name] = range.clone();
  43380. }
  43381. }
  43382. return clone;
  43383. };
  43384. Animation.prototype.setKeys = function (values) {
  43385. this._keys = values.slice(0);
  43386. };
  43387. Animation.prototype.serialize = function () {
  43388. var serializationObject = {};
  43389. serializationObject.name = this.name;
  43390. serializationObject.property = this.targetProperty;
  43391. serializationObject.framePerSecond = this.framePerSecond;
  43392. serializationObject.dataType = this.dataType;
  43393. serializationObject.loopBehavior = this.loopMode;
  43394. serializationObject.enableBlending = this.enableBlending;
  43395. serializationObject.blendingSpeed = this.blendingSpeed;
  43396. var dataType = this.dataType;
  43397. serializationObject.keys = [];
  43398. var keys = this.getKeys();
  43399. for (var index = 0; index < keys.length; index++) {
  43400. var animationKey = keys[index];
  43401. var key = {};
  43402. key.frame = animationKey.frame;
  43403. switch (dataType) {
  43404. case Animation.ANIMATIONTYPE_FLOAT:
  43405. key.values = [animationKey.value];
  43406. break;
  43407. case Animation.ANIMATIONTYPE_QUATERNION:
  43408. case Animation.ANIMATIONTYPE_MATRIX:
  43409. case Animation.ANIMATIONTYPE_VECTOR3:
  43410. case Animation.ANIMATIONTYPE_COLOR3:
  43411. key.values = animationKey.value.asArray();
  43412. break;
  43413. }
  43414. serializationObject.keys.push(key);
  43415. }
  43416. serializationObject.ranges = [];
  43417. for (var name in this._ranges) {
  43418. var source = this._ranges[name];
  43419. if (!source) {
  43420. continue;
  43421. }
  43422. var range = {};
  43423. range.name = name;
  43424. range.from = source.from;
  43425. range.to = source.to;
  43426. serializationObject.ranges.push(range);
  43427. }
  43428. return serializationObject;
  43429. };
  43430. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  43431. get: function () {
  43432. return Animation._ANIMATIONTYPE_FLOAT;
  43433. },
  43434. enumerable: true,
  43435. configurable: true
  43436. });
  43437. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  43438. get: function () {
  43439. return Animation._ANIMATIONTYPE_VECTOR3;
  43440. },
  43441. enumerable: true,
  43442. configurable: true
  43443. });
  43444. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  43445. get: function () {
  43446. return Animation._ANIMATIONTYPE_VECTOR2;
  43447. },
  43448. enumerable: true,
  43449. configurable: true
  43450. });
  43451. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  43452. get: function () {
  43453. return Animation._ANIMATIONTYPE_SIZE;
  43454. },
  43455. enumerable: true,
  43456. configurable: true
  43457. });
  43458. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  43459. get: function () {
  43460. return Animation._ANIMATIONTYPE_QUATERNION;
  43461. },
  43462. enumerable: true,
  43463. configurable: true
  43464. });
  43465. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  43466. get: function () {
  43467. return Animation._ANIMATIONTYPE_MATRIX;
  43468. },
  43469. enumerable: true,
  43470. configurable: true
  43471. });
  43472. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  43473. get: function () {
  43474. return Animation._ANIMATIONTYPE_COLOR3;
  43475. },
  43476. enumerable: true,
  43477. configurable: true
  43478. });
  43479. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  43480. get: function () {
  43481. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  43482. },
  43483. enumerable: true,
  43484. configurable: true
  43485. });
  43486. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  43487. get: function () {
  43488. return Animation._ANIMATIONLOOPMODE_CYCLE;
  43489. },
  43490. enumerable: true,
  43491. configurable: true
  43492. });
  43493. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  43494. get: function () {
  43495. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  43496. },
  43497. enumerable: true,
  43498. configurable: true
  43499. });
  43500. Animation.Parse = function (parsedAnimation) {
  43501. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  43502. var dataType = parsedAnimation.dataType;
  43503. var keys = [];
  43504. var data;
  43505. var index;
  43506. if (parsedAnimation.enableBlending) {
  43507. animation.enableBlending = parsedAnimation.enableBlending;
  43508. }
  43509. if (parsedAnimation.blendingSpeed) {
  43510. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  43511. }
  43512. for (index = 0; index < parsedAnimation.keys.length; index++) {
  43513. var key = parsedAnimation.keys[index];
  43514. var inTangent;
  43515. var outTangent;
  43516. switch (dataType) {
  43517. case Animation.ANIMATIONTYPE_FLOAT:
  43518. data = key.values[0];
  43519. if (key.values.length >= 1) {
  43520. inTangent = key.values[1];
  43521. }
  43522. if (key.values.length >= 2) {
  43523. outTangent = key.values[2];
  43524. }
  43525. break;
  43526. case Animation.ANIMATIONTYPE_QUATERNION:
  43527. data = BABYLON.Quaternion.FromArray(key.values);
  43528. if (key.values.length >= 8) {
  43529. var _inTangent = BABYLON.Quaternion.FromArray(key.values.slice(4, 8));
  43530. if (!_inTangent.equals(BABYLON.Quaternion.Zero())) {
  43531. inTangent = _inTangent;
  43532. }
  43533. }
  43534. if (key.values.length >= 12) {
  43535. var _outTangent = BABYLON.Quaternion.FromArray(key.values.slice(8, 12));
  43536. if (!_outTangent.equals(BABYLON.Quaternion.Zero())) {
  43537. outTangent = _outTangent;
  43538. }
  43539. }
  43540. break;
  43541. case Animation.ANIMATIONTYPE_MATRIX:
  43542. data = BABYLON.Matrix.FromArray(key.values);
  43543. break;
  43544. case Animation.ANIMATIONTYPE_COLOR3:
  43545. data = BABYLON.Color3.FromArray(key.values);
  43546. break;
  43547. case Animation.ANIMATIONTYPE_VECTOR3:
  43548. default:
  43549. data = BABYLON.Vector3.FromArray(key.values);
  43550. break;
  43551. }
  43552. var keyData = {};
  43553. keyData.frame = key.frame;
  43554. keyData.value = data;
  43555. if (inTangent != undefined) {
  43556. keyData.inTangent = inTangent;
  43557. }
  43558. if (outTangent != undefined) {
  43559. keyData.outTangent = outTangent;
  43560. }
  43561. keys.push(keyData);
  43562. }
  43563. animation.setKeys(keys);
  43564. if (parsedAnimation.ranges) {
  43565. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  43566. data = parsedAnimation.ranges[index];
  43567. animation.createRange(data.name, data.from, data.to);
  43568. }
  43569. }
  43570. return animation;
  43571. };
  43572. Animation.AppendSerializedAnimations = function (source, destination) {
  43573. if (source.animations) {
  43574. destination.animations = [];
  43575. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  43576. var animation = source.animations[animationIndex];
  43577. destination.animations.push(animation.serialize());
  43578. }
  43579. }
  43580. };
  43581. Animation.AllowMatricesInterpolation = false;
  43582. // Statics
  43583. Animation._ANIMATIONTYPE_FLOAT = 0;
  43584. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  43585. Animation._ANIMATIONTYPE_QUATERNION = 2;
  43586. Animation._ANIMATIONTYPE_MATRIX = 3;
  43587. Animation._ANIMATIONTYPE_COLOR3 = 4;
  43588. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  43589. Animation._ANIMATIONTYPE_SIZE = 6;
  43590. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  43591. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  43592. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  43593. return Animation;
  43594. }());
  43595. BABYLON.Animation = Animation;
  43596. })(BABYLON || (BABYLON = {}));
  43597. //# sourceMappingURL=babylon.animation.js.map
  43598. var BABYLON;
  43599. (function (BABYLON) {
  43600. /**
  43601. * This class defines the direct association between an animation and a target
  43602. */
  43603. var TargetedAnimation = /** @class */ (function () {
  43604. function TargetedAnimation() {
  43605. }
  43606. return TargetedAnimation;
  43607. }());
  43608. BABYLON.TargetedAnimation = TargetedAnimation;
  43609. /**
  43610. * Use this class to create coordinated animations on multiple targets
  43611. */
  43612. var AnimationGroup = /** @class */ (function () {
  43613. function AnimationGroup(name, scene) {
  43614. if (scene === void 0) { scene = null; }
  43615. this.name = name;
  43616. this._targetedAnimations = new Array();
  43617. this._animatables = new Array();
  43618. this._from = Number.MAX_VALUE;
  43619. this._to = -Number.MAX_VALUE;
  43620. this._speedRatio = 1;
  43621. this.onAnimationEndObservable = new BABYLON.Observable();
  43622. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  43623. this._scene.animationGroups.push(this);
  43624. }
  43625. Object.defineProperty(AnimationGroup.prototype, "isStarted", {
  43626. /**
  43627. * Define if the animations are started
  43628. */
  43629. get: function () {
  43630. return this._isStarted;
  43631. },
  43632. enumerable: true,
  43633. configurable: true
  43634. });
  43635. Object.defineProperty(AnimationGroup.prototype, "speedRatio", {
  43636. /**
  43637. * Gets or sets the speed ratio to use for all animations
  43638. */
  43639. get: function () {
  43640. return this._speedRatio;
  43641. },
  43642. /**
  43643. * Gets or sets the speed ratio to use for all animations
  43644. */
  43645. set: function (value) {
  43646. if (this._speedRatio === value) {
  43647. return;
  43648. }
  43649. this._speedRatio = value;
  43650. for (var index = 0; index < this._animatables.length; index++) {
  43651. var animatable = this._animatables[index];
  43652. animatable.speedRatio = this._speedRatio;
  43653. }
  43654. },
  43655. enumerable: true,
  43656. configurable: true
  43657. });
  43658. Object.defineProperty(AnimationGroup.prototype, "targetedAnimations", {
  43659. /**
  43660. * Gets the targeted animations for this animation group
  43661. */
  43662. get: function () {
  43663. return this._targetedAnimations;
  43664. },
  43665. enumerable: true,
  43666. configurable: true
  43667. });
  43668. /**
  43669. * Add an animation (with its target) in the group
  43670. * @param animation defines the animation we want to add
  43671. * @param target defines the target of the animation
  43672. * @returns the {BABYLON.TargetedAnimation} object
  43673. */
  43674. AnimationGroup.prototype.addTargetedAnimation = function (animation, target) {
  43675. var targetedAnimation = {
  43676. animation: animation,
  43677. target: target
  43678. };
  43679. var keys = animation.getKeys();
  43680. if (this._from > keys[0].frame) {
  43681. this._from = keys[0].frame;
  43682. }
  43683. if (this._to < keys[keys.length - 1].frame) {
  43684. this._to = keys[keys.length - 1].frame;
  43685. }
  43686. this._targetedAnimations.push(targetedAnimation);
  43687. return targetedAnimation;
  43688. };
  43689. /**
  43690. * This function will normalize every animation in the group to make sure they all go from beginFrame to endFrame
  43691. * It can add constant keys at begin or end
  43692. * @param beginFrame defines the new begin frame for all animations. It can't be bigger than the smallest begin frame of all animations
  43693. * @param endFrame defines the new end frame for all animations. It can't be smaller than the largest end frame of all animations
  43694. */
  43695. AnimationGroup.prototype.normalize = function (beginFrame, endFrame) {
  43696. if (beginFrame === void 0) { beginFrame = -Number.MAX_VALUE; }
  43697. if (endFrame === void 0) { endFrame = Number.MAX_VALUE; }
  43698. beginFrame = Math.max(beginFrame, this._from);
  43699. endFrame = Math.min(endFrame, this._to);
  43700. for (var index = 0; index < this._targetedAnimations.length; index++) {
  43701. var targetedAnimation = this._targetedAnimations[index];
  43702. var keys = targetedAnimation.animation.getKeys();
  43703. var startKey = keys[0];
  43704. var endKey = keys[keys.length - 1];
  43705. if (startKey.frame > beginFrame) {
  43706. var newKey = {
  43707. frame: beginFrame,
  43708. value: startKey.value,
  43709. inTangent: startKey.inTangent,
  43710. outTangent: startKey.outTangent,
  43711. interpolation: startKey.interpolation
  43712. };
  43713. keys.splice(0, 0, newKey);
  43714. }
  43715. if (endKey.frame < endFrame) {
  43716. var newKey = {
  43717. frame: endFrame,
  43718. value: endKey.value,
  43719. inTangent: endKey.outTangent,
  43720. outTangent: endKey.outTangent,
  43721. interpolation: endKey.interpolation
  43722. };
  43723. keys.push(newKey);
  43724. }
  43725. }
  43726. return this;
  43727. };
  43728. /**
  43729. * Start all animations on given targets
  43730. * @param loop defines if animations must loop
  43731. * @param speedRatio defines the ratio to apply to animation speed (1 by default)
  43732. */
  43733. AnimationGroup.prototype.start = function (loop, speedRatio) {
  43734. var _this = this;
  43735. if (loop === void 0) { loop = false; }
  43736. if (speedRatio === void 0) { speedRatio = 1; }
  43737. if (this._isStarted || this._targetedAnimations.length === 0) {
  43738. return this;
  43739. }
  43740. var _loop_1 = function () {
  43741. var targetedAnimation = this_1._targetedAnimations[index];
  43742. this_1._animatables.push(this_1._scene.beginDirectAnimation(targetedAnimation.target, [targetedAnimation.animation], this_1._from, this_1._to, loop, speedRatio, function () {
  43743. _this.onAnimationEndObservable.notifyObservers(targetedAnimation);
  43744. }));
  43745. };
  43746. var this_1 = this;
  43747. for (var index = 0; index < this._targetedAnimations.length; index++) {
  43748. _loop_1();
  43749. }
  43750. this._speedRatio = speedRatio;
  43751. this._isStarted = true;
  43752. return this;
  43753. };
  43754. /**
  43755. * Pause all animations
  43756. */
  43757. AnimationGroup.prototype.pause = function () {
  43758. if (!this._isStarted) {
  43759. return this;
  43760. }
  43761. for (var index = 0; index < this._animatables.length; index++) {
  43762. var animatable = this._animatables[index];
  43763. animatable.pause();
  43764. }
  43765. return this;
  43766. };
  43767. /**
  43768. * Play all animations to initial state
  43769. * This function will start() the animations if they were not started or will restart() them if they were paused
  43770. * @param loop defines if animations must loop
  43771. */
  43772. AnimationGroup.prototype.play = function (loop) {
  43773. if (this.isStarted) {
  43774. if (loop !== undefined) {
  43775. for (var index = 0; index < this._animatables.length; index++) {
  43776. var animatable = this._animatables[index];
  43777. animatable.loopAnimation = loop;
  43778. }
  43779. }
  43780. this.restart();
  43781. }
  43782. else {
  43783. this.start(loop, this._speedRatio);
  43784. }
  43785. return this;
  43786. };
  43787. /**
  43788. * Reset all animations to initial state
  43789. */
  43790. AnimationGroup.prototype.reset = function () {
  43791. if (!this._isStarted) {
  43792. return this;
  43793. }
  43794. for (var index = 0; index < this._animatables.length; index++) {
  43795. var animatable = this._animatables[index];
  43796. animatable.reset();
  43797. }
  43798. return this;
  43799. };
  43800. /**
  43801. * Restart animations from key 0
  43802. */
  43803. AnimationGroup.prototype.restart = function () {
  43804. if (!this._isStarted) {
  43805. return this;
  43806. }
  43807. for (var index = 0; index < this._animatables.length; index++) {
  43808. var animatable = this._animatables[index];
  43809. animatable.restart();
  43810. }
  43811. return this;
  43812. };
  43813. /**
  43814. * Stop all animations
  43815. */
  43816. AnimationGroup.prototype.stop = function () {
  43817. if (!this._isStarted) {
  43818. return this;
  43819. }
  43820. for (var index = 0; index < this._animatables.length; index++) {
  43821. var animatable = this._animatables[index];
  43822. animatable.stop();
  43823. }
  43824. this._isStarted = false;
  43825. return this;
  43826. };
  43827. /**
  43828. * Dispose all associated resources
  43829. */
  43830. AnimationGroup.prototype.dispose = function () {
  43831. this._targetedAnimations = [];
  43832. this._animatables = [];
  43833. var index = this._scene.animationGroups.indexOf(this);
  43834. if (index > -1) {
  43835. this._scene.animationGroups.splice(index, 1);
  43836. }
  43837. };
  43838. return AnimationGroup;
  43839. }());
  43840. BABYLON.AnimationGroup = AnimationGroup;
  43841. })(BABYLON || (BABYLON = {}));
  43842. //# sourceMappingURL=babylon.animationGroup.js.map
  43843. var BABYLON;
  43844. (function (BABYLON) {
  43845. var RuntimeAnimation = /** @class */ (function () {
  43846. function RuntimeAnimation(target, animation) {
  43847. this._offsetsCache = {};
  43848. this._highLimitsCache = {};
  43849. this._stopped = false;
  43850. this._blendingFactor = 0;
  43851. this._ratioOffset = 0;
  43852. this._animation = animation;
  43853. this._target = target;
  43854. animation._runtimeAnimations.push(this);
  43855. }
  43856. Object.defineProperty(RuntimeAnimation.prototype, "animation", {
  43857. get: function () {
  43858. return this._animation;
  43859. },
  43860. enumerable: true,
  43861. configurable: true
  43862. });
  43863. RuntimeAnimation.prototype.reset = function () {
  43864. this._offsetsCache = {};
  43865. this._highLimitsCache = {};
  43866. this.currentFrame = 0;
  43867. this._blendingFactor = 0;
  43868. this._originalBlendValue = null;
  43869. };
  43870. RuntimeAnimation.prototype.isStopped = function () {
  43871. return this._stopped;
  43872. };
  43873. RuntimeAnimation.prototype.dispose = function () {
  43874. var index = this._animation.runtimeAnimations.indexOf(this);
  43875. if (index > -1) {
  43876. this._animation.runtimeAnimations.splice(index, 1);
  43877. }
  43878. };
  43879. RuntimeAnimation.prototype._getKeyValue = function (value) {
  43880. if (typeof value === "function") {
  43881. return value();
  43882. }
  43883. return value;
  43884. };
  43885. RuntimeAnimation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  43886. if (loopMode === BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  43887. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  43888. }
  43889. this.currentFrame = currentFrame;
  43890. var keys = this._animation.getKeys();
  43891. // Try to get a hash to find the right key
  43892. 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));
  43893. if (keys[startKeyIndex].frame >= currentFrame) {
  43894. while (startKeyIndex - 1 >= 0 && keys[startKeyIndex].frame >= currentFrame) {
  43895. startKeyIndex--;
  43896. }
  43897. }
  43898. for (var key = startKeyIndex; key < keys.length; key++) {
  43899. var endKey = keys[key + 1];
  43900. if (endKey.frame >= currentFrame) {
  43901. var startKey = keys[key];
  43902. var startValue = this._getKeyValue(startKey.value);
  43903. if (startKey.interpolation === BABYLON.AnimationKeyInterpolation.STEP) {
  43904. return startValue;
  43905. }
  43906. var endValue = this._getKeyValue(endKey.value);
  43907. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  43908. var frameDelta = endKey.frame - startKey.frame;
  43909. // gradient : percent of currentFrame between the frame inf and the frame sup
  43910. var gradient = (currentFrame - startKey.frame) / frameDelta;
  43911. // check for easingFunction and correction of gradient
  43912. var easingFunction = this._animation.getEasingFunction();
  43913. if (easingFunction != null) {
  43914. gradient = easingFunction.ease(gradient);
  43915. }
  43916. switch (this._animation.dataType) {
  43917. // Float
  43918. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  43919. var floatValue = useTangent ? this._animation.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this._animation.floatInterpolateFunction(startValue, endValue, gradient);
  43920. switch (loopMode) {
  43921. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  43922. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  43923. return floatValue;
  43924. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  43925. return offsetValue * repeatCount + floatValue;
  43926. }
  43927. break;
  43928. // Quaternion
  43929. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  43930. var quatValue = useTangent ? this._animation.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.quaternionInterpolateFunction(startValue, endValue, gradient);
  43931. switch (loopMode) {
  43932. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  43933. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  43934. return quatValue;
  43935. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  43936. return quatValue.add(offsetValue.scale(repeatCount));
  43937. }
  43938. return quatValue;
  43939. // Vector3
  43940. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  43941. var vec3Value = useTangent ? this._animation.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.vector3InterpolateFunction(startValue, endValue, gradient);
  43942. switch (loopMode) {
  43943. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  43944. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  43945. return vec3Value;
  43946. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  43947. return vec3Value.add(offsetValue.scale(repeatCount));
  43948. }
  43949. // Vector2
  43950. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  43951. var vec2Value = useTangent ? this._animation.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.vector2InterpolateFunction(startValue, endValue, gradient);
  43952. switch (loopMode) {
  43953. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  43954. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  43955. return vec2Value;
  43956. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  43957. return vec2Value.add(offsetValue.scale(repeatCount));
  43958. }
  43959. // Size
  43960. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  43961. switch (loopMode) {
  43962. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  43963. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  43964. return this._animation.sizeInterpolateFunction(startValue, endValue, gradient);
  43965. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  43966. return this._animation.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  43967. }
  43968. // Color3
  43969. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  43970. switch (loopMode) {
  43971. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  43972. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  43973. return this._animation.color3InterpolateFunction(startValue, endValue, gradient);
  43974. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  43975. return this._animation.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  43976. }
  43977. // Matrix
  43978. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  43979. switch (loopMode) {
  43980. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  43981. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  43982. if (BABYLON.Animation.AllowMatricesInterpolation) {
  43983. return this._animation.matrixInterpolateFunction(startValue, endValue, gradient);
  43984. }
  43985. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  43986. return startValue;
  43987. }
  43988. default:
  43989. break;
  43990. }
  43991. break;
  43992. }
  43993. }
  43994. return this._getKeyValue(keys[keys.length - 1].value);
  43995. };
  43996. RuntimeAnimation.prototype.setValue = function (currentValue, blend) {
  43997. if (blend === void 0) { blend = false; }
  43998. // Set value
  43999. var path;
  44000. var destination;
  44001. var targetPropertyPath = this._animation.targetPropertyPath;
  44002. if (targetPropertyPath.length > 1) {
  44003. var property = this._target[targetPropertyPath[0]];
  44004. for (var index = 1; index < targetPropertyPath.length - 1; index++) {
  44005. property = property[targetPropertyPath[index]];
  44006. }
  44007. path = targetPropertyPath[targetPropertyPath.length - 1];
  44008. destination = property;
  44009. }
  44010. else {
  44011. path = targetPropertyPath[0];
  44012. destination = this._target;
  44013. }
  44014. // Blending
  44015. if (this._animation.enableBlending && this._blendingFactor <= 1.0) {
  44016. if (!this._originalBlendValue) {
  44017. if (destination[path].clone) {
  44018. this._originalBlendValue = destination[path].clone();
  44019. }
  44020. else {
  44021. this._originalBlendValue = destination[path];
  44022. }
  44023. }
  44024. if (this._originalBlendValue.prototype) {
  44025. if (this._originalBlendValue.prototype.Lerp) {
  44026. destination[path] = this._originalBlendValue.construtor.prototype.Lerp(currentValue, this._originalBlendValue, this._blendingFactor);
  44027. }
  44028. else {
  44029. destination[path] = currentValue;
  44030. }
  44031. }
  44032. else if (this._originalBlendValue.m) {
  44033. destination[path] = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  44034. }
  44035. else {
  44036. destination[path] = this._originalBlendValue * (1.0 - this._blendingFactor) + this._blendingFactor * currentValue;
  44037. }
  44038. this._blendingFactor += this._animation.blendingSpeed;
  44039. }
  44040. else {
  44041. destination[path] = currentValue;
  44042. }
  44043. if (this._target.markAsDirty) {
  44044. this._target.markAsDirty(this._animation.targetProperty);
  44045. }
  44046. };
  44047. RuntimeAnimation.prototype.goToFrame = function (frame) {
  44048. var keys = this._animation.getKeys();
  44049. if (frame < keys[0].frame) {
  44050. frame = keys[0].frame;
  44051. }
  44052. else if (frame > keys[keys.length - 1].frame) {
  44053. frame = keys[keys.length - 1].frame;
  44054. }
  44055. var currentValue = this._interpolate(frame, 0, this._animation.loopMode);
  44056. this.setValue(currentValue);
  44057. };
  44058. RuntimeAnimation.prototype._prepareForSpeedRatioChange = function (newSpeedRatio) {
  44059. var newRatio = this._previousDelay * (this._animation.framePerSecond * newSpeedRatio) / 1000.0;
  44060. this._ratioOffset = this._previousRatio - newRatio;
  44061. };
  44062. RuntimeAnimation.prototype.animate = function (delay, from, to, loop, speedRatio, blend) {
  44063. if (blend === void 0) { blend = false; }
  44064. var targetPropertyPath = this._animation.targetPropertyPath;
  44065. if (!targetPropertyPath || targetPropertyPath.length < 1) {
  44066. this._stopped = true;
  44067. return false;
  44068. }
  44069. var returnValue = true;
  44070. var keys = this._animation.getKeys();
  44071. // Adding a start key at frame 0 if missing
  44072. if (keys[0].frame !== 0) {
  44073. var newKey = { frame: 0, value: keys[0].value };
  44074. keys.splice(0, 0, newKey);
  44075. }
  44076. // Check limits
  44077. if (from < keys[0].frame || from > keys[keys.length - 1].frame) {
  44078. from = keys[0].frame;
  44079. }
  44080. if (to < keys[0].frame || to > keys[keys.length - 1].frame) {
  44081. to = keys[keys.length - 1].frame;
  44082. }
  44083. //to and from cannot be the same key
  44084. if (from === to) {
  44085. if (from > keys[0].frame) {
  44086. from--;
  44087. }
  44088. else if (to < keys[keys.length - 1].frame) {
  44089. to++;
  44090. }
  44091. }
  44092. // Compute ratio
  44093. var range = to - from;
  44094. var offsetValue;
  44095. // ratio represents the frame delta between from and to
  44096. var ratio = (delay * (this._animation.framePerSecond * speedRatio) / 1000.0) + this._ratioOffset;
  44097. var highLimitValue = 0;
  44098. this._previousDelay = delay;
  44099. this._previousRatio = ratio;
  44100. if (((to > from && ratio > range) || (from > to && ratio < range)) && !loop) {
  44101. returnValue = false;
  44102. highLimitValue = this._getKeyValue(keys[keys.length - 1].value);
  44103. }
  44104. else {
  44105. // Get max value if required
  44106. if (this._animation.loopMode !== BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE) {
  44107. var keyOffset = to.toString() + from.toString();
  44108. if (!this._offsetsCache[keyOffset]) {
  44109. var fromValue = this._interpolate(from, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  44110. var toValue = this._interpolate(to, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  44111. switch (this._animation.dataType) {
  44112. // Float
  44113. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  44114. this._offsetsCache[keyOffset] = toValue - fromValue;
  44115. break;
  44116. // Quaternion
  44117. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  44118. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  44119. break;
  44120. // Vector3
  44121. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  44122. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  44123. // Vector2
  44124. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  44125. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  44126. // Size
  44127. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  44128. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  44129. // Color3
  44130. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  44131. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  44132. default:
  44133. break;
  44134. }
  44135. this._highLimitsCache[keyOffset] = toValue;
  44136. }
  44137. highLimitValue = this._highLimitsCache[keyOffset];
  44138. offsetValue = this._offsetsCache[keyOffset];
  44139. }
  44140. }
  44141. if (offsetValue === undefined) {
  44142. switch (this._animation.dataType) {
  44143. // Float
  44144. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  44145. offsetValue = 0;
  44146. break;
  44147. // Quaternion
  44148. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  44149. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  44150. break;
  44151. // Vector3
  44152. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  44153. offsetValue = BABYLON.Vector3.Zero();
  44154. break;
  44155. // Vector2
  44156. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  44157. offsetValue = BABYLON.Vector2.Zero();
  44158. break;
  44159. // Size
  44160. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  44161. offsetValue = BABYLON.Size.Zero();
  44162. break;
  44163. // Color3
  44164. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  44165. offsetValue = BABYLON.Color3.Black();
  44166. }
  44167. }
  44168. // Compute value
  44169. var repeatCount = (ratio / range) >> 0;
  44170. var currentFrame = returnValue ? from + ratio % range : to;
  44171. var currentValue = this._interpolate(currentFrame, repeatCount, this._animation.loopMode, offsetValue, highLimitValue);
  44172. // Set value
  44173. this.setValue(currentValue);
  44174. // Check events
  44175. var events = this._animation.getEvents();
  44176. for (var index = 0; index < events.length; index++) {
  44177. // Make sure current frame has passed event frame and that event frame is within the current range
  44178. // Also, handle both forward and reverse animations
  44179. if ((range > 0 && currentFrame >= events[index].frame && events[index].frame >= from) ||
  44180. (range < 0 && currentFrame <= events[index].frame && events[index].frame <= from)) {
  44181. var event = events[index];
  44182. if (!event.isDone) {
  44183. // If event should be done only once, remove it.
  44184. if (event.onlyOnce) {
  44185. events.splice(index, 1);
  44186. index--;
  44187. }
  44188. event.isDone = true;
  44189. event.action();
  44190. } // Don't do anything if the event has already be done.
  44191. }
  44192. else if (events[index].isDone && !events[index].onlyOnce) {
  44193. // reset event, the animation is looping
  44194. events[index].isDone = false;
  44195. }
  44196. }
  44197. if (!returnValue) {
  44198. this._stopped = true;
  44199. }
  44200. return returnValue;
  44201. };
  44202. return RuntimeAnimation;
  44203. }());
  44204. BABYLON.RuntimeAnimation = RuntimeAnimation;
  44205. })(BABYLON || (BABYLON = {}));
  44206. //# sourceMappingURL=babylon.runtimeAnimation.js.map
  44207. var BABYLON;
  44208. (function (BABYLON) {
  44209. var Animatable = /** @class */ (function () {
  44210. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  44211. if (fromFrame === void 0) { fromFrame = 0; }
  44212. if (toFrame === void 0) { toFrame = 100; }
  44213. if (loopAnimation === void 0) { loopAnimation = false; }
  44214. if (speedRatio === void 0) { speedRatio = 1.0; }
  44215. this.target = target;
  44216. this.fromFrame = fromFrame;
  44217. this.toFrame = toFrame;
  44218. this.loopAnimation = loopAnimation;
  44219. this.onAnimationEnd = onAnimationEnd;
  44220. this._localDelayOffset = null;
  44221. this._pausedDelay = null;
  44222. this._runtimeAnimations = new Array();
  44223. this._paused = false;
  44224. this._speedRatio = 1;
  44225. this.animationStarted = false;
  44226. if (animations) {
  44227. this.appendAnimations(target, animations);
  44228. }
  44229. this._speedRatio = speedRatio;
  44230. this._scene = scene;
  44231. scene._activeAnimatables.push(this);
  44232. }
  44233. Object.defineProperty(Animatable.prototype, "speedRatio", {
  44234. get: function () {
  44235. return this._speedRatio;
  44236. },
  44237. set: function (value) {
  44238. for (var index = 0; index < this._runtimeAnimations.length; index++) {
  44239. var animation = this._runtimeAnimations[index];
  44240. animation._prepareForSpeedRatioChange(value);
  44241. }
  44242. this._speedRatio = value;
  44243. },
  44244. enumerable: true,
  44245. configurable: true
  44246. });
  44247. // Methods
  44248. Animatable.prototype.getAnimations = function () {
  44249. return this._runtimeAnimations;
  44250. };
  44251. Animatable.prototype.appendAnimations = function (target, animations) {
  44252. for (var index = 0; index < animations.length; index++) {
  44253. var animation = animations[index];
  44254. this._runtimeAnimations.push(new BABYLON.RuntimeAnimation(target, animation));
  44255. }
  44256. };
  44257. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  44258. var runtimeAnimations = this._runtimeAnimations;
  44259. for (var index = 0; index < runtimeAnimations.length; index++) {
  44260. if (runtimeAnimations[index].animation.targetProperty === property) {
  44261. return runtimeAnimations[index].animation;
  44262. }
  44263. }
  44264. return null;
  44265. };
  44266. Animatable.prototype.getRuntimeAnimationByTargetProperty = function (property) {
  44267. var runtimeAnimations = this._runtimeAnimations;
  44268. for (var index = 0; index < runtimeAnimations.length; index++) {
  44269. if (runtimeAnimations[index].animation.targetProperty === property) {
  44270. return runtimeAnimations[index];
  44271. }
  44272. }
  44273. return null;
  44274. };
  44275. Animatable.prototype.reset = function () {
  44276. var runtimeAnimations = this._runtimeAnimations;
  44277. for (var index = 0; index < runtimeAnimations.length; index++) {
  44278. runtimeAnimations[index].reset();
  44279. }
  44280. // Reset to original value
  44281. for (index = 0; index < runtimeAnimations.length; index++) {
  44282. var animation = runtimeAnimations[index];
  44283. animation.animate(0, this.fromFrame, this.toFrame, false, this._speedRatio);
  44284. }
  44285. this._localDelayOffset = null;
  44286. this._pausedDelay = null;
  44287. };
  44288. Animatable.prototype.enableBlending = function (blendingSpeed) {
  44289. var runtimeAnimations = this._runtimeAnimations;
  44290. for (var index = 0; index < runtimeAnimations.length; index++) {
  44291. runtimeAnimations[index].animation.enableBlending = true;
  44292. runtimeAnimations[index].animation.blendingSpeed = blendingSpeed;
  44293. }
  44294. };
  44295. Animatable.prototype.disableBlending = function () {
  44296. var runtimeAnimations = this._runtimeAnimations;
  44297. for (var index = 0; index < runtimeAnimations.length; index++) {
  44298. runtimeAnimations[index].animation.enableBlending = false;
  44299. }
  44300. };
  44301. Animatable.prototype.goToFrame = function (frame) {
  44302. var runtimeAnimations = this._runtimeAnimations;
  44303. if (runtimeAnimations[0]) {
  44304. var fps = runtimeAnimations[0].animation.framePerSecond;
  44305. var currentFrame = runtimeAnimations[0].currentFrame;
  44306. var adjustTime = frame - currentFrame;
  44307. var delay = adjustTime * 1000 / fps;
  44308. if (this._localDelayOffset === null) {
  44309. this._localDelayOffset = 0;
  44310. }
  44311. this._localDelayOffset -= delay;
  44312. }
  44313. for (var index = 0; index < runtimeAnimations.length; index++) {
  44314. runtimeAnimations[index].goToFrame(frame);
  44315. }
  44316. };
  44317. Animatable.prototype.pause = function () {
  44318. if (this._paused) {
  44319. return;
  44320. }
  44321. this._paused = true;
  44322. };
  44323. Animatable.prototype.restart = function () {
  44324. this._paused = false;
  44325. };
  44326. Animatable.prototype.stop = function (animationName) {
  44327. if (animationName) {
  44328. var idx = this._scene._activeAnimatables.indexOf(this);
  44329. if (idx > -1) {
  44330. var runtimeAnimations = this._runtimeAnimations;
  44331. for (var index = runtimeAnimations.length - 1; index >= 0; index--) {
  44332. if (typeof animationName === "string" && runtimeAnimations[index].animation.name != animationName) {
  44333. continue;
  44334. }
  44335. runtimeAnimations[index].dispose();
  44336. runtimeAnimations.splice(index, 1);
  44337. }
  44338. if (runtimeAnimations.length == 0) {
  44339. this._scene._activeAnimatables.splice(idx, 1);
  44340. if (this.onAnimationEnd) {
  44341. this.onAnimationEnd();
  44342. }
  44343. }
  44344. }
  44345. }
  44346. else {
  44347. var index = this._scene._activeAnimatables.indexOf(this);
  44348. if (index > -1) {
  44349. this._scene._activeAnimatables.splice(index, 1);
  44350. var runtimeAnimations = this._runtimeAnimations;
  44351. for (var index = 0; index < runtimeAnimations.length; index++) {
  44352. runtimeAnimations[index].dispose();
  44353. }
  44354. if (this.onAnimationEnd) {
  44355. this.onAnimationEnd();
  44356. }
  44357. }
  44358. }
  44359. };
  44360. Animatable.prototype._animate = function (delay) {
  44361. if (this._paused) {
  44362. this.animationStarted = false;
  44363. if (this._pausedDelay === null) {
  44364. this._pausedDelay = delay;
  44365. }
  44366. return true;
  44367. }
  44368. if (this._localDelayOffset === null) {
  44369. this._localDelayOffset = delay;
  44370. this._pausedDelay = null;
  44371. }
  44372. else if (this._pausedDelay !== null) {
  44373. this._localDelayOffset += delay - this._pausedDelay;
  44374. this._pausedDelay = null;
  44375. }
  44376. // Animating
  44377. var running = false;
  44378. var runtimeAnimations = this._runtimeAnimations;
  44379. var index;
  44380. for (index = 0; index < runtimeAnimations.length; index++) {
  44381. var animation = runtimeAnimations[index];
  44382. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this._speedRatio);
  44383. running = running || isRunning;
  44384. }
  44385. this.animationStarted = running;
  44386. if (!running) {
  44387. // Remove from active animatables
  44388. index = this._scene._activeAnimatables.indexOf(this);
  44389. this._scene._activeAnimatables.splice(index, 1);
  44390. // Dispose all runtime animations
  44391. for (index = 0; index < runtimeAnimations.length; index++) {
  44392. runtimeAnimations[index].dispose();
  44393. }
  44394. }
  44395. if (!running && this.onAnimationEnd) {
  44396. this.onAnimationEnd();
  44397. this.onAnimationEnd = null;
  44398. }
  44399. return running;
  44400. };
  44401. return Animatable;
  44402. }());
  44403. BABYLON.Animatable = Animatable;
  44404. })(BABYLON || (BABYLON = {}));
  44405. //# sourceMappingURL=babylon.animatable.js.map
  44406. var BABYLON;
  44407. (function (BABYLON) {
  44408. var EasingFunction = /** @class */ (function () {
  44409. function EasingFunction() {
  44410. // Properties
  44411. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  44412. }
  44413. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  44414. get: function () {
  44415. return EasingFunction._EASINGMODE_EASEIN;
  44416. },
  44417. enumerable: true,
  44418. configurable: true
  44419. });
  44420. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  44421. get: function () {
  44422. return EasingFunction._EASINGMODE_EASEOUT;
  44423. },
  44424. enumerable: true,
  44425. configurable: true
  44426. });
  44427. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  44428. get: function () {
  44429. return EasingFunction._EASINGMODE_EASEINOUT;
  44430. },
  44431. enumerable: true,
  44432. configurable: true
  44433. });
  44434. EasingFunction.prototype.setEasingMode = function (easingMode) {
  44435. var n = Math.min(Math.max(easingMode, 0), 2);
  44436. this._easingMode = n;
  44437. };
  44438. EasingFunction.prototype.getEasingMode = function () {
  44439. return this._easingMode;
  44440. };
  44441. EasingFunction.prototype.easeInCore = function (gradient) {
  44442. throw new Error('You must implement this method');
  44443. };
  44444. EasingFunction.prototype.ease = function (gradient) {
  44445. switch (this._easingMode) {
  44446. case EasingFunction.EASINGMODE_EASEIN:
  44447. return this.easeInCore(gradient);
  44448. case EasingFunction.EASINGMODE_EASEOUT:
  44449. return (1 - this.easeInCore(1 - gradient));
  44450. }
  44451. if (gradient >= 0.5) {
  44452. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  44453. }
  44454. return (this.easeInCore(gradient * 2) * 0.5);
  44455. };
  44456. //Statics
  44457. EasingFunction._EASINGMODE_EASEIN = 0;
  44458. EasingFunction._EASINGMODE_EASEOUT = 1;
  44459. EasingFunction._EASINGMODE_EASEINOUT = 2;
  44460. return EasingFunction;
  44461. }());
  44462. BABYLON.EasingFunction = EasingFunction;
  44463. var CircleEase = /** @class */ (function (_super) {
  44464. __extends(CircleEase, _super);
  44465. function CircleEase() {
  44466. return _super !== null && _super.apply(this, arguments) || this;
  44467. }
  44468. CircleEase.prototype.easeInCore = function (gradient) {
  44469. gradient = Math.max(0, Math.min(1, gradient));
  44470. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  44471. };
  44472. return CircleEase;
  44473. }(EasingFunction));
  44474. BABYLON.CircleEase = CircleEase;
  44475. var BackEase = /** @class */ (function (_super) {
  44476. __extends(BackEase, _super);
  44477. function BackEase(amplitude) {
  44478. if (amplitude === void 0) { amplitude = 1; }
  44479. var _this = _super.call(this) || this;
  44480. _this.amplitude = amplitude;
  44481. return _this;
  44482. }
  44483. BackEase.prototype.easeInCore = function (gradient) {
  44484. var num = Math.max(0, this.amplitude);
  44485. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  44486. };
  44487. return BackEase;
  44488. }(EasingFunction));
  44489. BABYLON.BackEase = BackEase;
  44490. var BounceEase = /** @class */ (function (_super) {
  44491. __extends(BounceEase, _super);
  44492. function BounceEase(bounces, bounciness) {
  44493. if (bounces === void 0) { bounces = 3; }
  44494. if (bounciness === void 0) { bounciness = 2; }
  44495. var _this = _super.call(this) || this;
  44496. _this.bounces = bounces;
  44497. _this.bounciness = bounciness;
  44498. return _this;
  44499. }
  44500. BounceEase.prototype.easeInCore = function (gradient) {
  44501. var y = Math.max(0.0, this.bounces);
  44502. var bounciness = this.bounciness;
  44503. if (bounciness <= 1.0) {
  44504. bounciness = 1.001;
  44505. }
  44506. var num9 = Math.pow(bounciness, y);
  44507. var num5 = 1.0 - bounciness;
  44508. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  44509. var num15 = gradient * num4;
  44510. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  44511. var num3 = Math.floor(num65);
  44512. var num13 = num3 + 1.0;
  44513. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  44514. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  44515. var num7 = (num8 + num12) * 0.5;
  44516. var num6 = gradient - num7;
  44517. var num2 = num7 - num8;
  44518. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  44519. };
  44520. return BounceEase;
  44521. }(EasingFunction));
  44522. BABYLON.BounceEase = BounceEase;
  44523. var CubicEase = /** @class */ (function (_super) {
  44524. __extends(CubicEase, _super);
  44525. function CubicEase() {
  44526. return _super !== null && _super.apply(this, arguments) || this;
  44527. }
  44528. CubicEase.prototype.easeInCore = function (gradient) {
  44529. return (gradient * gradient * gradient);
  44530. };
  44531. return CubicEase;
  44532. }(EasingFunction));
  44533. BABYLON.CubicEase = CubicEase;
  44534. var ElasticEase = /** @class */ (function (_super) {
  44535. __extends(ElasticEase, _super);
  44536. function ElasticEase(oscillations, springiness) {
  44537. if (oscillations === void 0) { oscillations = 3; }
  44538. if (springiness === void 0) { springiness = 3; }
  44539. var _this = _super.call(this) || this;
  44540. _this.oscillations = oscillations;
  44541. _this.springiness = springiness;
  44542. return _this;
  44543. }
  44544. ElasticEase.prototype.easeInCore = function (gradient) {
  44545. var num2;
  44546. var num3 = Math.max(0.0, this.oscillations);
  44547. var num = Math.max(0.0, this.springiness);
  44548. if (num == 0) {
  44549. num2 = gradient;
  44550. }
  44551. else {
  44552. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  44553. }
  44554. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  44555. };
  44556. return ElasticEase;
  44557. }(EasingFunction));
  44558. BABYLON.ElasticEase = ElasticEase;
  44559. var ExponentialEase = /** @class */ (function (_super) {
  44560. __extends(ExponentialEase, _super);
  44561. function ExponentialEase(exponent) {
  44562. if (exponent === void 0) { exponent = 2; }
  44563. var _this = _super.call(this) || this;
  44564. _this.exponent = exponent;
  44565. return _this;
  44566. }
  44567. ExponentialEase.prototype.easeInCore = function (gradient) {
  44568. if (this.exponent <= 0) {
  44569. return gradient;
  44570. }
  44571. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  44572. };
  44573. return ExponentialEase;
  44574. }(EasingFunction));
  44575. BABYLON.ExponentialEase = ExponentialEase;
  44576. var PowerEase = /** @class */ (function (_super) {
  44577. __extends(PowerEase, _super);
  44578. function PowerEase(power) {
  44579. if (power === void 0) { power = 2; }
  44580. var _this = _super.call(this) || this;
  44581. _this.power = power;
  44582. return _this;
  44583. }
  44584. PowerEase.prototype.easeInCore = function (gradient) {
  44585. var y = Math.max(0.0, this.power);
  44586. return Math.pow(gradient, y);
  44587. };
  44588. return PowerEase;
  44589. }(EasingFunction));
  44590. BABYLON.PowerEase = PowerEase;
  44591. var QuadraticEase = /** @class */ (function (_super) {
  44592. __extends(QuadraticEase, _super);
  44593. function QuadraticEase() {
  44594. return _super !== null && _super.apply(this, arguments) || this;
  44595. }
  44596. QuadraticEase.prototype.easeInCore = function (gradient) {
  44597. return (gradient * gradient);
  44598. };
  44599. return QuadraticEase;
  44600. }(EasingFunction));
  44601. BABYLON.QuadraticEase = QuadraticEase;
  44602. var QuarticEase = /** @class */ (function (_super) {
  44603. __extends(QuarticEase, _super);
  44604. function QuarticEase() {
  44605. return _super !== null && _super.apply(this, arguments) || this;
  44606. }
  44607. QuarticEase.prototype.easeInCore = function (gradient) {
  44608. return (gradient * gradient * gradient * gradient);
  44609. };
  44610. return QuarticEase;
  44611. }(EasingFunction));
  44612. BABYLON.QuarticEase = QuarticEase;
  44613. var QuinticEase = /** @class */ (function (_super) {
  44614. __extends(QuinticEase, _super);
  44615. function QuinticEase() {
  44616. return _super !== null && _super.apply(this, arguments) || this;
  44617. }
  44618. QuinticEase.prototype.easeInCore = function (gradient) {
  44619. return (gradient * gradient * gradient * gradient * gradient);
  44620. };
  44621. return QuinticEase;
  44622. }(EasingFunction));
  44623. BABYLON.QuinticEase = QuinticEase;
  44624. var SineEase = /** @class */ (function (_super) {
  44625. __extends(SineEase, _super);
  44626. function SineEase() {
  44627. return _super !== null && _super.apply(this, arguments) || this;
  44628. }
  44629. SineEase.prototype.easeInCore = function (gradient) {
  44630. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  44631. };
  44632. return SineEase;
  44633. }(EasingFunction));
  44634. BABYLON.SineEase = SineEase;
  44635. var BezierCurveEase = /** @class */ (function (_super) {
  44636. __extends(BezierCurveEase, _super);
  44637. function BezierCurveEase(x1, y1, x2, y2) {
  44638. if (x1 === void 0) { x1 = 0; }
  44639. if (y1 === void 0) { y1 = 0; }
  44640. if (x2 === void 0) { x2 = 1; }
  44641. if (y2 === void 0) { y2 = 1; }
  44642. var _this = _super.call(this) || this;
  44643. _this.x1 = x1;
  44644. _this.y1 = y1;
  44645. _this.x2 = x2;
  44646. _this.y2 = y2;
  44647. return _this;
  44648. }
  44649. BezierCurveEase.prototype.easeInCore = function (gradient) {
  44650. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  44651. };
  44652. return BezierCurveEase;
  44653. }(EasingFunction));
  44654. BABYLON.BezierCurveEase = BezierCurveEase;
  44655. })(BABYLON || (BABYLON = {}));
  44656. //# sourceMappingURL=babylon.easing.js.map
  44657. var BABYLON;
  44658. (function (BABYLON) {
  44659. var Condition = /** @class */ (function () {
  44660. function Condition(actionManager) {
  44661. this._actionManager = actionManager;
  44662. }
  44663. Condition.prototype.isValid = function () {
  44664. return true;
  44665. };
  44666. Condition.prototype._getProperty = function (propertyPath) {
  44667. return this._actionManager._getProperty(propertyPath);
  44668. };
  44669. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  44670. return this._actionManager._getEffectiveTarget(target, propertyPath);
  44671. };
  44672. Condition.prototype.serialize = function () {
  44673. };
  44674. Condition.prototype._serialize = function (serializedCondition) {
  44675. return {
  44676. type: 2,
  44677. children: [],
  44678. name: serializedCondition.name,
  44679. properties: serializedCondition.properties
  44680. };
  44681. };
  44682. return Condition;
  44683. }());
  44684. BABYLON.Condition = Condition;
  44685. var ValueCondition = /** @class */ (function (_super) {
  44686. __extends(ValueCondition, _super);
  44687. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  44688. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  44689. var _this = _super.call(this, actionManager) || this;
  44690. _this.propertyPath = propertyPath;
  44691. _this.value = value;
  44692. _this.operator = operator;
  44693. _this._target = target;
  44694. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  44695. _this._property = _this._getProperty(_this.propertyPath);
  44696. return _this;
  44697. }
  44698. Object.defineProperty(ValueCondition, "IsEqual", {
  44699. get: function () {
  44700. return ValueCondition._IsEqual;
  44701. },
  44702. enumerable: true,
  44703. configurable: true
  44704. });
  44705. Object.defineProperty(ValueCondition, "IsDifferent", {
  44706. get: function () {
  44707. return ValueCondition._IsDifferent;
  44708. },
  44709. enumerable: true,
  44710. configurable: true
  44711. });
  44712. Object.defineProperty(ValueCondition, "IsGreater", {
  44713. get: function () {
  44714. return ValueCondition._IsGreater;
  44715. },
  44716. enumerable: true,
  44717. configurable: true
  44718. });
  44719. Object.defineProperty(ValueCondition, "IsLesser", {
  44720. get: function () {
  44721. return ValueCondition._IsLesser;
  44722. },
  44723. enumerable: true,
  44724. configurable: true
  44725. });
  44726. // Methods
  44727. ValueCondition.prototype.isValid = function () {
  44728. switch (this.operator) {
  44729. case ValueCondition.IsGreater:
  44730. return this._effectiveTarget[this._property] > this.value;
  44731. case ValueCondition.IsLesser:
  44732. return this._effectiveTarget[this._property] < this.value;
  44733. case ValueCondition.IsEqual:
  44734. case ValueCondition.IsDifferent:
  44735. var check;
  44736. if (this.value.equals) {
  44737. check = this.value.equals(this._effectiveTarget[this._property]);
  44738. }
  44739. else {
  44740. check = this.value === this._effectiveTarget[this._property];
  44741. }
  44742. return this.operator === ValueCondition.IsEqual ? check : !check;
  44743. }
  44744. return false;
  44745. };
  44746. ValueCondition.prototype.serialize = function () {
  44747. return this._serialize({
  44748. name: "ValueCondition",
  44749. properties: [
  44750. BABYLON.Action._GetTargetProperty(this._target),
  44751. { name: "propertyPath", value: this.propertyPath },
  44752. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  44753. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  44754. ]
  44755. });
  44756. };
  44757. ValueCondition.GetOperatorName = function (operator) {
  44758. switch (operator) {
  44759. case ValueCondition._IsEqual: return "IsEqual";
  44760. case ValueCondition._IsDifferent: return "IsDifferent";
  44761. case ValueCondition._IsGreater: return "IsGreater";
  44762. case ValueCondition._IsLesser: return "IsLesser";
  44763. default: return "";
  44764. }
  44765. };
  44766. // Statics
  44767. ValueCondition._IsEqual = 0;
  44768. ValueCondition._IsDifferent = 1;
  44769. ValueCondition._IsGreater = 2;
  44770. ValueCondition._IsLesser = 3;
  44771. return ValueCondition;
  44772. }(Condition));
  44773. BABYLON.ValueCondition = ValueCondition;
  44774. var PredicateCondition = /** @class */ (function (_super) {
  44775. __extends(PredicateCondition, _super);
  44776. function PredicateCondition(actionManager, predicate) {
  44777. var _this = _super.call(this, actionManager) || this;
  44778. _this.predicate = predicate;
  44779. return _this;
  44780. }
  44781. PredicateCondition.prototype.isValid = function () {
  44782. return this.predicate();
  44783. };
  44784. return PredicateCondition;
  44785. }(Condition));
  44786. BABYLON.PredicateCondition = PredicateCondition;
  44787. var StateCondition = /** @class */ (function (_super) {
  44788. __extends(StateCondition, _super);
  44789. function StateCondition(actionManager, target, value) {
  44790. var _this = _super.call(this, actionManager) || this;
  44791. _this.value = value;
  44792. _this._target = target;
  44793. return _this;
  44794. }
  44795. // Methods
  44796. StateCondition.prototype.isValid = function () {
  44797. return this._target.state === this.value;
  44798. };
  44799. StateCondition.prototype.serialize = function () {
  44800. return this._serialize({
  44801. name: "StateCondition",
  44802. properties: [
  44803. BABYLON.Action._GetTargetProperty(this._target),
  44804. { name: "value", value: this.value }
  44805. ]
  44806. });
  44807. };
  44808. return StateCondition;
  44809. }(Condition));
  44810. BABYLON.StateCondition = StateCondition;
  44811. })(BABYLON || (BABYLON = {}));
  44812. //# sourceMappingURL=babylon.condition.js.map
  44813. var BABYLON;
  44814. (function (BABYLON) {
  44815. var Action = /** @class */ (function () {
  44816. function Action(triggerOptions, condition) {
  44817. this.triggerOptions = triggerOptions;
  44818. this.onBeforeExecuteObservable = new BABYLON.Observable();
  44819. if (triggerOptions.parameter) {
  44820. this.trigger = triggerOptions.trigger;
  44821. this._triggerParameter = triggerOptions.parameter;
  44822. }
  44823. else {
  44824. this.trigger = triggerOptions;
  44825. }
  44826. this._nextActiveAction = this;
  44827. this._condition = condition;
  44828. }
  44829. // Methods
  44830. Action.prototype._prepare = function () {
  44831. };
  44832. Action.prototype.getTriggerParameter = function () {
  44833. return this._triggerParameter;
  44834. };
  44835. Action.prototype._executeCurrent = function (evt) {
  44836. if (this._nextActiveAction._condition) {
  44837. var condition = this._nextActiveAction._condition;
  44838. var currentRenderId = this._actionManager.getScene().getRenderId();
  44839. // We cache the current evaluation for the current frame
  44840. if (condition._evaluationId === currentRenderId) {
  44841. if (!condition._currentResult) {
  44842. return;
  44843. }
  44844. }
  44845. else {
  44846. condition._evaluationId = currentRenderId;
  44847. if (!condition.isValid()) {
  44848. condition._currentResult = false;
  44849. return;
  44850. }
  44851. condition._currentResult = true;
  44852. }
  44853. }
  44854. this.onBeforeExecuteObservable.notifyObservers(this);
  44855. this._nextActiveAction.execute(evt);
  44856. this.skipToNextActiveAction();
  44857. };
  44858. Action.prototype.execute = function (evt) {
  44859. };
  44860. Action.prototype.skipToNextActiveAction = function () {
  44861. if (this._nextActiveAction._child) {
  44862. if (!this._nextActiveAction._child._actionManager) {
  44863. this._nextActiveAction._child._actionManager = this._actionManager;
  44864. }
  44865. this._nextActiveAction = this._nextActiveAction._child;
  44866. }
  44867. else {
  44868. this._nextActiveAction = this;
  44869. }
  44870. };
  44871. Action.prototype.then = function (action) {
  44872. this._child = action;
  44873. action._actionManager = this._actionManager;
  44874. action._prepare();
  44875. return action;
  44876. };
  44877. Action.prototype._getProperty = function (propertyPath) {
  44878. return this._actionManager._getProperty(propertyPath);
  44879. };
  44880. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  44881. return this._actionManager._getEffectiveTarget(target, propertyPath);
  44882. };
  44883. Action.prototype.serialize = function (parent) {
  44884. };
  44885. // Called by BABYLON.Action objects in serialize(...). Internal use
  44886. Action.prototype._serialize = function (serializedAction, parent) {
  44887. var serializationObject = {
  44888. type: 1,
  44889. children: [],
  44890. name: serializedAction.name,
  44891. properties: serializedAction.properties || []
  44892. };
  44893. // Serialize child
  44894. if (this._child) {
  44895. this._child.serialize(serializationObject);
  44896. }
  44897. // Check if "this" has a condition
  44898. if (this._condition) {
  44899. var serializedCondition = this._condition.serialize();
  44900. serializedCondition.children.push(serializationObject);
  44901. if (parent) {
  44902. parent.children.push(serializedCondition);
  44903. }
  44904. return serializedCondition;
  44905. }
  44906. if (parent) {
  44907. parent.children.push(serializationObject);
  44908. }
  44909. return serializationObject;
  44910. };
  44911. Action._SerializeValueAsString = function (value) {
  44912. if (typeof value === "number") {
  44913. return value.toString();
  44914. }
  44915. if (typeof value === "boolean") {
  44916. return value ? "true" : "false";
  44917. }
  44918. if (value instanceof BABYLON.Vector2) {
  44919. return value.x + ", " + value.y;
  44920. }
  44921. if (value instanceof BABYLON.Vector3) {
  44922. return value.x + ", " + value.y + ", " + value.z;
  44923. }
  44924. if (value instanceof BABYLON.Color3) {
  44925. return value.r + ", " + value.g + ", " + value.b;
  44926. }
  44927. if (value instanceof BABYLON.Color4) {
  44928. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  44929. }
  44930. return value; // string
  44931. };
  44932. Action._GetTargetProperty = function (target) {
  44933. return {
  44934. name: "target",
  44935. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  44936. : target instanceof BABYLON.Light ? "LightProperties"
  44937. : target instanceof BABYLON.Camera ? "CameraProperties"
  44938. : "SceneProperties",
  44939. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  44940. };
  44941. };
  44942. return Action;
  44943. }());
  44944. BABYLON.Action = Action;
  44945. })(BABYLON || (BABYLON = {}));
  44946. //# sourceMappingURL=babylon.action.js.map
  44947. var BABYLON;
  44948. (function (BABYLON) {
  44949. /**
  44950. * ActionEvent is the event beint sent when an action is triggered.
  44951. */
  44952. var ActionEvent = /** @class */ (function () {
  44953. /**
  44954. * @param source The mesh or sprite that triggered the action.
  44955. * @param pointerX The X mouse cursor position at the time of the event
  44956. * @param pointerY The Y mouse cursor position at the time of the event
  44957. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  44958. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  44959. */
  44960. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  44961. this.source = source;
  44962. this.pointerX = pointerX;
  44963. this.pointerY = pointerY;
  44964. this.meshUnderPointer = meshUnderPointer;
  44965. this.sourceEvent = sourceEvent;
  44966. this.additionalData = additionalData;
  44967. }
  44968. /**
  44969. * Helper function to auto-create an ActionEvent from a source mesh.
  44970. * @param source The source mesh that triggered the event
  44971. * @param evt {Event} The original (browser) event
  44972. */
  44973. ActionEvent.CreateNew = function (source, evt, additionalData) {
  44974. var scene = source.getScene();
  44975. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  44976. };
  44977. /**
  44978. * Helper function to auto-create an ActionEvent from a source mesh.
  44979. * @param source The source sprite that triggered the event
  44980. * @param scene Scene associated with the sprite
  44981. * @param evt {Event} The original (browser) event
  44982. */
  44983. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  44984. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  44985. };
  44986. /**
  44987. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  44988. * @param scene the scene where the event occurred
  44989. * @param evt {Event} The original (browser) event
  44990. */
  44991. ActionEvent.CreateNewFromScene = function (scene, evt) {
  44992. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  44993. };
  44994. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  44995. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  44996. };
  44997. return ActionEvent;
  44998. }());
  44999. BABYLON.ActionEvent = ActionEvent;
  45000. /**
  45001. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  45002. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  45003. */
  45004. var ActionManager = /** @class */ (function () {
  45005. function ActionManager(scene) {
  45006. // Members
  45007. this.actions = new Array();
  45008. this.hoverCursor = '';
  45009. this._scene = scene;
  45010. scene._actionManagers.push(this);
  45011. }
  45012. Object.defineProperty(ActionManager, "NothingTrigger", {
  45013. get: function () {
  45014. return ActionManager._NothingTrigger;
  45015. },
  45016. enumerable: true,
  45017. configurable: true
  45018. });
  45019. Object.defineProperty(ActionManager, "OnPickTrigger", {
  45020. get: function () {
  45021. return ActionManager._OnPickTrigger;
  45022. },
  45023. enumerable: true,
  45024. configurable: true
  45025. });
  45026. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  45027. get: function () {
  45028. return ActionManager._OnLeftPickTrigger;
  45029. },
  45030. enumerable: true,
  45031. configurable: true
  45032. });
  45033. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  45034. get: function () {
  45035. return ActionManager._OnRightPickTrigger;
  45036. },
  45037. enumerable: true,
  45038. configurable: true
  45039. });
  45040. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  45041. get: function () {
  45042. return ActionManager._OnCenterPickTrigger;
  45043. },
  45044. enumerable: true,
  45045. configurable: true
  45046. });
  45047. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  45048. get: function () {
  45049. return ActionManager._OnPickDownTrigger;
  45050. },
  45051. enumerable: true,
  45052. configurable: true
  45053. });
  45054. Object.defineProperty(ActionManager, "OnDoublePickTrigger", {
  45055. get: function () {
  45056. return ActionManager._OnDoublePickTrigger;
  45057. },
  45058. enumerable: true,
  45059. configurable: true
  45060. });
  45061. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  45062. get: function () {
  45063. return ActionManager._OnPickUpTrigger;
  45064. },
  45065. enumerable: true,
  45066. configurable: true
  45067. });
  45068. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  45069. /// This trigger will only be raised if you also declared a OnPickDown
  45070. get: function () {
  45071. return ActionManager._OnPickOutTrigger;
  45072. },
  45073. enumerable: true,
  45074. configurable: true
  45075. });
  45076. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  45077. get: function () {
  45078. return ActionManager._OnLongPressTrigger;
  45079. },
  45080. enumerable: true,
  45081. configurable: true
  45082. });
  45083. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  45084. get: function () {
  45085. return ActionManager._OnPointerOverTrigger;
  45086. },
  45087. enumerable: true,
  45088. configurable: true
  45089. });
  45090. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  45091. get: function () {
  45092. return ActionManager._OnPointerOutTrigger;
  45093. },
  45094. enumerable: true,
  45095. configurable: true
  45096. });
  45097. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  45098. get: function () {
  45099. return ActionManager._OnEveryFrameTrigger;
  45100. },
  45101. enumerable: true,
  45102. configurable: true
  45103. });
  45104. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  45105. get: function () {
  45106. return ActionManager._OnIntersectionEnterTrigger;
  45107. },
  45108. enumerable: true,
  45109. configurable: true
  45110. });
  45111. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  45112. get: function () {
  45113. return ActionManager._OnIntersectionExitTrigger;
  45114. },
  45115. enumerable: true,
  45116. configurable: true
  45117. });
  45118. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  45119. get: function () {
  45120. return ActionManager._OnKeyDownTrigger;
  45121. },
  45122. enumerable: true,
  45123. configurable: true
  45124. });
  45125. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  45126. get: function () {
  45127. return ActionManager._OnKeyUpTrigger;
  45128. },
  45129. enumerable: true,
  45130. configurable: true
  45131. });
  45132. // Methods
  45133. ActionManager.prototype.dispose = function () {
  45134. var index = this._scene._actionManagers.indexOf(this);
  45135. for (var i = 0; i < this.actions.length; i++) {
  45136. var action = this.actions[i];
  45137. ActionManager.Triggers[action.trigger]--;
  45138. if (ActionManager.Triggers[action.trigger] === 0) {
  45139. delete ActionManager.Triggers[action.trigger];
  45140. }
  45141. }
  45142. if (index > -1) {
  45143. this._scene._actionManagers.splice(index, 1);
  45144. }
  45145. };
  45146. ActionManager.prototype.getScene = function () {
  45147. return this._scene;
  45148. };
  45149. /**
  45150. * Does this action manager handles actions of any of the given triggers
  45151. * @param {number[]} triggers - the triggers to be tested
  45152. * @return {boolean} whether one (or more) of the triggers is handeled
  45153. */
  45154. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  45155. for (var index = 0; index < this.actions.length; index++) {
  45156. var action = this.actions[index];
  45157. if (triggers.indexOf(action.trigger) > -1) {
  45158. return true;
  45159. }
  45160. }
  45161. return false;
  45162. };
  45163. /**
  45164. * Does this action manager handles actions of a given trigger
  45165. * @param {number} trigger - the trigger to be tested
  45166. * @return {boolean} whether the trigger is handeled
  45167. */
  45168. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  45169. for (var index = 0; index < this.actions.length; index++) {
  45170. var action = this.actions[index];
  45171. if (action.trigger === trigger) {
  45172. return true;
  45173. }
  45174. }
  45175. return false;
  45176. };
  45177. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  45178. /**
  45179. * Does this action manager has pointer triggers
  45180. * @return {boolean} whether or not it has pointer triggers
  45181. */
  45182. get: function () {
  45183. for (var index = 0; index < this.actions.length; index++) {
  45184. var action = this.actions[index];
  45185. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  45186. return true;
  45187. }
  45188. }
  45189. return false;
  45190. },
  45191. enumerable: true,
  45192. configurable: true
  45193. });
  45194. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  45195. /**
  45196. * Does this action manager has pick triggers
  45197. * @return {boolean} whether or not it has pick triggers
  45198. */
  45199. get: function () {
  45200. for (var index = 0; index < this.actions.length; index++) {
  45201. var action = this.actions[index];
  45202. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  45203. return true;
  45204. }
  45205. }
  45206. return false;
  45207. },
  45208. enumerable: true,
  45209. configurable: true
  45210. });
  45211. Object.defineProperty(ActionManager, "HasTriggers", {
  45212. /**
  45213. * Does exist one action manager with at least one trigger
  45214. * @return {boolean} whether or not it exists one action manager with one trigger
  45215. **/
  45216. get: function () {
  45217. for (var t in ActionManager.Triggers) {
  45218. if (ActionManager.Triggers.hasOwnProperty(t)) {
  45219. return true;
  45220. }
  45221. }
  45222. return false;
  45223. },
  45224. enumerable: true,
  45225. configurable: true
  45226. });
  45227. Object.defineProperty(ActionManager, "HasPickTriggers", {
  45228. /**
  45229. * Does exist one action manager with at least one pick trigger
  45230. * @return {boolean} whether or not it exists one action manager with one pick trigger
  45231. **/
  45232. get: function () {
  45233. for (var t in ActionManager.Triggers) {
  45234. if (ActionManager.Triggers.hasOwnProperty(t)) {
  45235. var t_int = parseInt(t);
  45236. if (t_int >= ActionManager._OnPickTrigger && t_int <= ActionManager._OnPickUpTrigger) {
  45237. return true;
  45238. }
  45239. }
  45240. }
  45241. return false;
  45242. },
  45243. enumerable: true,
  45244. configurable: true
  45245. });
  45246. /**
  45247. * Does exist one action manager that handles actions of a given trigger
  45248. * @param {number} trigger - the trigger to be tested
  45249. * @return {boolean} whether the trigger is handeled by at least one action manager
  45250. **/
  45251. ActionManager.HasSpecificTrigger = function (trigger) {
  45252. for (var t in ActionManager.Triggers) {
  45253. if (ActionManager.Triggers.hasOwnProperty(t)) {
  45254. var t_int = parseInt(t);
  45255. if (t_int === trigger) {
  45256. return true;
  45257. }
  45258. }
  45259. }
  45260. return false;
  45261. };
  45262. /**
  45263. * Registers an action to this action manager
  45264. * @param {BABYLON.Action} action - the action to be registered
  45265. * @return {BABYLON.Action} the action amended (prepared) after registration
  45266. */
  45267. ActionManager.prototype.registerAction = function (action) {
  45268. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  45269. if (this.getScene().actionManager !== this) {
  45270. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  45271. return null;
  45272. }
  45273. }
  45274. this.actions.push(action);
  45275. if (ActionManager.Triggers[action.trigger]) {
  45276. ActionManager.Triggers[action.trigger]++;
  45277. }
  45278. else {
  45279. ActionManager.Triggers[action.trigger] = 1;
  45280. }
  45281. action._actionManager = this;
  45282. action._prepare();
  45283. return action;
  45284. };
  45285. /**
  45286. * Unregisters an action to this action manager
  45287. * @param action The action to be unregistered
  45288. * @return whether the action has been unregistered
  45289. */
  45290. ActionManager.prototype.unregisterAction = function (action) {
  45291. var index = this.actions.indexOf(action);
  45292. if (index !== -1) {
  45293. this.actions.splice(index, 1);
  45294. ActionManager.Triggers[action.trigger] -= 1;
  45295. if (ActionManager.Triggers[action.trigger] === 0) {
  45296. delete ActionManager.Triggers[action.trigger];
  45297. }
  45298. delete action._actionManager;
  45299. return true;
  45300. }
  45301. return false;
  45302. };
  45303. /**
  45304. * Process a specific trigger
  45305. * @param {number} trigger - the trigger to process
  45306. * @param evt {BABYLON.ActionEvent} the event details to be processed
  45307. */
  45308. ActionManager.prototype.processTrigger = function (trigger, evt) {
  45309. for (var index = 0; index < this.actions.length; index++) {
  45310. var action = this.actions[index];
  45311. if (action.trigger === trigger) {
  45312. if (evt) {
  45313. if (trigger === ActionManager.OnKeyUpTrigger
  45314. || trigger === ActionManager.OnKeyDownTrigger) {
  45315. var parameter = action.getTriggerParameter();
  45316. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  45317. if (!parameter.toLowerCase) {
  45318. continue;
  45319. }
  45320. var lowerCase = parameter.toLowerCase();
  45321. if (lowerCase !== evt.sourceEvent.key) {
  45322. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  45323. var actualkey = String.fromCharCode(unicode).toLowerCase();
  45324. if (actualkey !== lowerCase) {
  45325. continue;
  45326. }
  45327. }
  45328. }
  45329. }
  45330. }
  45331. action._executeCurrent(evt);
  45332. }
  45333. }
  45334. };
  45335. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  45336. var properties = propertyPath.split(".");
  45337. for (var index = 0; index < properties.length - 1; index++) {
  45338. target = target[properties[index]];
  45339. }
  45340. return target;
  45341. };
  45342. ActionManager.prototype._getProperty = function (propertyPath) {
  45343. var properties = propertyPath.split(".");
  45344. return properties[properties.length - 1];
  45345. };
  45346. ActionManager.prototype.serialize = function (name) {
  45347. var root = {
  45348. children: new Array(),
  45349. name: name,
  45350. type: 3,
  45351. properties: new Array() // Empty for root but required
  45352. };
  45353. for (var i = 0; i < this.actions.length; i++) {
  45354. var triggerObject = {
  45355. type: 0,
  45356. children: new Array(),
  45357. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  45358. properties: new Array()
  45359. };
  45360. var triggerOptions = this.actions[i].triggerOptions;
  45361. if (triggerOptions && typeof triggerOptions !== "number") {
  45362. if (triggerOptions.parameter instanceof BABYLON.Node) {
  45363. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  45364. }
  45365. else {
  45366. var parameter = {};
  45367. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  45368. if (triggerOptions.parameter.mesh) {
  45369. parameter._meshId = triggerOptions.parameter.mesh.id;
  45370. }
  45371. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  45372. }
  45373. }
  45374. // Serialize child action, recursively
  45375. this.actions[i].serialize(triggerObject);
  45376. // Add serialized trigger
  45377. root.children.push(triggerObject);
  45378. }
  45379. return root;
  45380. };
  45381. ActionManager.Parse = function (parsedActions, object, scene) {
  45382. var actionManager = new ActionManager(scene);
  45383. if (object === null)
  45384. scene.actionManager = actionManager;
  45385. else
  45386. object.actionManager = actionManager;
  45387. // instanciate a new object
  45388. var instanciate = function (name, params) {
  45389. // TODO: We will need to find a solution for the next line when using commonjs / es6 .
  45390. var newInstance = Object.create(BABYLON.Tools.Instantiate("BABYLON." + name).prototype);
  45391. newInstance.constructor.apply(newInstance, params);
  45392. return newInstance;
  45393. };
  45394. var parseParameter = function (name, value, target, propertyPath) {
  45395. if (propertyPath === null) {
  45396. // String, boolean or float
  45397. var floatValue = parseFloat(value);
  45398. if (value === "true" || value === "false")
  45399. return value === "true";
  45400. else
  45401. return isNaN(floatValue) ? value : floatValue;
  45402. }
  45403. var effectiveTarget = propertyPath.split(".");
  45404. var values = value.split(",");
  45405. // Get effective Target
  45406. for (var i = 0; i < effectiveTarget.length; i++) {
  45407. target = target[effectiveTarget[i]];
  45408. }
  45409. // Return appropriate value with its type
  45410. if (typeof (target) === "boolean")
  45411. return values[0] === "true";
  45412. if (typeof (target) === "string")
  45413. return values[0];
  45414. // Parameters with multiple values such as Vector3 etc.
  45415. var split = new Array();
  45416. for (var i = 0; i < values.length; i++)
  45417. split.push(parseFloat(values[i]));
  45418. if (target instanceof BABYLON.Vector3)
  45419. return BABYLON.Vector3.FromArray(split);
  45420. if (target instanceof BABYLON.Vector4)
  45421. return BABYLON.Vector4.FromArray(split);
  45422. if (target instanceof BABYLON.Color3)
  45423. return BABYLON.Color3.FromArray(split);
  45424. if (target instanceof BABYLON.Color4)
  45425. return BABYLON.Color4.FromArray(split);
  45426. return parseFloat(values[0]);
  45427. };
  45428. // traverse graph per trigger
  45429. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  45430. if (combineArray === void 0) { combineArray = null; }
  45431. if (parsedAction.detached)
  45432. return;
  45433. var parameters = new Array();
  45434. var target = null;
  45435. var propertyPath = null;
  45436. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  45437. // Parameters
  45438. if (parsedAction.type === 2)
  45439. parameters.push(actionManager);
  45440. else
  45441. parameters.push(trigger);
  45442. if (combine) {
  45443. var actions = new Array();
  45444. for (var j = 0; j < parsedAction.combine.length; j++) {
  45445. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  45446. }
  45447. parameters.push(actions);
  45448. }
  45449. else {
  45450. for (var i = 0; i < parsedAction.properties.length; i++) {
  45451. var value = parsedAction.properties[i].value;
  45452. var name = parsedAction.properties[i].name;
  45453. var targetType = parsedAction.properties[i].targetType;
  45454. if (name === "target")
  45455. if (targetType !== null && targetType === "SceneProperties")
  45456. value = target = scene;
  45457. else
  45458. value = target = scene.getNodeByName(value);
  45459. else if (name === "parent")
  45460. value = scene.getNodeByName(value);
  45461. else if (name === "sound")
  45462. value = scene.getSoundByName(value);
  45463. else if (name !== "propertyPath") {
  45464. if (parsedAction.type === 2 && name === "operator")
  45465. value = BABYLON.ValueCondition[value];
  45466. else
  45467. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  45468. }
  45469. else {
  45470. propertyPath = value;
  45471. }
  45472. parameters.push(value);
  45473. }
  45474. }
  45475. if (combineArray === null) {
  45476. parameters.push(condition);
  45477. }
  45478. else {
  45479. parameters.push(null);
  45480. }
  45481. // If interpolate value action
  45482. if (parsedAction.name === "InterpolateValueAction") {
  45483. var param = parameters[parameters.length - 2];
  45484. parameters[parameters.length - 1] = param;
  45485. parameters[parameters.length - 2] = condition;
  45486. }
  45487. // Action or condition(s) and not CombineAction
  45488. var newAction = instanciate(parsedAction.name, parameters);
  45489. if (newAction instanceof BABYLON.Condition && condition !== null) {
  45490. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  45491. if (action)
  45492. action.then(nothing);
  45493. else
  45494. actionManager.registerAction(nothing);
  45495. action = nothing;
  45496. }
  45497. if (combineArray === null) {
  45498. if (newAction instanceof BABYLON.Condition) {
  45499. condition = newAction;
  45500. newAction = action;
  45501. }
  45502. else {
  45503. condition = null;
  45504. if (action)
  45505. action.then(newAction);
  45506. else
  45507. actionManager.registerAction(newAction);
  45508. }
  45509. }
  45510. else {
  45511. combineArray.push(newAction);
  45512. }
  45513. for (var i = 0; i < parsedAction.children.length; i++)
  45514. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  45515. };
  45516. // triggers
  45517. for (var i = 0; i < parsedActions.children.length; i++) {
  45518. var triggerParams;
  45519. var trigger = parsedActions.children[i];
  45520. if (trigger.properties.length > 0) {
  45521. var param = trigger.properties[0].value;
  45522. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  45523. if (value._meshId) {
  45524. value.mesh = scene.getMeshByID(value._meshId);
  45525. }
  45526. triggerParams = { trigger: ActionManager[trigger.name], parameter: value };
  45527. }
  45528. else
  45529. triggerParams = ActionManager[trigger.name];
  45530. for (var j = 0; j < trigger.children.length; j++) {
  45531. if (!trigger.detached)
  45532. traverse(trigger.children[j], triggerParams, null, null);
  45533. }
  45534. }
  45535. };
  45536. ActionManager.GetTriggerName = function (trigger) {
  45537. switch (trigger) {
  45538. case 0: return "NothingTrigger";
  45539. case 1: return "OnPickTrigger";
  45540. case 2: return "OnLeftPickTrigger";
  45541. case 3: return "OnRightPickTrigger";
  45542. case 4: return "OnCenterPickTrigger";
  45543. case 5: return "OnPickDownTrigger";
  45544. case 6: return "OnPickUpTrigger";
  45545. case 7: return "OnLongPressTrigger";
  45546. case 8: return "OnPointerOverTrigger";
  45547. case 9: return "OnPointerOutTrigger";
  45548. case 10: return "OnEveryFrameTrigger";
  45549. case 11: return "OnIntersectionEnterTrigger";
  45550. case 12: return "OnIntersectionExitTrigger";
  45551. case 13: return "OnKeyDownTrigger";
  45552. case 14: return "OnKeyUpTrigger";
  45553. case 15: return "OnPickOutTrigger";
  45554. default: return "";
  45555. }
  45556. };
  45557. // Statics
  45558. ActionManager._NothingTrigger = 0;
  45559. ActionManager._OnPickTrigger = 1;
  45560. ActionManager._OnLeftPickTrigger = 2;
  45561. ActionManager._OnRightPickTrigger = 3;
  45562. ActionManager._OnCenterPickTrigger = 4;
  45563. ActionManager._OnPickDownTrigger = 5;
  45564. ActionManager._OnDoublePickTrigger = 6;
  45565. ActionManager._OnPickUpTrigger = 7;
  45566. ActionManager._OnLongPressTrigger = 8;
  45567. ActionManager._OnPointerOverTrigger = 9;
  45568. ActionManager._OnPointerOutTrigger = 10;
  45569. ActionManager._OnEveryFrameTrigger = 11;
  45570. ActionManager._OnIntersectionEnterTrigger = 12;
  45571. ActionManager._OnIntersectionExitTrigger = 13;
  45572. ActionManager._OnKeyDownTrigger = 14;
  45573. ActionManager._OnKeyUpTrigger = 15;
  45574. ActionManager._OnPickOutTrigger = 16;
  45575. ActionManager.Triggers = {};
  45576. return ActionManager;
  45577. }());
  45578. BABYLON.ActionManager = ActionManager;
  45579. })(BABYLON || (BABYLON = {}));
  45580. //# sourceMappingURL=babylon.actionManager.js.map
  45581. var BABYLON;
  45582. (function (BABYLON) {
  45583. var InterpolateValueAction = /** @class */ (function (_super) {
  45584. __extends(InterpolateValueAction, _super);
  45585. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  45586. if (duration === void 0) { duration = 1000; }
  45587. var _this = _super.call(this, triggerOptions, condition) || this;
  45588. _this.propertyPath = propertyPath;
  45589. _this.value = value;
  45590. _this.duration = duration;
  45591. _this.stopOtherAnimations = stopOtherAnimations;
  45592. _this.onInterpolationDone = onInterpolationDone;
  45593. _this.onInterpolationDoneObservable = new BABYLON.Observable();
  45594. _this._target = _this._effectiveTarget = target;
  45595. return _this;
  45596. }
  45597. InterpolateValueAction.prototype._prepare = function () {
  45598. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  45599. this._property = this._getProperty(this.propertyPath);
  45600. };
  45601. InterpolateValueAction.prototype.execute = function () {
  45602. var _this = this;
  45603. var scene = this._actionManager.getScene();
  45604. var keys = [
  45605. {
  45606. frame: 0,
  45607. value: this._effectiveTarget[this._property]
  45608. }, {
  45609. frame: 100,
  45610. value: this.value
  45611. }
  45612. ];
  45613. var dataType;
  45614. if (typeof this.value === "number") {
  45615. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  45616. }
  45617. else if (this.value instanceof BABYLON.Color3) {
  45618. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  45619. }
  45620. else if (this.value instanceof BABYLON.Vector3) {
  45621. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  45622. }
  45623. else if (this.value instanceof BABYLON.Matrix) {
  45624. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  45625. }
  45626. else if (this.value instanceof BABYLON.Quaternion) {
  45627. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  45628. }
  45629. else {
  45630. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  45631. return;
  45632. }
  45633. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  45634. animation.setKeys(keys);
  45635. if (this.stopOtherAnimations) {
  45636. scene.stopAnimation(this._effectiveTarget);
  45637. }
  45638. var wrapper = function () {
  45639. _this.onInterpolationDoneObservable.notifyObservers(_this);
  45640. if (_this.onInterpolationDone) {
  45641. _this.onInterpolationDone();
  45642. }
  45643. };
  45644. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, wrapper);
  45645. };
  45646. InterpolateValueAction.prototype.serialize = function (parent) {
  45647. return _super.prototype._serialize.call(this, {
  45648. name: "InterpolateValueAction",
  45649. properties: [
  45650. BABYLON.Action._GetTargetProperty(this._target),
  45651. { name: "propertyPath", value: this.propertyPath },
  45652. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  45653. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  45654. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  45655. ]
  45656. }, parent);
  45657. };
  45658. return InterpolateValueAction;
  45659. }(BABYLON.Action));
  45660. BABYLON.InterpolateValueAction = InterpolateValueAction;
  45661. })(BABYLON || (BABYLON = {}));
  45662. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  45663. var BABYLON;
  45664. (function (BABYLON) {
  45665. var SwitchBooleanAction = /** @class */ (function (_super) {
  45666. __extends(SwitchBooleanAction, _super);
  45667. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  45668. var _this = _super.call(this, triggerOptions, condition) || this;
  45669. _this.propertyPath = propertyPath;
  45670. _this._target = _this._effectiveTarget = target;
  45671. return _this;
  45672. }
  45673. SwitchBooleanAction.prototype._prepare = function () {
  45674. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  45675. this._property = this._getProperty(this.propertyPath);
  45676. };
  45677. SwitchBooleanAction.prototype.execute = function () {
  45678. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  45679. };
  45680. SwitchBooleanAction.prototype.serialize = function (parent) {
  45681. return _super.prototype._serialize.call(this, {
  45682. name: "SwitchBooleanAction",
  45683. properties: [
  45684. BABYLON.Action._GetTargetProperty(this._target),
  45685. { name: "propertyPath", value: this.propertyPath }
  45686. ]
  45687. }, parent);
  45688. };
  45689. return SwitchBooleanAction;
  45690. }(BABYLON.Action));
  45691. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  45692. var SetStateAction = /** @class */ (function (_super) {
  45693. __extends(SetStateAction, _super);
  45694. function SetStateAction(triggerOptions, target, value, condition) {
  45695. var _this = _super.call(this, triggerOptions, condition) || this;
  45696. _this.value = value;
  45697. _this._target = target;
  45698. return _this;
  45699. }
  45700. SetStateAction.prototype.execute = function () {
  45701. this._target.state = this.value;
  45702. };
  45703. SetStateAction.prototype.serialize = function (parent) {
  45704. return _super.prototype._serialize.call(this, {
  45705. name: "SetStateAction",
  45706. properties: [
  45707. BABYLON.Action._GetTargetProperty(this._target),
  45708. { name: "value", value: this.value }
  45709. ]
  45710. }, parent);
  45711. };
  45712. return SetStateAction;
  45713. }(BABYLON.Action));
  45714. BABYLON.SetStateAction = SetStateAction;
  45715. var SetValueAction = /** @class */ (function (_super) {
  45716. __extends(SetValueAction, _super);
  45717. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  45718. var _this = _super.call(this, triggerOptions, condition) || this;
  45719. _this.propertyPath = propertyPath;
  45720. _this.value = value;
  45721. _this._target = _this._effectiveTarget = target;
  45722. return _this;
  45723. }
  45724. SetValueAction.prototype._prepare = function () {
  45725. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  45726. this._property = this._getProperty(this.propertyPath);
  45727. };
  45728. SetValueAction.prototype.execute = function () {
  45729. this._effectiveTarget[this._property] = this.value;
  45730. if (this._target.markAsDirty) {
  45731. this._target.markAsDirty(this._property);
  45732. }
  45733. };
  45734. SetValueAction.prototype.serialize = function (parent) {
  45735. return _super.prototype._serialize.call(this, {
  45736. name: "SetValueAction",
  45737. properties: [
  45738. BABYLON.Action._GetTargetProperty(this._target),
  45739. { name: "propertyPath", value: this.propertyPath },
  45740. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  45741. ]
  45742. }, parent);
  45743. };
  45744. return SetValueAction;
  45745. }(BABYLON.Action));
  45746. BABYLON.SetValueAction = SetValueAction;
  45747. var IncrementValueAction = /** @class */ (function (_super) {
  45748. __extends(IncrementValueAction, _super);
  45749. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  45750. var _this = _super.call(this, triggerOptions, condition) || this;
  45751. _this.propertyPath = propertyPath;
  45752. _this.value = value;
  45753. _this._target = _this._effectiveTarget = target;
  45754. return _this;
  45755. }
  45756. IncrementValueAction.prototype._prepare = function () {
  45757. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  45758. this._property = this._getProperty(this.propertyPath);
  45759. if (typeof this._effectiveTarget[this._property] !== "number") {
  45760. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  45761. }
  45762. };
  45763. IncrementValueAction.prototype.execute = function () {
  45764. this._effectiveTarget[this._property] += this.value;
  45765. if (this._target.markAsDirty) {
  45766. this._target.markAsDirty(this._property);
  45767. }
  45768. };
  45769. IncrementValueAction.prototype.serialize = function (parent) {
  45770. return _super.prototype._serialize.call(this, {
  45771. name: "IncrementValueAction",
  45772. properties: [
  45773. BABYLON.Action._GetTargetProperty(this._target),
  45774. { name: "propertyPath", value: this.propertyPath },
  45775. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  45776. ]
  45777. }, parent);
  45778. };
  45779. return IncrementValueAction;
  45780. }(BABYLON.Action));
  45781. BABYLON.IncrementValueAction = IncrementValueAction;
  45782. var PlayAnimationAction = /** @class */ (function (_super) {
  45783. __extends(PlayAnimationAction, _super);
  45784. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  45785. var _this = _super.call(this, triggerOptions, condition) || this;
  45786. _this.from = from;
  45787. _this.to = to;
  45788. _this.loop = loop;
  45789. _this._target = target;
  45790. return _this;
  45791. }
  45792. PlayAnimationAction.prototype._prepare = function () {
  45793. };
  45794. PlayAnimationAction.prototype.execute = function () {
  45795. var scene = this._actionManager.getScene();
  45796. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  45797. };
  45798. PlayAnimationAction.prototype.serialize = function (parent) {
  45799. return _super.prototype._serialize.call(this, {
  45800. name: "PlayAnimationAction",
  45801. properties: [
  45802. BABYLON.Action._GetTargetProperty(this._target),
  45803. { name: "from", value: String(this.from) },
  45804. { name: "to", value: String(this.to) },
  45805. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  45806. ]
  45807. }, parent);
  45808. };
  45809. return PlayAnimationAction;
  45810. }(BABYLON.Action));
  45811. BABYLON.PlayAnimationAction = PlayAnimationAction;
  45812. var StopAnimationAction = /** @class */ (function (_super) {
  45813. __extends(StopAnimationAction, _super);
  45814. function StopAnimationAction(triggerOptions, target, condition) {
  45815. var _this = _super.call(this, triggerOptions, condition) || this;
  45816. _this._target = target;
  45817. return _this;
  45818. }
  45819. StopAnimationAction.prototype._prepare = function () {
  45820. };
  45821. StopAnimationAction.prototype.execute = function () {
  45822. var scene = this._actionManager.getScene();
  45823. scene.stopAnimation(this._target);
  45824. };
  45825. StopAnimationAction.prototype.serialize = function (parent) {
  45826. return _super.prototype._serialize.call(this, {
  45827. name: "StopAnimationAction",
  45828. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  45829. }, parent);
  45830. };
  45831. return StopAnimationAction;
  45832. }(BABYLON.Action));
  45833. BABYLON.StopAnimationAction = StopAnimationAction;
  45834. var DoNothingAction = /** @class */ (function (_super) {
  45835. __extends(DoNothingAction, _super);
  45836. function DoNothingAction(triggerOptions, condition) {
  45837. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  45838. return _super.call(this, triggerOptions, condition) || this;
  45839. }
  45840. DoNothingAction.prototype.execute = function () {
  45841. };
  45842. DoNothingAction.prototype.serialize = function (parent) {
  45843. return _super.prototype._serialize.call(this, {
  45844. name: "DoNothingAction",
  45845. properties: []
  45846. }, parent);
  45847. };
  45848. return DoNothingAction;
  45849. }(BABYLON.Action));
  45850. BABYLON.DoNothingAction = DoNothingAction;
  45851. var CombineAction = /** @class */ (function (_super) {
  45852. __extends(CombineAction, _super);
  45853. function CombineAction(triggerOptions, children, condition) {
  45854. var _this = _super.call(this, triggerOptions, condition) || this;
  45855. _this.children = children;
  45856. return _this;
  45857. }
  45858. CombineAction.prototype._prepare = function () {
  45859. for (var index = 0; index < this.children.length; index++) {
  45860. this.children[index]._actionManager = this._actionManager;
  45861. this.children[index]._prepare();
  45862. }
  45863. };
  45864. CombineAction.prototype.execute = function (evt) {
  45865. for (var index = 0; index < this.children.length; index++) {
  45866. this.children[index].execute(evt);
  45867. }
  45868. };
  45869. CombineAction.prototype.serialize = function (parent) {
  45870. var serializationObject = _super.prototype._serialize.call(this, {
  45871. name: "CombineAction",
  45872. properties: [],
  45873. combine: []
  45874. }, parent);
  45875. for (var i = 0; i < this.children.length; i++) {
  45876. serializationObject.combine.push(this.children[i].serialize(null));
  45877. }
  45878. return serializationObject;
  45879. };
  45880. return CombineAction;
  45881. }(BABYLON.Action));
  45882. BABYLON.CombineAction = CombineAction;
  45883. var ExecuteCodeAction = /** @class */ (function (_super) {
  45884. __extends(ExecuteCodeAction, _super);
  45885. function ExecuteCodeAction(triggerOptions, func, condition) {
  45886. var _this = _super.call(this, triggerOptions, condition) || this;
  45887. _this.func = func;
  45888. return _this;
  45889. }
  45890. ExecuteCodeAction.prototype.execute = function (evt) {
  45891. this.func(evt);
  45892. };
  45893. return ExecuteCodeAction;
  45894. }(BABYLON.Action));
  45895. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  45896. var SetParentAction = /** @class */ (function (_super) {
  45897. __extends(SetParentAction, _super);
  45898. function SetParentAction(triggerOptions, target, parent, condition) {
  45899. var _this = _super.call(this, triggerOptions, condition) || this;
  45900. _this._target = target;
  45901. _this._parent = parent;
  45902. return _this;
  45903. }
  45904. SetParentAction.prototype._prepare = function () {
  45905. };
  45906. SetParentAction.prototype.execute = function () {
  45907. if (this._target.parent === this._parent) {
  45908. return;
  45909. }
  45910. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  45911. invertParentWorldMatrix.invert();
  45912. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  45913. this._target.parent = this._parent;
  45914. };
  45915. SetParentAction.prototype.serialize = function (parent) {
  45916. return _super.prototype._serialize.call(this, {
  45917. name: "SetParentAction",
  45918. properties: [
  45919. BABYLON.Action._GetTargetProperty(this._target),
  45920. BABYLON.Action._GetTargetProperty(this._parent),
  45921. ]
  45922. }, parent);
  45923. };
  45924. return SetParentAction;
  45925. }(BABYLON.Action));
  45926. BABYLON.SetParentAction = SetParentAction;
  45927. var PlaySoundAction = /** @class */ (function (_super) {
  45928. __extends(PlaySoundAction, _super);
  45929. function PlaySoundAction(triggerOptions, sound, condition) {
  45930. var _this = _super.call(this, triggerOptions, condition) || this;
  45931. _this._sound = sound;
  45932. return _this;
  45933. }
  45934. PlaySoundAction.prototype._prepare = function () {
  45935. };
  45936. PlaySoundAction.prototype.execute = function () {
  45937. if (this._sound !== undefined)
  45938. this._sound.play();
  45939. };
  45940. PlaySoundAction.prototype.serialize = function (parent) {
  45941. return _super.prototype._serialize.call(this, {
  45942. name: "PlaySoundAction",
  45943. properties: [{ name: "sound", value: this._sound.name }]
  45944. }, parent);
  45945. };
  45946. return PlaySoundAction;
  45947. }(BABYLON.Action));
  45948. BABYLON.PlaySoundAction = PlaySoundAction;
  45949. var StopSoundAction = /** @class */ (function (_super) {
  45950. __extends(StopSoundAction, _super);
  45951. function StopSoundAction(triggerOptions, sound, condition) {
  45952. var _this = _super.call(this, triggerOptions, condition) || this;
  45953. _this._sound = sound;
  45954. return _this;
  45955. }
  45956. StopSoundAction.prototype._prepare = function () {
  45957. };
  45958. StopSoundAction.prototype.execute = function () {
  45959. if (this._sound !== undefined)
  45960. this._sound.stop();
  45961. };
  45962. StopSoundAction.prototype.serialize = function (parent) {
  45963. return _super.prototype._serialize.call(this, {
  45964. name: "StopSoundAction",
  45965. properties: [{ name: "sound", value: this._sound.name }]
  45966. }, parent);
  45967. };
  45968. return StopSoundAction;
  45969. }(BABYLON.Action));
  45970. BABYLON.StopSoundAction = StopSoundAction;
  45971. })(BABYLON || (BABYLON = {}));
  45972. //# sourceMappingURL=babylon.directActions.js.map
  45973. var BABYLON;
  45974. (function (BABYLON) {
  45975. var SpriteManager = /** @class */ (function () {
  45976. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  45977. if (epsilon === void 0) { epsilon = 0.01; }
  45978. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  45979. this.name = name;
  45980. this.sprites = new Array();
  45981. this.renderingGroupId = 0;
  45982. this.layerMask = 0x0FFFFFFF;
  45983. this.fogEnabled = true;
  45984. this.isPickable = false;
  45985. /**
  45986. * An event triggered when the manager is disposed.
  45987. * @type {BABYLON.Observable}
  45988. */
  45989. this.onDisposeObservable = new BABYLON.Observable();
  45990. this._vertexBuffers = {};
  45991. this._capacity = capacity;
  45992. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  45993. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  45994. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  45995. if (cellSize.width && cellSize.height) {
  45996. this.cellWidth = cellSize.width;
  45997. this.cellHeight = cellSize.height;
  45998. }
  45999. else if (cellSize !== undefined) {
  46000. this.cellWidth = cellSize;
  46001. this.cellHeight = cellSize;
  46002. }
  46003. else {
  46004. return;
  46005. }
  46006. this._epsilon = epsilon;
  46007. this._scene = scene;
  46008. this._scene.spriteManagers.push(this);
  46009. var indices = [];
  46010. var index = 0;
  46011. for (var count = 0; count < capacity; count++) {
  46012. indices.push(index);
  46013. indices.push(index + 1);
  46014. indices.push(index + 2);
  46015. indices.push(index);
  46016. indices.push(index + 2);
  46017. indices.push(index + 3);
  46018. index += 4;
  46019. }
  46020. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  46021. // VBO
  46022. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  46023. this._vertexData = new Float32Array(capacity * 16 * 4);
  46024. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  46025. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  46026. var options = this._buffer.createVertexBuffer("options", 4, 4);
  46027. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  46028. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  46029. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  46030. this._vertexBuffers["options"] = options;
  46031. this._vertexBuffers["cellInfo"] = cellInfo;
  46032. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  46033. // Effects
  46034. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  46035. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  46036. }
  46037. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  46038. set: function (callback) {
  46039. if (this._onDisposeObserver) {
  46040. this.onDisposeObservable.remove(this._onDisposeObserver);
  46041. }
  46042. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  46043. },
  46044. enumerable: true,
  46045. configurable: true
  46046. });
  46047. Object.defineProperty(SpriteManager.prototype, "texture", {
  46048. get: function () {
  46049. return this._spriteTexture;
  46050. },
  46051. set: function (value) {
  46052. this._spriteTexture = value;
  46053. },
  46054. enumerable: true,
  46055. configurable: true
  46056. });
  46057. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  46058. var arrayOffset = index * 16;
  46059. if (offsetX === 0)
  46060. offsetX = this._epsilon;
  46061. else if (offsetX === 1)
  46062. offsetX = 1 - this._epsilon;
  46063. if (offsetY === 0)
  46064. offsetY = this._epsilon;
  46065. else if (offsetY === 1)
  46066. offsetY = 1 - this._epsilon;
  46067. this._vertexData[arrayOffset] = sprite.position.x;
  46068. this._vertexData[arrayOffset + 1] = sprite.position.y;
  46069. this._vertexData[arrayOffset + 2] = sprite.position.z;
  46070. this._vertexData[arrayOffset + 3] = sprite.angle;
  46071. this._vertexData[arrayOffset + 4] = sprite.width;
  46072. this._vertexData[arrayOffset + 5] = sprite.height;
  46073. this._vertexData[arrayOffset + 6] = offsetX;
  46074. this._vertexData[arrayOffset + 7] = offsetY;
  46075. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  46076. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  46077. var offset = (sprite.cellIndex / rowSize) >> 0;
  46078. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  46079. this._vertexData[arrayOffset + 11] = offset;
  46080. // Color
  46081. this._vertexData[arrayOffset + 12] = sprite.color.r;
  46082. this._vertexData[arrayOffset + 13] = sprite.color.g;
  46083. this._vertexData[arrayOffset + 14] = sprite.color.b;
  46084. this._vertexData[arrayOffset + 15] = sprite.color.a;
  46085. };
  46086. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  46087. var count = Math.min(this._capacity, this.sprites.length);
  46088. var min = BABYLON.Vector3.Zero();
  46089. var max = BABYLON.Vector3.Zero();
  46090. var distance = Number.MAX_VALUE;
  46091. var currentSprite = null;
  46092. var cameraSpacePosition = BABYLON.Vector3.Zero();
  46093. var cameraView = camera.getViewMatrix();
  46094. for (var index = 0; index < count; index++) {
  46095. var sprite = this.sprites[index];
  46096. if (!sprite) {
  46097. continue;
  46098. }
  46099. if (predicate) {
  46100. if (!predicate(sprite)) {
  46101. continue;
  46102. }
  46103. }
  46104. else if (!sprite.isPickable) {
  46105. continue;
  46106. }
  46107. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  46108. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  46109. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  46110. if (ray.intersectsBoxMinMax(min, max)) {
  46111. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  46112. if (distance > currentDistance) {
  46113. distance = currentDistance;
  46114. currentSprite = sprite;
  46115. if (fastCheck) {
  46116. break;
  46117. }
  46118. }
  46119. }
  46120. }
  46121. if (currentSprite) {
  46122. var result = new BABYLON.PickingInfo();
  46123. result.hit = true;
  46124. result.pickedSprite = currentSprite;
  46125. result.distance = distance;
  46126. return result;
  46127. }
  46128. return null;
  46129. };
  46130. SpriteManager.prototype.render = function () {
  46131. // Check
  46132. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  46133. return;
  46134. var engine = this._scene.getEngine();
  46135. var baseSize = this._spriteTexture.getBaseSize();
  46136. // Sprites
  46137. var deltaTime = engine.getDeltaTime();
  46138. var max = Math.min(this._capacity, this.sprites.length);
  46139. var rowSize = baseSize.width / this.cellWidth;
  46140. var offset = 0;
  46141. for (var index = 0; index < max; index++) {
  46142. var sprite = this.sprites[index];
  46143. if (!sprite) {
  46144. continue;
  46145. }
  46146. sprite._animate(deltaTime);
  46147. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  46148. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  46149. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  46150. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  46151. }
  46152. this._buffer.update(this._vertexData);
  46153. // Render
  46154. var effect = this._effectBase;
  46155. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  46156. effect = this._effectFog;
  46157. }
  46158. engine.enableEffect(effect);
  46159. var viewMatrix = this._scene.getViewMatrix();
  46160. effect.setTexture("diffuseSampler", this._spriteTexture);
  46161. effect.setMatrix("view", viewMatrix);
  46162. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  46163. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  46164. // Fog
  46165. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  46166. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  46167. effect.setColor3("vFogColor", this._scene.fogColor);
  46168. }
  46169. // VBOs
  46170. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  46171. // Draw order
  46172. engine.setDepthFunctionToLessOrEqual();
  46173. effect.setBool("alphaTest", true);
  46174. engine.setColorWrite(false);
  46175. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  46176. engine.setColorWrite(true);
  46177. effect.setBool("alphaTest", false);
  46178. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  46179. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  46180. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  46181. };
  46182. SpriteManager.prototype.dispose = function () {
  46183. if (this._buffer) {
  46184. this._buffer.dispose();
  46185. this._buffer = null;
  46186. }
  46187. if (this._indexBuffer) {
  46188. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  46189. this._indexBuffer = null;
  46190. }
  46191. if (this._spriteTexture) {
  46192. this._spriteTexture.dispose();
  46193. this._spriteTexture = null;
  46194. }
  46195. // Remove from scene
  46196. var index = this._scene.spriteManagers.indexOf(this);
  46197. this._scene.spriteManagers.splice(index, 1);
  46198. // Callback
  46199. this.onDisposeObservable.notifyObservers(this);
  46200. this.onDisposeObservable.clear();
  46201. };
  46202. return SpriteManager;
  46203. }());
  46204. BABYLON.SpriteManager = SpriteManager;
  46205. })(BABYLON || (BABYLON = {}));
  46206. //# sourceMappingURL=babylon.spriteManager.js.map
  46207. var BABYLON;
  46208. (function (BABYLON) {
  46209. var Sprite = /** @class */ (function () {
  46210. function Sprite(name, manager) {
  46211. this.name = name;
  46212. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  46213. this.width = 1.0;
  46214. this.height = 1.0;
  46215. this.angle = 0;
  46216. this.cellIndex = 0;
  46217. this.invertU = 0;
  46218. this.invertV = 0;
  46219. this.animations = new Array();
  46220. this.isPickable = false;
  46221. this._animationStarted = false;
  46222. this._loopAnimation = false;
  46223. this._fromIndex = 0;
  46224. this._toIndex = 0;
  46225. this._delay = 0;
  46226. this._direction = 1;
  46227. this._time = 0;
  46228. this._manager = manager;
  46229. this._manager.sprites.push(this);
  46230. this.position = BABYLON.Vector3.Zero();
  46231. }
  46232. Object.defineProperty(Sprite.prototype, "size", {
  46233. get: function () {
  46234. return this.width;
  46235. },
  46236. set: function (value) {
  46237. this.width = value;
  46238. this.height = value;
  46239. },
  46240. enumerable: true,
  46241. configurable: true
  46242. });
  46243. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  46244. this._fromIndex = from;
  46245. this._toIndex = to;
  46246. this._loopAnimation = loop;
  46247. this._delay = delay;
  46248. this._animationStarted = true;
  46249. this._direction = from < to ? 1 : -1;
  46250. this.cellIndex = from;
  46251. this._time = 0;
  46252. this._onAnimationEnd = onAnimationEnd;
  46253. };
  46254. Sprite.prototype.stopAnimation = function () {
  46255. this._animationStarted = false;
  46256. };
  46257. Sprite.prototype._animate = function (deltaTime) {
  46258. if (!this._animationStarted)
  46259. return;
  46260. this._time += deltaTime;
  46261. if (this._time > this._delay) {
  46262. this._time = this._time % this._delay;
  46263. this.cellIndex += this._direction;
  46264. if (this.cellIndex > this._toIndex) {
  46265. if (this._loopAnimation) {
  46266. this.cellIndex = this._fromIndex;
  46267. }
  46268. else {
  46269. this.cellIndex = this._toIndex;
  46270. this._animationStarted = false;
  46271. if (this._onAnimationEnd) {
  46272. this._onAnimationEnd();
  46273. }
  46274. if (this.disposeWhenFinishedAnimating) {
  46275. this.dispose();
  46276. }
  46277. }
  46278. }
  46279. }
  46280. };
  46281. Sprite.prototype.dispose = function () {
  46282. for (var i = 0; i < this._manager.sprites.length; i++) {
  46283. if (this._manager.sprites[i] == this) {
  46284. this._manager.sprites.splice(i, 1);
  46285. }
  46286. }
  46287. };
  46288. return Sprite;
  46289. }());
  46290. BABYLON.Sprite = Sprite;
  46291. })(BABYLON || (BABYLON = {}));
  46292. //# sourceMappingURL=babylon.sprite.js.map
  46293. var BABYLON;
  46294. (function (BABYLON) {
  46295. var IntersectionInfo = /** @class */ (function () {
  46296. function IntersectionInfo(bu, bv, distance) {
  46297. this.bu = bu;
  46298. this.bv = bv;
  46299. this.distance = distance;
  46300. this.faceId = 0;
  46301. this.subMeshId = 0;
  46302. }
  46303. return IntersectionInfo;
  46304. }());
  46305. BABYLON.IntersectionInfo = IntersectionInfo;
  46306. var PickingInfo = /** @class */ (function () {
  46307. function PickingInfo() {
  46308. this.hit = false;
  46309. this.distance = 0;
  46310. this.pickedPoint = null;
  46311. this.pickedMesh = null;
  46312. this.bu = 0;
  46313. this.bv = 0;
  46314. this.faceId = -1;
  46315. this.subMeshId = 0;
  46316. this.pickedSprite = null;
  46317. }
  46318. // Methods
  46319. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  46320. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  46321. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  46322. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  46323. return null;
  46324. }
  46325. var indices = this.pickedMesh.getIndices();
  46326. if (!indices) {
  46327. return null;
  46328. }
  46329. var result;
  46330. if (useVerticesNormals) {
  46331. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  46332. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  46333. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  46334. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  46335. normal0 = normal0.scale(this.bu);
  46336. normal1 = normal1.scale(this.bv);
  46337. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  46338. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  46339. }
  46340. else {
  46341. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  46342. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  46343. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  46344. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  46345. var p1p2 = vertex1.subtract(vertex2);
  46346. var p3p2 = vertex3.subtract(vertex2);
  46347. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  46348. }
  46349. if (useWorldCoordinates) {
  46350. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  46351. }
  46352. return BABYLON.Vector3.Normalize(result);
  46353. };
  46354. PickingInfo.prototype.getTextureCoordinates = function () {
  46355. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  46356. return null;
  46357. }
  46358. var indices = this.pickedMesh.getIndices();
  46359. if (!indices) {
  46360. return null;
  46361. }
  46362. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  46363. if (!uvs) {
  46364. return null;
  46365. }
  46366. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  46367. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  46368. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  46369. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  46370. uv1 = uv1.scale(this.bu);
  46371. uv2 = uv2.scale(this.bv);
  46372. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  46373. };
  46374. return PickingInfo;
  46375. }());
  46376. BABYLON.PickingInfo = PickingInfo;
  46377. })(BABYLON || (BABYLON = {}));
  46378. //# sourceMappingURL=babylon.pickingInfo.js.map
  46379. var BABYLON;
  46380. (function (BABYLON) {
  46381. var Ray = /** @class */ (function () {
  46382. function Ray(origin, direction, length) {
  46383. if (length === void 0) { length = Number.MAX_VALUE; }
  46384. this.origin = origin;
  46385. this.direction = direction;
  46386. this.length = length;
  46387. }
  46388. // Methods
  46389. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  46390. var d = 0.0;
  46391. var maxValue = Number.MAX_VALUE;
  46392. var inv;
  46393. var min;
  46394. var max;
  46395. var temp;
  46396. if (Math.abs(this.direction.x) < 0.0000001) {
  46397. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  46398. return false;
  46399. }
  46400. }
  46401. else {
  46402. inv = 1.0 / this.direction.x;
  46403. min = (minimum.x - this.origin.x) * inv;
  46404. max = (maximum.x - this.origin.x) * inv;
  46405. if (max === -Infinity) {
  46406. max = Infinity;
  46407. }
  46408. if (min > max) {
  46409. temp = min;
  46410. min = max;
  46411. max = temp;
  46412. }
  46413. d = Math.max(min, d);
  46414. maxValue = Math.min(max, maxValue);
  46415. if (d > maxValue) {
  46416. return false;
  46417. }
  46418. }
  46419. if (Math.abs(this.direction.y) < 0.0000001) {
  46420. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  46421. return false;
  46422. }
  46423. }
  46424. else {
  46425. inv = 1.0 / this.direction.y;
  46426. min = (minimum.y - this.origin.y) * inv;
  46427. max = (maximum.y - this.origin.y) * inv;
  46428. if (max === -Infinity) {
  46429. max = Infinity;
  46430. }
  46431. if (min > max) {
  46432. temp = min;
  46433. min = max;
  46434. max = temp;
  46435. }
  46436. d = Math.max(min, d);
  46437. maxValue = Math.min(max, maxValue);
  46438. if (d > maxValue) {
  46439. return false;
  46440. }
  46441. }
  46442. if (Math.abs(this.direction.z) < 0.0000001) {
  46443. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  46444. return false;
  46445. }
  46446. }
  46447. else {
  46448. inv = 1.0 / this.direction.z;
  46449. min = (minimum.z - this.origin.z) * inv;
  46450. max = (maximum.z - this.origin.z) * inv;
  46451. if (max === -Infinity) {
  46452. max = Infinity;
  46453. }
  46454. if (min > max) {
  46455. temp = min;
  46456. min = max;
  46457. max = temp;
  46458. }
  46459. d = Math.max(min, d);
  46460. maxValue = Math.min(max, maxValue);
  46461. if (d > maxValue) {
  46462. return false;
  46463. }
  46464. }
  46465. return true;
  46466. };
  46467. Ray.prototype.intersectsBox = function (box) {
  46468. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  46469. };
  46470. Ray.prototype.intersectsSphere = function (sphere) {
  46471. var x = sphere.center.x - this.origin.x;
  46472. var y = sphere.center.y - this.origin.y;
  46473. var z = sphere.center.z - this.origin.z;
  46474. var pyth = (x * x) + (y * y) + (z * z);
  46475. var rr = sphere.radius * sphere.radius;
  46476. if (pyth <= rr) {
  46477. return true;
  46478. }
  46479. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  46480. if (dot < 0.0) {
  46481. return false;
  46482. }
  46483. var temp = pyth - (dot * dot);
  46484. return temp <= rr;
  46485. };
  46486. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  46487. if (!this._edge1) {
  46488. this._edge1 = BABYLON.Vector3.Zero();
  46489. this._edge2 = BABYLON.Vector3.Zero();
  46490. this._pvec = BABYLON.Vector3.Zero();
  46491. this._tvec = BABYLON.Vector3.Zero();
  46492. this._qvec = BABYLON.Vector3.Zero();
  46493. }
  46494. vertex1.subtractToRef(vertex0, this._edge1);
  46495. vertex2.subtractToRef(vertex0, this._edge2);
  46496. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  46497. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  46498. if (det === 0) {
  46499. return null;
  46500. }
  46501. var invdet = 1 / det;
  46502. this.origin.subtractToRef(vertex0, this._tvec);
  46503. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  46504. if (bu < 0 || bu > 1.0) {
  46505. return null;
  46506. }
  46507. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  46508. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  46509. if (bv < 0 || bu + bv > 1.0) {
  46510. return null;
  46511. }
  46512. //check if the distance is longer than the predefined length.
  46513. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  46514. if (distance > this.length) {
  46515. return null;
  46516. }
  46517. return new BABYLON.IntersectionInfo(bu, bv, distance);
  46518. };
  46519. Ray.prototype.intersectsPlane = function (plane) {
  46520. var distance;
  46521. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  46522. if (Math.abs(result1) < 9.99999997475243E-07) {
  46523. return null;
  46524. }
  46525. else {
  46526. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  46527. distance = (-plane.d - result2) / result1;
  46528. if (distance < 0.0) {
  46529. if (distance < -9.99999997475243E-07) {
  46530. return null;
  46531. }
  46532. else {
  46533. return 0;
  46534. }
  46535. }
  46536. return distance;
  46537. }
  46538. };
  46539. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  46540. var tm = BABYLON.Tmp.Matrix[0];
  46541. mesh.getWorldMatrix().invertToRef(tm);
  46542. if (this._tmpRay) {
  46543. Ray.TransformToRef(this, tm, this._tmpRay);
  46544. }
  46545. else {
  46546. this._tmpRay = Ray.Transform(this, tm);
  46547. }
  46548. return mesh.intersects(this._tmpRay, fastCheck);
  46549. };
  46550. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  46551. if (results) {
  46552. results.length = 0;
  46553. }
  46554. else {
  46555. results = [];
  46556. }
  46557. for (var i = 0; i < meshes.length; i++) {
  46558. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  46559. if (pickInfo.hit) {
  46560. results.push(pickInfo);
  46561. }
  46562. }
  46563. results.sort(this._comparePickingInfo);
  46564. return results;
  46565. };
  46566. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  46567. if (pickingInfoA.distance < pickingInfoB.distance) {
  46568. return -1;
  46569. }
  46570. else if (pickingInfoA.distance > pickingInfoB.distance) {
  46571. return 1;
  46572. }
  46573. else {
  46574. return 0;
  46575. }
  46576. };
  46577. /**
  46578. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  46579. * @param sega the first point of the segment to test the intersection against
  46580. * @param segb the second point of the segment to test the intersection against
  46581. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  46582. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  46583. */
  46584. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  46585. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  46586. var u = segb.subtract(sega);
  46587. var v = rsegb.subtract(this.origin);
  46588. var w = sega.subtract(this.origin);
  46589. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  46590. var b = BABYLON.Vector3.Dot(u, v);
  46591. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  46592. var d = BABYLON.Vector3.Dot(u, w);
  46593. var e = BABYLON.Vector3.Dot(v, w);
  46594. var D = a * c - b * b; // always >= 0
  46595. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  46596. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  46597. // compute the line parameters of the two closest points
  46598. if (D < Ray.smallnum) {
  46599. sN = 0.0; // force using point P0 on segment S1
  46600. sD = 1.0; // to prevent possible division by 0.0 later
  46601. tN = e;
  46602. tD = c;
  46603. }
  46604. else {
  46605. sN = (b * e - c * d);
  46606. tN = (a * e - b * d);
  46607. if (sN < 0.0) {
  46608. sN = 0.0;
  46609. tN = e;
  46610. tD = c;
  46611. }
  46612. else if (sN > sD) {
  46613. sN = sD;
  46614. tN = e + b;
  46615. tD = c;
  46616. }
  46617. }
  46618. if (tN < 0.0) {
  46619. tN = 0.0;
  46620. // recompute sc for this edge
  46621. if (-d < 0.0) {
  46622. sN = 0.0;
  46623. }
  46624. else if (-d > a)
  46625. sN = sD;
  46626. else {
  46627. sN = -d;
  46628. sD = a;
  46629. }
  46630. }
  46631. else if (tN > tD) {
  46632. tN = tD;
  46633. // recompute sc for this edge
  46634. if ((-d + b) < 0.0) {
  46635. sN = 0;
  46636. }
  46637. else if ((-d + b) > a) {
  46638. sN = sD;
  46639. }
  46640. else {
  46641. sN = (-d + b);
  46642. sD = a;
  46643. }
  46644. }
  46645. // finally do the division to get sc and tc
  46646. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  46647. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  46648. // get the difference of the two closest points
  46649. var qtc = v.multiplyByFloats(tc, tc, tc);
  46650. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  46651. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  46652. if (isIntersected) {
  46653. return qtc.length();
  46654. }
  46655. return -1;
  46656. };
  46657. Ray.prototype.update = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  46658. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 0, viewportWidth, viewportHeight, world, view, projection, this.origin);
  46659. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 1, viewportWidth, viewportHeight, world, view, projection, BABYLON.Tmp.Vector3[0]);
  46660. BABYLON.Tmp.Vector3[0].subtractToRef(this.origin, this.direction);
  46661. this.direction.normalize();
  46662. return this;
  46663. };
  46664. // Statics
  46665. Ray.Zero = function () {
  46666. return new Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero());
  46667. };
  46668. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  46669. var result = Ray.Zero();
  46670. return result.update(x, y, viewportWidth, viewportHeight, world, view, projection);
  46671. };
  46672. /**
  46673. * 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
  46674. * transformed to the given world matrix.
  46675. * @param origin The origin point
  46676. * @param end The end point
  46677. * @param world a matrix to transform the ray to. Default is the identity matrix.
  46678. */
  46679. Ray.CreateNewFromTo = function (origin, end, world) {
  46680. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  46681. var direction = end.subtract(origin);
  46682. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  46683. direction.normalize();
  46684. return Ray.Transform(new Ray(origin, direction, length), world);
  46685. };
  46686. Ray.Transform = function (ray, matrix) {
  46687. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  46688. Ray.TransformToRef(ray, matrix, result);
  46689. return result;
  46690. };
  46691. Ray.TransformToRef = function (ray, matrix, result) {
  46692. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  46693. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  46694. result.length = ray.length;
  46695. var dir = result.direction;
  46696. var len = dir.length();
  46697. if (!(len === 0 || len === 1)) {
  46698. var num = 1.0 / len;
  46699. dir.x *= num;
  46700. dir.y *= num;
  46701. dir.z *= num;
  46702. result.length *= len;
  46703. }
  46704. };
  46705. Ray.smallnum = 0.00000001;
  46706. Ray.rayl = 10e8;
  46707. return Ray;
  46708. }());
  46709. BABYLON.Ray = Ray;
  46710. })(BABYLON || (BABYLON = {}));
  46711. //# sourceMappingURL=babylon.ray.js.map
  46712. var BABYLON;
  46713. (function (BABYLON) {
  46714. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  46715. if (boxMin.x > sphereCenter.x + sphereRadius)
  46716. return false;
  46717. if (sphereCenter.x - sphereRadius > boxMax.x)
  46718. return false;
  46719. if (boxMin.y > sphereCenter.y + sphereRadius)
  46720. return false;
  46721. if (sphereCenter.y - sphereRadius > boxMax.y)
  46722. return false;
  46723. if (boxMin.z > sphereCenter.z + sphereRadius)
  46724. return false;
  46725. if (sphereCenter.z - sphereRadius > boxMax.z)
  46726. return false;
  46727. return true;
  46728. };
  46729. var getLowestRoot = (function () {
  46730. var result = { root: 0, found: false };
  46731. return function (a, b, c, maxR) {
  46732. result.root = 0;
  46733. result.found = false;
  46734. var determinant = b * b - 4.0 * a * c;
  46735. if (determinant < 0)
  46736. return result;
  46737. var sqrtD = Math.sqrt(determinant);
  46738. var r1 = (-b - sqrtD) / (2.0 * a);
  46739. var r2 = (-b + sqrtD) / (2.0 * a);
  46740. if (r1 > r2) {
  46741. var temp = r2;
  46742. r2 = r1;
  46743. r1 = temp;
  46744. }
  46745. if (r1 > 0 && r1 < maxR) {
  46746. result.root = r1;
  46747. result.found = true;
  46748. return result;
  46749. }
  46750. if (r2 > 0 && r2 < maxR) {
  46751. result.root = r2;
  46752. result.found = true;
  46753. return result;
  46754. }
  46755. return result;
  46756. };
  46757. })();
  46758. var Collider = /** @class */ (function () {
  46759. function Collider() {
  46760. this._collisionPoint = BABYLON.Vector3.Zero();
  46761. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  46762. this._tempVector = BABYLON.Vector3.Zero();
  46763. this._tempVector2 = BABYLON.Vector3.Zero();
  46764. this._tempVector3 = BABYLON.Vector3.Zero();
  46765. this._tempVector4 = BABYLON.Vector3.Zero();
  46766. this._edge = BABYLON.Vector3.Zero();
  46767. this._baseToVertex = BABYLON.Vector3.Zero();
  46768. this._destinationPoint = BABYLON.Vector3.Zero();
  46769. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  46770. this._displacementVector = BABYLON.Vector3.Zero();
  46771. this._radius = BABYLON.Vector3.One();
  46772. this._retry = 0;
  46773. this._basePointWorld = BABYLON.Vector3.Zero();
  46774. this._velocityWorld = BABYLON.Vector3.Zero();
  46775. this._normalizedVelocity = BABYLON.Vector3.Zero();
  46776. this._collisionMask = -1;
  46777. }
  46778. Object.defineProperty(Collider.prototype, "collisionMask", {
  46779. get: function () {
  46780. return this._collisionMask;
  46781. },
  46782. set: function (mask) {
  46783. this._collisionMask = !isNaN(mask) ? mask : -1;
  46784. },
  46785. enumerable: true,
  46786. configurable: true
  46787. });
  46788. Object.defineProperty(Collider.prototype, "slidePlaneNormal", {
  46789. /**
  46790. * Gets the plane normal used to compute the sliding response (in local space)
  46791. */
  46792. get: function () {
  46793. return this._slidePlaneNormal;
  46794. },
  46795. enumerable: true,
  46796. configurable: true
  46797. });
  46798. // Methods
  46799. Collider.prototype._initialize = function (source, dir, e) {
  46800. this._velocity = dir;
  46801. BABYLON.Vector3.NormalizeToRef(dir, this._normalizedVelocity);
  46802. this._basePoint = source;
  46803. source.multiplyToRef(this._radius, this._basePointWorld);
  46804. dir.multiplyToRef(this._radius, this._velocityWorld);
  46805. this._velocityWorldLength = this._velocityWorld.length();
  46806. this._epsilon = e;
  46807. this.collisionFound = false;
  46808. };
  46809. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  46810. pa.subtractToRef(point, this._tempVector);
  46811. pb.subtractToRef(point, this._tempVector2);
  46812. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  46813. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  46814. if (d < 0)
  46815. return false;
  46816. pc.subtractToRef(point, this._tempVector3);
  46817. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  46818. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  46819. if (d < 0)
  46820. return false;
  46821. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  46822. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  46823. return d >= 0;
  46824. };
  46825. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  46826. var distance = BABYLON.Vector3.Distance(this._basePointWorld, sphereCenter);
  46827. var max = Math.max(this._radius.x, this._radius.y, this._radius.z);
  46828. if (distance > this._velocityWorldLength + max + sphereRadius) {
  46829. return false;
  46830. }
  46831. if (!intersectBoxAASphere(vecMin, vecMax, this._basePointWorld, this._velocityWorldLength + max))
  46832. return false;
  46833. return true;
  46834. };
  46835. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  46836. var t0;
  46837. var embeddedInPlane = false;
  46838. //defensive programming, actually not needed.
  46839. if (!trianglePlaneArray) {
  46840. trianglePlaneArray = [];
  46841. }
  46842. if (!trianglePlaneArray[faceIndex]) {
  46843. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  46844. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  46845. }
  46846. var trianglePlane = trianglePlaneArray[faceIndex];
  46847. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this._normalizedVelocity, 0))
  46848. return;
  46849. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this._basePoint);
  46850. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this._velocity);
  46851. if (normalDotVelocity == 0) {
  46852. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  46853. return;
  46854. embeddedInPlane = true;
  46855. t0 = 0;
  46856. }
  46857. else {
  46858. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  46859. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  46860. if (t0 > t1) {
  46861. var temp = t1;
  46862. t1 = t0;
  46863. t0 = temp;
  46864. }
  46865. if (t0 > 1.0 || t1 < 0.0)
  46866. return;
  46867. if (t0 < 0)
  46868. t0 = 0;
  46869. if (t0 > 1.0)
  46870. t0 = 1.0;
  46871. }
  46872. this._collisionPoint.copyFromFloats(0, 0, 0);
  46873. var found = false;
  46874. var t = 1.0;
  46875. if (!embeddedInPlane) {
  46876. this._basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  46877. this._velocity.scaleToRef(t0, this._tempVector);
  46878. this._planeIntersectionPoint.addInPlace(this._tempVector);
  46879. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  46880. found = true;
  46881. t = t0;
  46882. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  46883. }
  46884. }
  46885. if (!found) {
  46886. var velocitySquaredLength = this._velocity.lengthSquared();
  46887. var a = velocitySquaredLength;
  46888. this._basePoint.subtractToRef(p1, this._tempVector);
  46889. var b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  46890. var c = this._tempVector.lengthSquared() - 1.0;
  46891. var lowestRoot = getLowestRoot(a, b, c, t);
  46892. if (lowestRoot.found) {
  46893. t = lowestRoot.root;
  46894. found = true;
  46895. this._collisionPoint.copyFrom(p1);
  46896. }
  46897. this._basePoint.subtractToRef(p2, this._tempVector);
  46898. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  46899. c = this._tempVector.lengthSquared() - 1.0;
  46900. lowestRoot = getLowestRoot(a, b, c, t);
  46901. if (lowestRoot.found) {
  46902. t = lowestRoot.root;
  46903. found = true;
  46904. this._collisionPoint.copyFrom(p2);
  46905. }
  46906. this._basePoint.subtractToRef(p3, this._tempVector);
  46907. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  46908. c = this._tempVector.lengthSquared() - 1.0;
  46909. lowestRoot = getLowestRoot(a, b, c, t);
  46910. if (lowestRoot.found) {
  46911. t = lowestRoot.root;
  46912. found = true;
  46913. this._collisionPoint.copyFrom(p3);
  46914. }
  46915. p2.subtractToRef(p1, this._edge);
  46916. p1.subtractToRef(this._basePoint, this._baseToVertex);
  46917. var edgeSquaredLength = this._edge.lengthSquared();
  46918. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  46919. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  46920. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  46921. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  46922. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  46923. lowestRoot = getLowestRoot(a, b, c, t);
  46924. if (lowestRoot.found) {
  46925. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  46926. if (f >= 0.0 && f <= 1.0) {
  46927. t = lowestRoot.root;
  46928. found = true;
  46929. this._edge.scaleInPlace(f);
  46930. p1.addToRef(this._edge, this._collisionPoint);
  46931. }
  46932. }
  46933. p3.subtractToRef(p2, this._edge);
  46934. p2.subtractToRef(this._basePoint, this._baseToVertex);
  46935. edgeSquaredLength = this._edge.lengthSquared();
  46936. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  46937. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  46938. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  46939. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  46940. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  46941. lowestRoot = getLowestRoot(a, b, c, t);
  46942. if (lowestRoot.found) {
  46943. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  46944. if (f >= 0.0 && f <= 1.0) {
  46945. t = lowestRoot.root;
  46946. found = true;
  46947. this._edge.scaleInPlace(f);
  46948. p2.addToRef(this._edge, this._collisionPoint);
  46949. }
  46950. }
  46951. p1.subtractToRef(p3, this._edge);
  46952. p3.subtractToRef(this._basePoint, this._baseToVertex);
  46953. edgeSquaredLength = this._edge.lengthSquared();
  46954. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  46955. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  46956. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  46957. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  46958. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  46959. lowestRoot = getLowestRoot(a, b, c, t);
  46960. if (lowestRoot.found) {
  46961. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  46962. if (f >= 0.0 && f <= 1.0) {
  46963. t = lowestRoot.root;
  46964. found = true;
  46965. this._edge.scaleInPlace(f);
  46966. p3.addToRef(this._edge, this._collisionPoint);
  46967. }
  46968. }
  46969. }
  46970. if (found) {
  46971. var distToCollision = t * this._velocity.length();
  46972. if (!this.collisionFound || distToCollision < this._nearestDistance) {
  46973. if (!this.intersectionPoint) {
  46974. this.intersectionPoint = this._collisionPoint.clone();
  46975. }
  46976. else {
  46977. this.intersectionPoint.copyFrom(this._collisionPoint);
  46978. }
  46979. this._nearestDistance = distToCollision;
  46980. this.collisionFound = true;
  46981. }
  46982. }
  46983. };
  46984. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  46985. for (var i = indexStart; i < indexEnd; i += 3) {
  46986. var p1 = pts[indices[i] - decal];
  46987. var p2 = pts[indices[i + 1] - decal];
  46988. var p3 = pts[indices[i + 2] - decal];
  46989. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  46990. }
  46991. };
  46992. Collider.prototype._getResponse = function (pos, vel) {
  46993. pos.addToRef(vel, this._destinationPoint);
  46994. vel.scaleInPlace((this._nearestDistance / vel.length()));
  46995. this._basePoint.addToRef(vel, pos);
  46996. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  46997. this._slidePlaneNormal.normalize();
  46998. this._slidePlaneNormal.scaleToRef(this._epsilon, this._displacementVector);
  46999. pos.addInPlace(this._displacementVector);
  47000. this.intersectionPoint.addInPlace(this._displacementVector);
  47001. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  47002. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  47003. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  47004. };
  47005. return Collider;
  47006. }());
  47007. BABYLON.Collider = Collider;
  47008. })(BABYLON || (BABYLON = {}));
  47009. //# sourceMappingURL=babylon.collider.js.map
  47010. var BABYLON;
  47011. (function (BABYLON) {
  47012. //WebWorker code will be inserted to this variable.
  47013. BABYLON.CollisionWorker = "";
  47014. var WorkerTaskType;
  47015. (function (WorkerTaskType) {
  47016. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  47017. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  47018. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  47019. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  47020. var WorkerReplyType;
  47021. (function (WorkerReplyType) {
  47022. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  47023. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  47024. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  47025. var CollisionCoordinatorWorker = /** @class */ (function () {
  47026. function CollisionCoordinatorWorker() {
  47027. var _this = this;
  47028. this._scaledPosition = BABYLON.Vector3.Zero();
  47029. this._scaledVelocity = BABYLON.Vector3.Zero();
  47030. this.onMeshUpdated = function (transformNode) {
  47031. _this._addUpdateMeshesList[transformNode.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(transformNode);
  47032. };
  47033. this.onGeometryUpdated = function (geometry) {
  47034. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  47035. };
  47036. this._afterRender = function () {
  47037. if (!_this._init)
  47038. return;
  47039. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  47040. return;
  47041. }
  47042. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  47043. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  47044. if (_this._runningUpdated > 4) {
  47045. return;
  47046. }
  47047. ++_this._runningUpdated;
  47048. var payload = {
  47049. updatedMeshes: _this._addUpdateMeshesList,
  47050. updatedGeometries: _this._addUpdateGeometriesList,
  47051. removedGeometries: _this._toRemoveGeometryArray,
  47052. removedMeshes: _this._toRemoveMeshesArray
  47053. };
  47054. var message = {
  47055. payload: payload,
  47056. taskType: WorkerTaskType.UPDATE
  47057. };
  47058. var serializable = [];
  47059. for (var id in payload.updatedGeometries) {
  47060. if (payload.updatedGeometries.hasOwnProperty(id)) {
  47061. //prepare transferables
  47062. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  47063. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  47064. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  47065. }
  47066. }
  47067. _this._worker.postMessage(message, serializable);
  47068. _this._addUpdateMeshesList = {};
  47069. _this._addUpdateGeometriesList = {};
  47070. _this._toRemoveGeometryArray = [];
  47071. _this._toRemoveMeshesArray = [];
  47072. };
  47073. this._onMessageFromWorker = function (e) {
  47074. var returnData = e.data;
  47075. if (returnData.error != WorkerReplyType.SUCCESS) {
  47076. //TODO what errors can be returned from the worker?
  47077. BABYLON.Tools.Warn("error returned from worker!");
  47078. return;
  47079. }
  47080. switch (returnData.taskType) {
  47081. case WorkerTaskType.INIT:
  47082. _this._init = true;
  47083. //Update the worked with ALL of the scene's current state
  47084. _this._scene.meshes.forEach(function (mesh) {
  47085. _this.onMeshAdded(mesh);
  47086. });
  47087. _this._scene.getGeometries().forEach(function (geometry) {
  47088. _this.onGeometryAdded(geometry);
  47089. });
  47090. break;
  47091. case WorkerTaskType.UPDATE:
  47092. _this._runningUpdated--;
  47093. break;
  47094. case WorkerTaskType.COLLIDE:
  47095. var returnPayload = returnData.payload;
  47096. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  47097. return;
  47098. var callback = _this._collisionsCallbackArray[returnPayload.collisionId];
  47099. if (callback) {
  47100. var mesh = _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId);
  47101. if (mesh) {
  47102. callback(returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), mesh);
  47103. }
  47104. }
  47105. //cleanup
  47106. _this._collisionsCallbackArray[returnPayload.collisionId] = null;
  47107. break;
  47108. }
  47109. };
  47110. this._collisionsCallbackArray = [];
  47111. this._init = false;
  47112. this._runningUpdated = 0;
  47113. this._addUpdateMeshesList = {};
  47114. this._addUpdateGeometriesList = {};
  47115. this._toRemoveGeometryArray = [];
  47116. this._toRemoveMeshesArray = [];
  47117. }
  47118. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  47119. if (!this._init)
  47120. return;
  47121. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  47122. return;
  47123. position.divideToRef(collider._radius, this._scaledPosition);
  47124. displacement.divideToRef(collider._radius, this._scaledVelocity);
  47125. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  47126. var payload = {
  47127. collider: {
  47128. position: this._scaledPosition.asArray(),
  47129. velocity: this._scaledVelocity.asArray(),
  47130. radius: collider._radius.asArray()
  47131. },
  47132. collisionId: collisionIndex,
  47133. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  47134. maximumRetry: maximumRetry
  47135. };
  47136. var message = {
  47137. payload: payload,
  47138. taskType: WorkerTaskType.COLLIDE
  47139. };
  47140. this._worker.postMessage(message);
  47141. };
  47142. CollisionCoordinatorWorker.prototype.init = function (scene) {
  47143. this._scene = scene;
  47144. this._scene.registerAfterRender(this._afterRender);
  47145. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  47146. this._worker = new Worker(workerUrl);
  47147. this._worker.onmessage = this._onMessageFromWorker;
  47148. var message = {
  47149. payload: {},
  47150. taskType: WorkerTaskType.INIT
  47151. };
  47152. this._worker.postMessage(message);
  47153. };
  47154. CollisionCoordinatorWorker.prototype.destroy = function () {
  47155. this._scene.unregisterAfterRender(this._afterRender);
  47156. this._worker.terminate();
  47157. };
  47158. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  47159. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  47160. this.onMeshUpdated(mesh);
  47161. };
  47162. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  47163. this._toRemoveMeshesArray.push(mesh.uniqueId);
  47164. };
  47165. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  47166. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  47167. geometry.onGeometryUpdated = this.onGeometryUpdated;
  47168. this.onGeometryUpdated(geometry);
  47169. };
  47170. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  47171. this._toRemoveGeometryArray.push(geometry.id);
  47172. };
  47173. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  47174. var submeshes = [];
  47175. if (mesh.subMeshes) {
  47176. submeshes = mesh.subMeshes.map(function (sm, idx) {
  47177. var boundingInfo = sm.getBoundingInfo();
  47178. return {
  47179. position: idx,
  47180. verticesStart: sm.verticesStart,
  47181. verticesCount: sm.verticesCount,
  47182. indexStart: sm.indexStart,
  47183. indexCount: sm.indexCount,
  47184. hasMaterial: !!sm.getMaterial(),
  47185. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  47186. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  47187. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  47188. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray()
  47189. };
  47190. });
  47191. }
  47192. var geometryId = null;
  47193. if (mesh instanceof BABYLON.Mesh) {
  47194. var geometry = mesh.geometry;
  47195. geometryId = geometry ? geometry.id : null;
  47196. }
  47197. else if (mesh instanceof BABYLON.InstancedMesh) {
  47198. var geometry = mesh.sourceMesh.geometry;
  47199. geometryId = geometry ? geometry.id : null;
  47200. }
  47201. var boundingInfo = mesh.getBoundingInfo();
  47202. return {
  47203. uniqueId: mesh.uniqueId,
  47204. id: mesh.id,
  47205. name: mesh.name,
  47206. geometryId: geometryId,
  47207. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  47208. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  47209. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  47210. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray(),
  47211. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  47212. subMeshes: submeshes,
  47213. checkCollisions: mesh.checkCollisions
  47214. };
  47215. };
  47216. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  47217. return {
  47218. id: geometry.id,
  47219. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  47220. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  47221. indices: new Uint32Array(geometry.getIndices() || []),
  47222. };
  47223. };
  47224. return CollisionCoordinatorWorker;
  47225. }());
  47226. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  47227. var CollisionCoordinatorLegacy = /** @class */ (function () {
  47228. function CollisionCoordinatorLegacy() {
  47229. this._scaledPosition = BABYLON.Vector3.Zero();
  47230. this._scaledVelocity = BABYLON.Vector3.Zero();
  47231. this._finalPosition = BABYLON.Vector3.Zero();
  47232. }
  47233. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  47234. position.divideToRef(collider._radius, this._scaledPosition);
  47235. displacement.divideToRef(collider._radius, this._scaledVelocity);
  47236. collider.collidedMesh = null;
  47237. collider._retry = 0;
  47238. collider._initialVelocity = this._scaledVelocity;
  47239. collider._initialPosition = this._scaledPosition;
  47240. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  47241. this._finalPosition.multiplyInPlace(collider._radius);
  47242. //run the callback
  47243. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  47244. };
  47245. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  47246. this._scene = scene;
  47247. };
  47248. CollisionCoordinatorLegacy.prototype.destroy = function () {
  47249. //Legacy need no destruction method.
  47250. };
  47251. //No update in legacy mode
  47252. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  47253. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  47254. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  47255. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  47256. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  47257. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  47258. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  47259. if (excludedMesh === void 0) { excludedMesh = null; }
  47260. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  47261. if (collider._retry >= maximumRetry) {
  47262. finalPosition.copyFrom(position);
  47263. return;
  47264. }
  47265. // Check if this is a mesh else camera or -1
  47266. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  47267. collider._initialize(position, velocity, closeDistance);
  47268. // Check all meshes
  47269. for (var index = 0; index < this._scene.meshes.length; index++) {
  47270. var mesh = this._scene.meshes[index];
  47271. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  47272. mesh._checkCollision(collider);
  47273. }
  47274. }
  47275. if (!collider.collisionFound) {
  47276. position.addToRef(velocity, finalPosition);
  47277. return;
  47278. }
  47279. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  47280. collider._getResponse(position, velocity);
  47281. }
  47282. if (velocity.length() <= closeDistance) {
  47283. finalPosition.copyFrom(position);
  47284. return;
  47285. }
  47286. collider._retry++;
  47287. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  47288. };
  47289. return CollisionCoordinatorLegacy;
  47290. }());
  47291. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  47292. })(BABYLON || (BABYLON = {}));
  47293. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  47294. var BABYLON;
  47295. (function (BABYLON) {
  47296. /**
  47297. * A particle represents one of the element emitted by a particle system.
  47298. * This is mainly define by its coordinates, direction, velocity and age.
  47299. */
  47300. var Particle = /** @class */ (function () {
  47301. /**
  47302. * Creates a new instance of @see Particle
  47303. * @param particleSystem the particle system the particle belongs to
  47304. */
  47305. function Particle(particleSystem) {
  47306. this.particleSystem = particleSystem;
  47307. /**
  47308. * The world position of the particle in the scene.
  47309. */
  47310. this.position = BABYLON.Vector3.Zero();
  47311. /**
  47312. * The world direction of the particle in the scene.
  47313. */
  47314. this.direction = BABYLON.Vector3.Zero();
  47315. /**
  47316. * The color of the particle.
  47317. */
  47318. this.color = new BABYLON.Color4(0, 0, 0, 0);
  47319. /**
  47320. * The color change of the particle per step.
  47321. */
  47322. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  47323. /**
  47324. * Defines how long will the life of the particle be.
  47325. */
  47326. this.lifeTime = 1.0;
  47327. /**
  47328. * The current age of the particle.
  47329. */
  47330. this.age = 0;
  47331. /**
  47332. * The current size of the particle.
  47333. */
  47334. this.size = 0;
  47335. /**
  47336. * The current angle of the particle.
  47337. */
  47338. this.angle = 0;
  47339. /**
  47340. * Defines how fast is the angle changing.
  47341. */
  47342. this.angularSpeed = 0;
  47343. /**
  47344. * Defines the cell index used by the particle to be rendered from a sprite.
  47345. */
  47346. this.cellIndex = 0;
  47347. this._currentFrameCounter = 0;
  47348. if (!this.particleSystem.isAnimationSheetEnabled) {
  47349. return;
  47350. }
  47351. this.cellIndex = this.particleSystem.startSpriteCellID;
  47352. if (this.particleSystem.spriteCellChangeSpeed == 0) {
  47353. this.updateCellIndex = this.updateCellIndexWithSpeedCalculated;
  47354. }
  47355. else {
  47356. this.updateCellIndex = this.updateCellIndexWithCustomSpeed;
  47357. }
  47358. }
  47359. Particle.prototype.updateCellIndexWithSpeedCalculated = function (scaledUpdateSpeed) {
  47360. // (ageOffset / scaledUpdateSpeed) / available cells
  47361. var numberOfScaledUpdatesPerCell = ((this.lifeTime - this.age) / scaledUpdateSpeed) / (this.particleSystem.endSpriteCellID + 1 - this.cellIndex);
  47362. this._currentFrameCounter += scaledUpdateSpeed;
  47363. if (this._currentFrameCounter >= numberOfScaledUpdatesPerCell * scaledUpdateSpeed) {
  47364. this._currentFrameCounter = 0;
  47365. this.cellIndex++;
  47366. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  47367. this.cellIndex = this.particleSystem.endSpriteCellID;
  47368. }
  47369. }
  47370. };
  47371. Particle.prototype.updateCellIndexWithCustomSpeed = function () {
  47372. if (this._currentFrameCounter >= this.particleSystem.spriteCellChangeSpeed) {
  47373. this.cellIndex++;
  47374. this._currentFrameCounter = 0;
  47375. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  47376. if (this.particleSystem.spriteCellLoop) {
  47377. this.cellIndex = this.particleSystem.startSpriteCellID;
  47378. }
  47379. else {
  47380. this.cellIndex = this.particleSystem.endSpriteCellID;
  47381. }
  47382. }
  47383. }
  47384. else {
  47385. this._currentFrameCounter++;
  47386. }
  47387. };
  47388. /**
  47389. * Copy the properties of particle to another one.
  47390. * @param other the particle to copy the information to.
  47391. */
  47392. Particle.prototype.copyTo = function (other) {
  47393. other.position.copyFrom(this.position);
  47394. other.direction.copyFrom(this.direction);
  47395. other.color.copyFrom(this.color);
  47396. other.colorStep.copyFrom(this.colorStep);
  47397. other.lifeTime = this.lifeTime;
  47398. other.age = this.age;
  47399. other.size = this.size;
  47400. other.angle = this.angle;
  47401. other.angularSpeed = this.angularSpeed;
  47402. other.particleSystem = this.particleSystem;
  47403. other.cellIndex = this.cellIndex;
  47404. };
  47405. return Particle;
  47406. }());
  47407. BABYLON.Particle = Particle;
  47408. })(BABYLON || (BABYLON = {}));
  47409. //# sourceMappingURL=babylon.particle.js.map
  47410. var BABYLON;
  47411. (function (BABYLON) {
  47412. /**
  47413. * This represents a particle system in Babylon.
  47414. * Particles are often small sprites used to simulate hard-to-reproduce phenomena like fire, smoke, water, or abstract visual effects like magic glitter and faery dust.
  47415. * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function.
  47416. * @example https://doc.babylonjs.com/babylon101/particles
  47417. */
  47418. var ParticleSystem = /** @class */ (function () {
  47419. /**
  47420. * Instantiates a particle system.
  47421. * Particles are often small sprites used to simulate hard-to-reproduce phenomena like fire, smoke, water, or abstract visual effects like magic glitter and faery dust.
  47422. * @param name The name of the particle system
  47423. * @param capacity The max number of particles alive at the same time
  47424. * @param scene The scene the particle system belongs to
  47425. * @param customEffect a custom effect used to change the way particles are rendered by default
  47426. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  47427. * @param epsilon Offset used to render the particles
  47428. */
  47429. function ParticleSystem(name, capacity, scene, customEffect, isAnimationSheetEnabled, epsilon) {
  47430. if (customEffect === void 0) { customEffect = null; }
  47431. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  47432. if (epsilon === void 0) { epsilon = 0.01; }
  47433. var _this = this;
  47434. /**
  47435. * List of animations used by the particle system.
  47436. */
  47437. this.animations = [];
  47438. /**
  47439. * The rendering group used by the Particle system to chose when to render.
  47440. */
  47441. this.renderingGroupId = 0;
  47442. /**
  47443. * The emitter represents the Mesh or position we are attaching the particle system to.
  47444. */
  47445. this.emitter = null;
  47446. /**
  47447. * The density of particles, the rate of particle flow
  47448. */
  47449. this.emitRate = 10;
  47450. /**
  47451. * If you want to launch only a few particles at once, that can be done, as well.
  47452. */
  47453. this.manualEmitCount = -1;
  47454. /**
  47455. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  47456. */
  47457. this.updateSpeed = 0.01;
  47458. /**
  47459. * The amount of time the particle system is running (depends of the overall speed above).
  47460. */
  47461. this.targetStopDuration = 0;
  47462. /**
  47463. * Specifies whether the particle system will be disposed once it reaches the end of the animation.
  47464. */
  47465. this.disposeOnStop = false;
  47466. /**
  47467. * Minimum power of emitting particles.
  47468. */
  47469. this.minEmitPower = 1;
  47470. /**
  47471. * Maximum power of emitting particles.
  47472. */
  47473. this.maxEmitPower = 1;
  47474. /**
  47475. * Minimum life time of emitting particles.
  47476. */
  47477. this.minLifeTime = 1;
  47478. /**
  47479. * Maximum life time of emitting particles.
  47480. */
  47481. this.maxLifeTime = 1;
  47482. /**
  47483. * Minimum Size of emitting particles.
  47484. */
  47485. this.minSize = 1;
  47486. /**
  47487. * Maximum Size of emitting particles.
  47488. */
  47489. this.maxSize = 1;
  47490. /**
  47491. * Minimum angular speed of emitting particles (Z-axis rotation for each particle).
  47492. */
  47493. this.minAngularSpeed = 0;
  47494. /**
  47495. * Maximum angular speed of emitting particles (Z-axis rotation for each particle).
  47496. */
  47497. this.maxAngularSpeed = 0;
  47498. /**
  47499. * The layer mask we are rendering the particles through.
  47500. */
  47501. this.layerMask = 0x0FFFFFFF;
  47502. /**
  47503. * This can help using your own shader to render the particle system.
  47504. * The according effect will be created
  47505. */
  47506. this.customShader = null;
  47507. /**
  47508. * By default particle system starts as soon as they are created. This prevents the
  47509. * automatic start to happen and let you decide when to start emitting particles.
  47510. */
  47511. this.preventAutoStart = false;
  47512. /**
  47513. * Callback triggered when the particle animation is ending.
  47514. */
  47515. this.onAnimationEnd = null;
  47516. /**
  47517. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  47518. */
  47519. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  47520. /**
  47521. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  47522. * to override the particles.
  47523. */
  47524. this.forceDepthWrite = false;
  47525. /**
  47526. * You can use gravity if you want to give an orientation to your particles.
  47527. */
  47528. this.gravity = BABYLON.Vector3.Zero();
  47529. /**
  47530. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  47531. */
  47532. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  47533. /**
  47534. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  47535. */
  47536. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  47537. /**
  47538. * Minimum box point around our emitter. Our emitter is the center of particles source, but if you want your particles to emit from more than one point, then you can tell it to do so.
  47539. */
  47540. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  47541. /**
  47542. * Maximum box point around our emitter. Our emitter is the center of particles source, but if you want your particles to emit from more than one point, then you can tell it to do so.
  47543. */
  47544. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  47545. /**
  47546. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  47547. */
  47548. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  47549. /**
  47550. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  47551. */
  47552. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  47553. /**
  47554. * Color the particle will have at the end of its lifetime.
  47555. */
  47556. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  47557. /**
  47558. * An optional mask to filter some colors out of the texture, or filter a part of the alpha channel.
  47559. */
  47560. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  47561. /**
  47562. * If using a spritesheet (isAnimationSheetEnabled), defines if the sprite animation should loop between startSpriteCellID and endSpriteCellID or not.
  47563. */
  47564. this.spriteCellLoop = true;
  47565. /**
  47566. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the speed of the sprite loop.
  47567. */
  47568. this.spriteCellChangeSpeed = 0;
  47569. /**
  47570. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the first sprite cell to display.
  47571. */
  47572. this.startSpriteCellID = 0;
  47573. /**
  47574. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the last sprite cell to display.
  47575. */
  47576. this.endSpriteCellID = 0;
  47577. /**
  47578. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell width to use.
  47579. */
  47580. this.spriteCellWidth = 0;
  47581. /**
  47582. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell height to use.
  47583. */
  47584. this.spriteCellHeight = 0;
  47585. /**
  47586. * An event triggered when the system is disposed.
  47587. */
  47588. this.onDisposeObservable = new BABYLON.Observable();
  47589. this._particles = new Array();
  47590. this._stockParticles = new Array();
  47591. this._newPartsExcess = 0;
  47592. this._vertexBuffers = {};
  47593. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  47594. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  47595. this._scaledDirection = BABYLON.Vector3.Zero();
  47596. this._scaledGravity = BABYLON.Vector3.Zero();
  47597. this._currentRenderId = -1;
  47598. this._started = false;
  47599. this._stopped = false;
  47600. this._actualFrame = 0;
  47601. this._vertexBufferSize = 11;
  47602. this._appendParticleVertexes = null;
  47603. this.id = name;
  47604. this.name = name;
  47605. this._capacity = capacity;
  47606. this._epsilon = epsilon;
  47607. this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  47608. if (isAnimationSheetEnabled) {
  47609. this._vertexBufferSize = 12;
  47610. }
  47611. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  47612. this._customEffect = customEffect;
  47613. scene.particleSystems.push(this);
  47614. this._createIndexBuffer();
  47615. // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY) + 1 filler
  47616. this._vertexData = new Float32Array(capacity * this._vertexBufferSize * 4);
  47617. this._vertexBuffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, this._vertexBufferSize);
  47618. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 3);
  47619. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 3, 4);
  47620. var options = this._vertexBuffer.createVertexBuffer("options", 7, 4);
  47621. if (this._isAnimationSheetEnabled) {
  47622. var cellIndexBuffer = this._vertexBuffer.createVertexBuffer("cellIndex", 11, 1);
  47623. this._vertexBuffers["cellIndex"] = cellIndexBuffer;
  47624. }
  47625. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  47626. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  47627. this._vertexBuffers["options"] = options;
  47628. // Default behaviors
  47629. this.particleEmitterType = new BABYLON.BoxParticleEmitter(this);
  47630. this.updateFunction = function (particles) {
  47631. for (var index = 0; index < particles.length; index++) {
  47632. var particle = particles[index];
  47633. particle.age += _this._scaledUpdateSpeed;
  47634. if (particle.age >= particle.lifeTime) {
  47635. _this.recycleParticle(particle);
  47636. index--;
  47637. continue;
  47638. }
  47639. else {
  47640. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  47641. particle.color.addInPlace(_this._scaledColorStep);
  47642. if (particle.color.a < 0)
  47643. particle.color.a = 0;
  47644. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  47645. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  47646. particle.position.addInPlace(_this._scaledDirection);
  47647. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  47648. particle.direction.addInPlace(_this._scaledGravity);
  47649. if (_this._isAnimationSheetEnabled) {
  47650. particle.updateCellIndex(_this._scaledUpdateSpeed);
  47651. }
  47652. }
  47653. }
  47654. };
  47655. }
  47656. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  47657. /**
  47658. * Sets a callback that will be triggered when the system is disposed.
  47659. */
  47660. set: function (callback) {
  47661. if (this._onDisposeObserver) {
  47662. this.onDisposeObservable.remove(this._onDisposeObserver);
  47663. }
  47664. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  47665. },
  47666. enumerable: true,
  47667. configurable: true
  47668. });
  47669. Object.defineProperty(ParticleSystem.prototype, "isAnimationSheetEnabled", {
  47670. /**
  47671. * Gets wether an animation sprite sheet is enabled or not on the particle system.
  47672. */
  47673. get: function () {
  47674. return this._isAnimationSheetEnabled;
  47675. },
  47676. enumerable: true,
  47677. configurable: true
  47678. });
  47679. ParticleSystem.prototype._createIndexBuffer = function () {
  47680. var indices = [];
  47681. var index = 0;
  47682. for (var count = 0; count < this._capacity; count++) {
  47683. indices.push(index);
  47684. indices.push(index + 1);
  47685. indices.push(index + 2);
  47686. indices.push(index);
  47687. indices.push(index + 2);
  47688. indices.push(index + 3);
  47689. index += 4;
  47690. }
  47691. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  47692. };
  47693. /**
  47694. * "Recycles" one of the particle by copying it back to the "stock" of particles and removing it from the active list.
  47695. * Its lifetime will start back at 0.
  47696. * @param particle The particle to recycle
  47697. */
  47698. ParticleSystem.prototype.recycleParticle = function (particle) {
  47699. var lastParticle = this._particles.pop();
  47700. if (lastParticle !== particle) {
  47701. lastParticle.copyTo(particle);
  47702. this._stockParticles.push(lastParticle);
  47703. }
  47704. };
  47705. /**
  47706. * Gets the maximum number of particles active at the same time.
  47707. * @returns The max number of active particles.
  47708. */
  47709. ParticleSystem.prototype.getCapacity = function () {
  47710. return this._capacity;
  47711. };
  47712. /**
  47713. * Gets Wether there are still active particles in the system.
  47714. * @returns True if it is alive, otherwise false.
  47715. */
  47716. ParticleSystem.prototype.isAlive = function () {
  47717. return this._alive;
  47718. };
  47719. /**
  47720. * Gets Wether the system has been started.
  47721. * @returns True if it has been started, otherwise false.
  47722. */
  47723. ParticleSystem.prototype.isStarted = function () {
  47724. return this._started;
  47725. };
  47726. /**
  47727. * Starts the particle system and begins to emit.
  47728. */
  47729. ParticleSystem.prototype.start = function () {
  47730. this._started = true;
  47731. this._stopped = false;
  47732. this._actualFrame = 0;
  47733. };
  47734. /**
  47735. * Stops the particle system.
  47736. */
  47737. ParticleSystem.prototype.stop = function () {
  47738. this._stopped = true;
  47739. };
  47740. /**
  47741. * @ignore (for internal use only)
  47742. */
  47743. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  47744. var offset = index * this._vertexBufferSize;
  47745. this._vertexData[offset] = particle.position.x;
  47746. this._vertexData[offset + 1] = particle.position.y;
  47747. this._vertexData[offset + 2] = particle.position.z;
  47748. this._vertexData[offset + 3] = particle.color.r;
  47749. this._vertexData[offset + 4] = particle.color.g;
  47750. this._vertexData[offset + 5] = particle.color.b;
  47751. this._vertexData[offset + 6] = particle.color.a;
  47752. this._vertexData[offset + 7] = particle.angle;
  47753. this._vertexData[offset + 8] = particle.size;
  47754. this._vertexData[offset + 9] = offsetX;
  47755. this._vertexData[offset + 10] = offsetY;
  47756. };
  47757. /**
  47758. * @ignore (for internal use only)
  47759. */
  47760. ParticleSystem.prototype._appendParticleVertexWithAnimation = function (index, particle, offsetX, offsetY) {
  47761. if (offsetX === 0)
  47762. offsetX = this._epsilon;
  47763. else if (offsetX === 1)
  47764. offsetX = 1 - this._epsilon;
  47765. if (offsetY === 0)
  47766. offsetY = this._epsilon;
  47767. else if (offsetY === 1)
  47768. offsetY = 1 - this._epsilon;
  47769. var offset = index * this._vertexBufferSize;
  47770. this._vertexData[offset] = particle.position.x;
  47771. this._vertexData[offset + 1] = particle.position.y;
  47772. this._vertexData[offset + 2] = particle.position.z;
  47773. this._vertexData[offset + 3] = particle.color.r;
  47774. this._vertexData[offset + 4] = particle.color.g;
  47775. this._vertexData[offset + 5] = particle.color.b;
  47776. this._vertexData[offset + 6] = particle.color.a;
  47777. this._vertexData[offset + 7] = particle.angle;
  47778. this._vertexData[offset + 8] = particle.size;
  47779. this._vertexData[offset + 9] = offsetX;
  47780. this._vertexData[offset + 10] = offsetY;
  47781. this._vertexData[offset + 11] = particle.cellIndex;
  47782. };
  47783. ParticleSystem.prototype._update = function (newParticles) {
  47784. // Update current
  47785. this._alive = this._particles.length > 0;
  47786. this.updateFunction(this._particles);
  47787. // Add new ones
  47788. var worldMatrix;
  47789. if (this.emitter.position) {
  47790. var emitterMesh = this.emitter;
  47791. worldMatrix = emitterMesh.getWorldMatrix();
  47792. }
  47793. else {
  47794. var emitterPosition = this.emitter;
  47795. worldMatrix = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  47796. }
  47797. var particle;
  47798. for (var index = 0; index < newParticles; index++) {
  47799. if (this._particles.length === this._capacity) {
  47800. break;
  47801. }
  47802. if (this._stockParticles.length !== 0) {
  47803. particle = this._stockParticles.pop();
  47804. particle.age = 0;
  47805. particle.cellIndex = this.startSpriteCellID;
  47806. }
  47807. else {
  47808. particle = new BABYLON.Particle(this);
  47809. }
  47810. this._particles.push(particle);
  47811. var emitPower = BABYLON.Scalar.RandomRange(this.minEmitPower, this.maxEmitPower);
  47812. if (this.startPositionFunction) {
  47813. this.startPositionFunction(worldMatrix, particle.position, particle);
  47814. }
  47815. else {
  47816. this.particleEmitterType.startPositionFunction(worldMatrix, particle.position, particle);
  47817. }
  47818. if (this.startDirectionFunction) {
  47819. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  47820. }
  47821. else {
  47822. this.particleEmitterType.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  47823. }
  47824. particle.lifeTime = BABYLON.Scalar.RandomRange(this.minLifeTime, this.maxLifeTime);
  47825. particle.size = BABYLON.Scalar.RandomRange(this.minSize, this.maxSize);
  47826. particle.angularSpeed = BABYLON.Scalar.RandomRange(this.minAngularSpeed, this.maxAngularSpeed);
  47827. var step = BABYLON.Scalar.RandomRange(0, 1.0);
  47828. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  47829. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  47830. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  47831. }
  47832. };
  47833. ParticleSystem.prototype._getEffect = function () {
  47834. if (this._customEffect) {
  47835. return this._customEffect;
  47836. }
  47837. ;
  47838. var defines = [];
  47839. if (this._scene.clipPlane) {
  47840. defines.push("#define CLIPPLANE");
  47841. }
  47842. if (this._isAnimationSheetEnabled) {
  47843. defines.push("#define ANIMATESHEET");
  47844. }
  47845. // Effect
  47846. var join = defines.join("\n");
  47847. if (this._cachedDefines !== join) {
  47848. this._cachedDefines = join;
  47849. var attributesNamesOrOptions;
  47850. var effectCreationOption;
  47851. if (this._isAnimationSheetEnabled) {
  47852. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options", "cellIndex"];
  47853. effectCreationOption = ["invView", "view", "projection", "particlesInfos", "vClipPlane", "textureMask"];
  47854. }
  47855. else {
  47856. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options"];
  47857. effectCreationOption = ["invView", "view", "projection", "vClipPlane", "textureMask"];
  47858. }
  47859. this._effect = this._scene.getEngine().createEffect("particles", attributesNamesOrOptions, effectCreationOption, ["diffuseSampler"], join);
  47860. }
  47861. return this._effect;
  47862. };
  47863. /**
  47864. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  47865. */
  47866. ParticleSystem.prototype.animate = function () {
  47867. if (!this._started)
  47868. return;
  47869. var effect = this._getEffect();
  47870. // Check
  47871. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  47872. return;
  47873. if (this._currentRenderId === this._scene.getRenderId()) {
  47874. return;
  47875. }
  47876. this._currentRenderId = this._scene.getRenderId();
  47877. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  47878. // determine the number of particles we need to create
  47879. var newParticles;
  47880. if (this.manualEmitCount > -1) {
  47881. newParticles = this.manualEmitCount;
  47882. this._newPartsExcess = 0;
  47883. this.manualEmitCount = 0;
  47884. }
  47885. else {
  47886. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  47887. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  47888. }
  47889. if (this._newPartsExcess > 1.0) {
  47890. newParticles += this._newPartsExcess >> 0;
  47891. this._newPartsExcess -= this._newPartsExcess >> 0;
  47892. }
  47893. this._alive = false;
  47894. if (!this._stopped) {
  47895. this._actualFrame += this._scaledUpdateSpeed;
  47896. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  47897. this.stop();
  47898. }
  47899. else {
  47900. newParticles = 0;
  47901. }
  47902. this._update(newParticles);
  47903. // Stopped?
  47904. if (this._stopped) {
  47905. if (!this._alive) {
  47906. this._started = false;
  47907. if (this.onAnimationEnd) {
  47908. this.onAnimationEnd();
  47909. }
  47910. if (this.disposeOnStop) {
  47911. this._scene._toBeDisposed.push(this);
  47912. }
  47913. }
  47914. }
  47915. // Animation sheet
  47916. if (this._isAnimationSheetEnabled) {
  47917. this._appendParticleVertexes = this._appenedParticleVertexesWithSheet;
  47918. }
  47919. else {
  47920. this._appendParticleVertexes = this._appenedParticleVertexesNoSheet;
  47921. }
  47922. // Update VBO
  47923. var offset = 0;
  47924. for (var index = 0; index < this._particles.length; index++) {
  47925. var particle = this._particles[index];
  47926. this._appendParticleVertexes(offset, particle);
  47927. offset += 4;
  47928. }
  47929. if (this._vertexBuffer) {
  47930. this._vertexBuffer.update(this._vertexData);
  47931. }
  47932. };
  47933. ParticleSystem.prototype._appenedParticleVertexesWithSheet = function (offset, particle) {
  47934. this._appendParticleVertexWithAnimation(offset++, particle, 0, 0);
  47935. this._appendParticleVertexWithAnimation(offset++, particle, 1, 0);
  47936. this._appendParticleVertexWithAnimation(offset++, particle, 1, 1);
  47937. this._appendParticleVertexWithAnimation(offset++, particle, 0, 1);
  47938. };
  47939. ParticleSystem.prototype._appenedParticleVertexesNoSheet = function (offset, particle) {
  47940. this._appendParticleVertex(offset++, particle, 0, 0);
  47941. this._appendParticleVertex(offset++, particle, 1, 0);
  47942. this._appendParticleVertex(offset++, particle, 1, 1);
  47943. this._appendParticleVertex(offset++, particle, 0, 1);
  47944. };
  47945. /**
  47946. * Rebuilds the particle system.
  47947. */
  47948. ParticleSystem.prototype.rebuild = function () {
  47949. this._createIndexBuffer();
  47950. if (this._vertexBuffer) {
  47951. this._vertexBuffer._rebuild();
  47952. }
  47953. };
  47954. /**
  47955. * Renders the particle system in its current state.
  47956. * @returns the current number of particles.
  47957. */
  47958. ParticleSystem.prototype.render = function () {
  47959. var effect = this._getEffect();
  47960. // Check
  47961. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this._particles.length)
  47962. return 0;
  47963. var engine = this._scene.getEngine();
  47964. // Render
  47965. engine.enableEffect(effect);
  47966. engine.setState(false);
  47967. var viewMatrix = this._scene.getViewMatrix();
  47968. effect.setTexture("diffuseSampler", this.particleTexture);
  47969. effect.setMatrix("view", viewMatrix);
  47970. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  47971. if (this._isAnimationSheetEnabled) {
  47972. var baseSize = this.particleTexture.getBaseSize();
  47973. effect.setFloat3("particlesInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  47974. }
  47975. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  47976. if (this._scene.clipPlane) {
  47977. var clipPlane = this._scene.clipPlane;
  47978. var invView = viewMatrix.clone();
  47979. invView.invert();
  47980. effect.setMatrix("invView", invView);
  47981. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  47982. }
  47983. // VBOs
  47984. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  47985. // Draw order
  47986. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  47987. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  47988. }
  47989. else {
  47990. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  47991. }
  47992. if (this.forceDepthWrite) {
  47993. engine.setDepthWrite(true);
  47994. }
  47995. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._particles.length * 6);
  47996. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  47997. return this._particles.length;
  47998. };
  47999. /**
  48000. * Disposes the particle system and free the associated resources.
  48001. */
  48002. ParticleSystem.prototype.dispose = function () {
  48003. if (this._vertexBuffer) {
  48004. this._vertexBuffer.dispose();
  48005. this._vertexBuffer = null;
  48006. }
  48007. if (this._indexBuffer) {
  48008. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  48009. this._indexBuffer = null;
  48010. }
  48011. if (this.particleTexture) {
  48012. this.particleTexture.dispose();
  48013. this.particleTexture = null;
  48014. }
  48015. // Remove from scene
  48016. var index = this._scene.particleSystems.indexOf(this);
  48017. if (index > -1) {
  48018. this._scene.particleSystems.splice(index, 1);
  48019. }
  48020. // Callback
  48021. this.onDisposeObservable.notifyObservers(this);
  48022. this.onDisposeObservable.clear();
  48023. };
  48024. /**
  48025. * Creates a Sphere Emitter for the particle system. (emits along the sphere radius)
  48026. * @param radius The radius of the sphere to emit from
  48027. * @returns the emitter
  48028. */
  48029. ParticleSystem.prototype.createSphereEmitter = function (radius) {
  48030. if (radius === void 0) { radius = 1; }
  48031. var particleEmitter = new BABYLON.SphereParticleEmitter(radius);
  48032. this.particleEmitterType = particleEmitter;
  48033. return particleEmitter;
  48034. };
  48035. /**
  48036. * Creates a Directed Sphere Emitter for the particle system. (emits between direction1 and direction2)
  48037. * @param radius The radius of the sphere to emit from
  48038. * @param direction1 Particles are emitted between the direction1 and direction2 from within the sphere
  48039. * @param direction2 Particles are emitted between the direction1 and direction2 from within the sphere
  48040. * @returns the emitter
  48041. */
  48042. ParticleSystem.prototype.createDirectedSphereEmitter = function (radius, direction1, direction2) {
  48043. if (radius === void 0) { radius = 1; }
  48044. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1.0, 0); }
  48045. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1.0, 0); }
  48046. var particleEmitter = new BABYLON.SphereDirectedParticleEmitter(radius, direction1, direction2);
  48047. this.particleEmitterType = particleEmitter;
  48048. return particleEmitter;
  48049. };
  48050. /**
  48051. * Creates a Cone Emitter for the particle system. (emits from the cone to the particle position)
  48052. * @param radius The radius of the cone to emit from
  48053. * @param angle The base angle of the cone
  48054. * @returns the emitter
  48055. */
  48056. ParticleSystem.prototype.createConeEmitter = function (radius, angle) {
  48057. if (radius === void 0) { radius = 1; }
  48058. if (angle === void 0) { angle = Math.PI / 4; }
  48059. var particleEmitter = new BABYLON.ConeParticleEmitter(radius, angle);
  48060. this.particleEmitterType = particleEmitter;
  48061. return particleEmitter;
  48062. };
  48063. // this method needs to be changed when breaking changes will be allowed to match the sphere and cone methods and properties direction1,2 and minEmitBox,maxEmitBox to be removed from the system.
  48064. /**
  48065. * Creates a Box Emitter for the particle system. (emits between direction1 and direction2 from withing the box defined by minEmitBox and maxEmitBox)
  48066. * @param direction1 Particles are emitted between the direction1 and direction2 from within the box
  48067. * @param direction2 Particles are emitted between the direction1 and direction2 from within the box
  48068. * @param minEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  48069. * @param maxEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  48070. * @returns the emitter
  48071. */
  48072. ParticleSystem.prototype.createBoxEmitter = function (direction1, direction2, minEmitBox, maxEmitBox) {
  48073. var particleEmitter = new BABYLON.BoxParticleEmitter(this);
  48074. this.direction1 = direction1;
  48075. this.direction2 = direction2;
  48076. this.minEmitBox = minEmitBox;
  48077. this.maxEmitBox = maxEmitBox;
  48078. this.particleEmitterType = particleEmitter;
  48079. return particleEmitter;
  48080. };
  48081. /**
  48082. * Clones the particle system.
  48083. * @param name The name of the cloned object
  48084. * @param newEmitter The new emitter to use
  48085. * @returns the cloned particle system
  48086. */
  48087. ParticleSystem.prototype.clone = function (name, newEmitter) {
  48088. var custom = null;
  48089. var program = null;
  48090. if (this.customShader != null) {
  48091. program = this.customShader;
  48092. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  48093. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  48094. }
  48095. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  48096. result.customShader = program;
  48097. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader"]);
  48098. if (newEmitter === undefined) {
  48099. newEmitter = this.emitter;
  48100. }
  48101. result.emitter = newEmitter;
  48102. if (this.particleTexture) {
  48103. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  48104. }
  48105. if (!this.preventAutoStart) {
  48106. result.start();
  48107. }
  48108. return result;
  48109. };
  48110. /**
  48111. * Serializes the particle system to a JSON object.
  48112. * @returns the JSON object
  48113. */
  48114. ParticleSystem.prototype.serialize = function () {
  48115. var serializationObject = {};
  48116. serializationObject.name = this.name;
  48117. serializationObject.id = this.id;
  48118. // Emitter
  48119. if (this.emitter.position) {
  48120. var emitterMesh = this.emitter;
  48121. serializationObject.emitterId = emitterMesh.id;
  48122. }
  48123. else {
  48124. var emitterPosition = this.emitter;
  48125. serializationObject.emitter = emitterPosition.asArray();
  48126. }
  48127. serializationObject.capacity = this.getCapacity();
  48128. if (this.particleTexture) {
  48129. serializationObject.textureName = this.particleTexture.name;
  48130. }
  48131. // Animations
  48132. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  48133. // Particle system
  48134. serializationObject.minAngularSpeed = this.minAngularSpeed;
  48135. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  48136. serializationObject.minSize = this.minSize;
  48137. serializationObject.maxSize = this.maxSize;
  48138. serializationObject.minEmitPower = this.minEmitPower;
  48139. serializationObject.maxEmitPower = this.maxEmitPower;
  48140. serializationObject.minLifeTime = this.minLifeTime;
  48141. serializationObject.maxLifeTime = this.maxLifeTime;
  48142. serializationObject.emitRate = this.emitRate;
  48143. serializationObject.minEmitBox = this.minEmitBox.asArray();
  48144. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  48145. serializationObject.gravity = this.gravity.asArray();
  48146. serializationObject.direction1 = this.direction1.asArray();
  48147. serializationObject.direction2 = this.direction2.asArray();
  48148. serializationObject.color1 = this.color1.asArray();
  48149. serializationObject.color2 = this.color2.asArray();
  48150. serializationObject.colorDead = this.colorDead.asArray();
  48151. serializationObject.updateSpeed = this.updateSpeed;
  48152. serializationObject.targetStopDuration = this.targetStopDuration;
  48153. serializationObject.textureMask = this.textureMask.asArray();
  48154. serializationObject.blendMode = this.blendMode;
  48155. serializationObject.customShader = this.customShader;
  48156. serializationObject.preventAutoStart = this.preventAutoStart;
  48157. serializationObject.startSpriteCellID = this.startSpriteCellID;
  48158. serializationObject.endSpriteCellID = this.endSpriteCellID;
  48159. serializationObject.spriteCellLoop = this.spriteCellLoop;
  48160. serializationObject.spriteCellChangeSpeed = this.spriteCellChangeSpeed;
  48161. serializationObject.spriteCellWidth = this.spriteCellWidth;
  48162. serializationObject.spriteCellHeight = this.spriteCellHeight;
  48163. serializationObject.isAnimationSheetEnabled = this._isAnimationSheetEnabled;
  48164. return serializationObject;
  48165. };
  48166. /**
  48167. * Parses a JSON object to create a particle system.
  48168. * @param parsedParticleSystem The JSON object to parse
  48169. * @param scene The scene to create the particle system in
  48170. * @param rootUrl The root url to use to load external dependencies like texture
  48171. * @returns the Parsed particle system
  48172. */
  48173. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  48174. var name = parsedParticleSystem.name;
  48175. var custom = null;
  48176. var program = null;
  48177. if (parsedParticleSystem.customShader) {
  48178. program = parsedParticleSystem.customShader;
  48179. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  48180. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  48181. }
  48182. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom, parsedParticleSystem.isAnimationSheetEnabled);
  48183. particleSystem.customShader = program;
  48184. if (parsedParticleSystem.id) {
  48185. particleSystem.id = parsedParticleSystem.id;
  48186. }
  48187. // Auto start
  48188. if (parsedParticleSystem.preventAutoStart) {
  48189. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  48190. }
  48191. // Texture
  48192. if (parsedParticleSystem.textureName) {
  48193. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  48194. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  48195. }
  48196. // Emitter
  48197. if (parsedParticleSystem.emitterId) {
  48198. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  48199. }
  48200. else {
  48201. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  48202. }
  48203. // Animations
  48204. if (parsedParticleSystem.animations) {
  48205. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  48206. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  48207. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  48208. }
  48209. }
  48210. if (parsedParticleSystem.autoAnimate) {
  48211. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  48212. }
  48213. // Particle system
  48214. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  48215. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  48216. particleSystem.minSize = parsedParticleSystem.minSize;
  48217. particleSystem.maxSize = parsedParticleSystem.maxSize;
  48218. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  48219. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  48220. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  48221. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  48222. particleSystem.emitRate = parsedParticleSystem.emitRate;
  48223. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  48224. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  48225. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  48226. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  48227. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  48228. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  48229. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  48230. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  48231. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  48232. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  48233. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  48234. particleSystem.blendMode = parsedParticleSystem.blendMode;
  48235. particleSystem.startSpriteCellID = parsedParticleSystem.startSpriteCellID;
  48236. particleSystem.endSpriteCellID = parsedParticleSystem.endSpriteCellID;
  48237. particleSystem.spriteCellLoop = parsedParticleSystem.spriteCellLoop;
  48238. particleSystem.spriteCellChangeSpeed = parsedParticleSystem.spriteCellChangeSpeed;
  48239. particleSystem.spriteCellWidth = parsedParticleSystem.spriteCellWidth;
  48240. particleSystem.spriteCellHeight = parsedParticleSystem.spriteCellHeight;
  48241. if (!particleSystem.preventAutoStart) {
  48242. particleSystem.start();
  48243. }
  48244. return particleSystem;
  48245. };
  48246. /**
  48247. * Source color is added to the destination color without alpha affecting the result.
  48248. */
  48249. ParticleSystem.BLENDMODE_ONEONE = 0;
  48250. /**
  48251. * Blend current color and particle color using particle’s alpha.
  48252. */
  48253. ParticleSystem.BLENDMODE_STANDARD = 1;
  48254. return ParticleSystem;
  48255. }());
  48256. BABYLON.ParticleSystem = ParticleSystem;
  48257. })(BABYLON || (BABYLON = {}));
  48258. //# sourceMappingURL=babylon.particleSystem.js.map
  48259. var BABYLON;
  48260. (function (BABYLON) {
  48261. /**
  48262. * Particle emitter emitting particles from the inside of a box.
  48263. * It emits the particles randomly between 2 given directions.
  48264. */
  48265. var BoxParticleEmitter = /** @class */ (function () {
  48266. // to be updated like the rest of emitters when breaking changes.
  48267. // all property should be come public variables and passed through constructor.
  48268. /**
  48269. * Creates a new instance of @see BoxParticleEmitter
  48270. * @param _particleSystem the particle system associated with the emitter
  48271. */
  48272. function BoxParticleEmitter(_particleSystem) {
  48273. this._particleSystem = _particleSystem;
  48274. }
  48275. Object.defineProperty(BoxParticleEmitter.prototype, "direction1", {
  48276. /**
  48277. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  48278. */
  48279. get: function () {
  48280. return this._particleSystem.direction1;
  48281. },
  48282. /**
  48283. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  48284. */
  48285. set: function (value) {
  48286. this._particleSystem.direction1 = value;
  48287. },
  48288. enumerable: true,
  48289. configurable: true
  48290. });
  48291. Object.defineProperty(BoxParticleEmitter.prototype, "direction2", {
  48292. /**
  48293. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  48294. */
  48295. get: function () {
  48296. return this._particleSystem.direction2;
  48297. },
  48298. /**
  48299. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  48300. */
  48301. set: function (value) {
  48302. this._particleSystem.direction2 = value;
  48303. },
  48304. enumerable: true,
  48305. configurable: true
  48306. });
  48307. Object.defineProperty(BoxParticleEmitter.prototype, "minEmitBox", {
  48308. /**
  48309. * Minimum box point around our emitter. Our emitter is the center of particles source, but if you want your particles to emit from more than one point, then you can tell it to do so.
  48310. */
  48311. get: function () {
  48312. return this._particleSystem.minEmitBox;
  48313. },
  48314. /**
  48315. * Minimum box point around our emitter. Our emitter is the center of particles source, but if you want your particles to emit from more than one point, then you can tell it to do so.
  48316. */
  48317. set: function (value) {
  48318. this._particleSystem.minEmitBox = value;
  48319. },
  48320. enumerable: true,
  48321. configurable: true
  48322. });
  48323. Object.defineProperty(BoxParticleEmitter.prototype, "maxEmitBox", {
  48324. /**
  48325. * Maximum box point around our emitter. Our emitter is the center of particles source, but if you want your particles to emit from more than one point, then you can tell it to do so.
  48326. */
  48327. get: function () {
  48328. return this._particleSystem.maxEmitBox;
  48329. },
  48330. /**
  48331. * Maximum box point around our emitter. Our emitter is the center of particles source, but if you want your particles to emit from more than one point, then you can tell it to do so.
  48332. */
  48333. set: function (value) {
  48334. this._particleSystem.maxEmitBox = value;
  48335. },
  48336. enumerable: true,
  48337. configurable: true
  48338. });
  48339. /**
  48340. * Called by the particle System when the direction is computed for the created particle.
  48341. * @param emitPower is the power of the particle (speed)
  48342. * @param worldMatrix is the world matrix of the particle system
  48343. * @param directionToUpdate is the direction vector to update with the result
  48344. * @param particle is the particle we are computed the direction for
  48345. */
  48346. BoxParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  48347. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  48348. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  48349. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  48350. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  48351. };
  48352. /**
  48353. * Called by the particle System when the position is computed for the created particle.
  48354. * @param worldMatrix is the world matrix of the particle system
  48355. * @param positionToUpdate is the position vector to update with the result
  48356. * @param particle is the particle we are computed the position for
  48357. */
  48358. BoxParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  48359. var randX = BABYLON.Scalar.RandomRange(this.minEmitBox.x, this.maxEmitBox.x);
  48360. var randY = BABYLON.Scalar.RandomRange(this.minEmitBox.y, this.maxEmitBox.y);
  48361. var randZ = BABYLON.Scalar.RandomRange(this.minEmitBox.z, this.maxEmitBox.z);
  48362. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  48363. };
  48364. /**
  48365. * Clones the current emitter and returns a copy of it
  48366. * @returns the new emitter
  48367. */
  48368. BoxParticleEmitter.prototype.clone = function () {
  48369. var newOne = new BoxParticleEmitter(this._particleSystem);
  48370. BABYLON.Tools.DeepCopy(this, newOne);
  48371. return newOne;
  48372. };
  48373. return BoxParticleEmitter;
  48374. }());
  48375. BABYLON.BoxParticleEmitter = BoxParticleEmitter;
  48376. })(BABYLON || (BABYLON = {}));
  48377. //# sourceMappingURL=babylon.boxParticleEmitter.js.map
  48378. var BABYLON;
  48379. (function (BABYLON) {
  48380. /**
  48381. * Particle emitter emitting particles from the inside of a cone.
  48382. * It emits the particles alongside the cone volume from the base to the particle.
  48383. * The emission direction might be randomized.
  48384. */
  48385. var ConeParticleEmitter = /** @class */ (function () {
  48386. /**
  48387. * Creates a new instance of @see ConeParticleEmitter
  48388. * @param radius the radius of the emission cone
  48389. * @param angles the cone base angle
  48390. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  48391. */
  48392. function ConeParticleEmitter(radius,
  48393. /**
  48394. * The radius of the emission cone.
  48395. */
  48396. angle,
  48397. /**
  48398. * The cone base angle.
  48399. */
  48400. directionRandomizer) {
  48401. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  48402. this.angle = angle;
  48403. this.directionRandomizer = directionRandomizer;
  48404. this.radius = radius;
  48405. }
  48406. Object.defineProperty(ConeParticleEmitter.prototype, "radius", {
  48407. /**
  48408. * Gets the radius of the emission cone.
  48409. */
  48410. get: function () {
  48411. return this._radius;
  48412. },
  48413. /**
  48414. * Sets the radius of the emission cone.
  48415. */
  48416. set: function (value) {
  48417. this._radius = value;
  48418. if (this.angle !== 0) {
  48419. this._height = value / Math.tan(this.angle / 2);
  48420. }
  48421. else {
  48422. this._height = 1;
  48423. }
  48424. },
  48425. enumerable: true,
  48426. configurable: true
  48427. });
  48428. /**
  48429. * Called by the particle System when the direction is computed for the created particle.
  48430. * @param emitPower is the power of the particle (speed)
  48431. * @param worldMatrix is the world matrix of the particle system
  48432. * @param directionToUpdate is the direction vector to update with the result
  48433. * @param particle is the particle we are computed the direction for
  48434. */
  48435. ConeParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  48436. if (this.angle === 0) {
  48437. BABYLON.Vector3.TransformNormalFromFloatsToRef(0, emitPower, 0, worldMatrix, directionToUpdate);
  48438. }
  48439. else {
  48440. // measure the direction Vector from the emitter to the particle.
  48441. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  48442. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  48443. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  48444. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  48445. direction.x += randX;
  48446. direction.y += randY;
  48447. direction.z += randZ;
  48448. direction.normalize();
  48449. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x * emitPower, direction.y * emitPower, direction.z * emitPower, worldMatrix, directionToUpdate);
  48450. }
  48451. };
  48452. /**
  48453. * Called by the particle System when the position is computed for the created particle.
  48454. * @param worldMatrix is the world matrix of the particle system
  48455. * @param positionToUpdate is the position vector to update with the result
  48456. * @param particle is the particle we are computed the position for
  48457. */
  48458. ConeParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  48459. var s = BABYLON.Scalar.RandomRange(0, Math.PI * 2);
  48460. var h = BABYLON.Scalar.RandomRange(0, 1);
  48461. // Better distribution in a cone at normal angles.
  48462. h = 1 - h * h;
  48463. var radius = BABYLON.Scalar.RandomRange(0, this._radius);
  48464. radius = radius * h / this._height;
  48465. var randX = radius * Math.sin(s);
  48466. var randZ = radius * Math.cos(s);
  48467. var randY = h;
  48468. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  48469. };
  48470. /**
  48471. * Clones the current emitter and returns a copy of it
  48472. * @returns the new emitter
  48473. */
  48474. ConeParticleEmitter.prototype.clone = function () {
  48475. var newOne = new ConeParticleEmitter(this.radius, this.angle, this.directionRandomizer);
  48476. BABYLON.Tools.DeepCopy(this, newOne);
  48477. return newOne;
  48478. };
  48479. return ConeParticleEmitter;
  48480. }());
  48481. BABYLON.ConeParticleEmitter = ConeParticleEmitter;
  48482. })(BABYLON || (BABYLON = {}));
  48483. //# sourceMappingURL=babylon.coneParticleEmitter.js.map
  48484. var BABYLON;
  48485. (function (BABYLON) {
  48486. /**
  48487. * Particle emitter emitting particles from the inside of a sphere.
  48488. * It emits the particles alongside the sphere radius. The emission direction might be randomized.
  48489. */
  48490. var SphereParticleEmitter = /** @class */ (function () {
  48491. /**
  48492. * Creates a new instance of @see SphereParticleEmitter
  48493. * @param radius the radius of the emission sphere
  48494. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  48495. */
  48496. function SphereParticleEmitter(
  48497. /**
  48498. * The radius of the emission sphere.
  48499. */
  48500. radius,
  48501. /**
  48502. * How much to randomize the particle direction [0-1].
  48503. */
  48504. directionRandomizer) {
  48505. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  48506. this.radius = radius;
  48507. this.directionRandomizer = directionRandomizer;
  48508. }
  48509. /**
  48510. * Called by the particle System when the direction is computed for the created particle.
  48511. * @param emitPower is the power of the particle (speed)
  48512. * @param worldMatrix is the world matrix of the particle system
  48513. * @param directionToUpdate is the direction vector to update with the result
  48514. * @param particle is the particle we are computed the direction for
  48515. */
  48516. SphereParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  48517. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  48518. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  48519. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  48520. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  48521. direction.x += randX;
  48522. direction.y += randY;
  48523. direction.z += randZ;
  48524. direction.normalize();
  48525. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x * emitPower, direction.y * emitPower, direction.z * emitPower, worldMatrix, directionToUpdate);
  48526. };
  48527. /**
  48528. * Called by the particle System when the position is computed for the created particle.
  48529. * @param worldMatrix is the world matrix of the particle system
  48530. * @param positionToUpdate is the position vector to update with the result
  48531. * @param particle is the particle we are computed the position for
  48532. */
  48533. SphereParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  48534. var phi = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  48535. var theta = BABYLON.Scalar.RandomRange(0, Math.PI);
  48536. var randX = this.radius * Math.cos(phi) * Math.sin(theta);
  48537. var randY = this.radius * Math.cos(theta);
  48538. var randZ = this.radius * Math.sin(phi) * Math.sin(theta);
  48539. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  48540. };
  48541. /**
  48542. * Clones the current emitter and returns a copy of it
  48543. * @returns the new emitter
  48544. */
  48545. SphereParticleEmitter.prototype.clone = function () {
  48546. var newOne = new SphereParticleEmitter(this.radius, this.directionRandomizer);
  48547. BABYLON.Tools.DeepCopy(this, newOne);
  48548. return newOne;
  48549. };
  48550. return SphereParticleEmitter;
  48551. }());
  48552. BABYLON.SphereParticleEmitter = SphereParticleEmitter;
  48553. /**
  48554. * Particle emitter emitting particles from the inside of a sphere.
  48555. * It emits the particles randomly between two vectors.
  48556. */
  48557. var SphereDirectedParticleEmitter = /** @class */ (function (_super) {
  48558. __extends(SphereDirectedParticleEmitter, _super);
  48559. /**
  48560. * Creates a new instance of @see SphereDirectedParticleEmitter
  48561. * @param radius the radius of the emission sphere
  48562. * @param direction1 the min limit of the emission direction
  48563. * @param direction2 the max limit of the emission direction
  48564. */
  48565. function SphereDirectedParticleEmitter(radius,
  48566. /**
  48567. * The min limit of the emission direction.
  48568. */
  48569. direction1,
  48570. /**
  48571. * The max limit of the emission direction.
  48572. */
  48573. direction2) {
  48574. var _this = _super.call(this, radius) || this;
  48575. _this.direction1 = direction1;
  48576. _this.direction2 = direction2;
  48577. return _this;
  48578. }
  48579. /**
  48580. * Called by the particle System when the direction is computed for the created particle.
  48581. * @param emitPower is the power of the particle (speed)
  48582. * @param worldMatrix is the world matrix of the particle system
  48583. * @param directionToUpdate is the direction vector to update with the result
  48584. * @param particle is the particle we are computed the direction for
  48585. */
  48586. SphereDirectedParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  48587. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  48588. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  48589. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  48590. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  48591. };
  48592. /**
  48593. * Clones the current emitter and returns a copy of it
  48594. * @returns the new emitter
  48595. */
  48596. SphereDirectedParticleEmitter.prototype.clone = function () {
  48597. var newOne = new SphereDirectedParticleEmitter(this.radius, this.direction1, this.direction2);
  48598. BABYLON.Tools.DeepCopy(this, newOne);
  48599. return newOne;
  48600. };
  48601. return SphereDirectedParticleEmitter;
  48602. }(SphereParticleEmitter));
  48603. BABYLON.SphereDirectedParticleEmitter = SphereDirectedParticleEmitter;
  48604. })(BABYLON || (BABYLON = {}));
  48605. //# sourceMappingURL=babylon.sphereParticleEmitter.js.map
  48606. //# sourceMappingURL=babylon.IParticleEmitterType.js.map
  48607. var BABYLON;
  48608. (function (BABYLON) {
  48609. /**
  48610. * This represents a GPU particle system in Babylon.
  48611. * This os the fastest particle system in Babylon as it uses the GPU to update the individual particle data.
  48612. */
  48613. var GPUParticleSystem = /** @class */ (function () {
  48614. /**
  48615. * Instantiates a GPU particle system.
  48616. * Particles are often small sprites used to simulate hard-to-reproduce phenomena like fire, smoke, water, or abstract visual effects like magic glitter and faery dust.
  48617. * @param name The name of the particle system
  48618. * @param capacity The max number of particles alive at the same time
  48619. * @param scene The scene the particle system belongs to
  48620. */
  48621. function GPUParticleSystem(name, capacity, scene) {
  48622. /**
  48623. * The emitter represents the Mesh or position we are attaching the particle system to.
  48624. */
  48625. this.emitter = null;
  48626. /**
  48627. * The rendering group used by the Particle system to chose when to render.
  48628. */
  48629. this.renderingGroupId = 0;
  48630. /**
  48631. * The layer mask we are rendering the particles through.
  48632. */
  48633. this.layerMask = 0x0FFFFFFF; // TODO
  48634. this._updateVertexBuffers = {};
  48635. this._renderVertexBuffers = {};
  48636. this._currentRenderId = -1;
  48637. this._started = true;
  48638. /**
  48639. * An event triggered when the system is disposed.
  48640. */
  48641. this.onDisposeObservable = new BABYLON.Observable();
  48642. this.id = name;
  48643. this.name = name;
  48644. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  48645. this._capacity = capacity;
  48646. this._engine = this._scene.getEngine();
  48647. this._scene.particleSystems.push(this);
  48648. this._renderEffect = new BABYLON.Effect("gpuRenderParticles", ["position", "age", "life", "velocity"], [], [], this._scene.getEngine());
  48649. var updateEffectOptions = {
  48650. attributes: ["position", "age", "life", "velocity"],
  48651. uniformsNames: [],
  48652. uniformBuffersNames: [],
  48653. samplers: [],
  48654. defines: "",
  48655. fallbacks: null,
  48656. onCompiled: null,
  48657. onError: null,
  48658. indexParameters: null,
  48659. maxSimultaneousLights: 0,
  48660. transformFeedbackVaryings: ["outPosition", "outAge", "outLife", "outVelocity"]
  48661. };
  48662. this._updateEffect = new BABYLON.Effect("gpuUpdateParticles", updateEffectOptions, this._scene.getEngine());
  48663. }
  48664. /**
  48665. * Gets Wether the system has been started.
  48666. * @returns True if it has been started, otherwise false.
  48667. */
  48668. GPUParticleSystem.prototype.isStarted = function () {
  48669. return this._started;
  48670. };
  48671. /**
  48672. * Starts the particle system and begins to emit.
  48673. */
  48674. GPUParticleSystem.prototype.start = function () {
  48675. this._started = true;
  48676. };
  48677. /**
  48678. * Stops the particle system.
  48679. */
  48680. GPUParticleSystem.prototype.stop = function () {
  48681. this._started = false;
  48682. };
  48683. /**
  48684. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  48685. */
  48686. GPUParticleSystem.prototype.animate = function () {
  48687. // Do nothing
  48688. };
  48689. GPUParticleSystem.prototype._initialize = function () {
  48690. if (this._renderVAO) {
  48691. return;
  48692. }
  48693. var data = new Array();
  48694. for (var particleIndex = 0; particleIndex < this._capacity; particleIndex++) {
  48695. // position
  48696. data.push(0.0);
  48697. data.push(0.0);
  48698. data.push(0.0);
  48699. var life = 1 + Math.random() * 10; // TODO: var
  48700. data.push(life + 1); // create the particle as a dead one to create a new one at start
  48701. data.push(life);
  48702. // velocity
  48703. data.push(0.0);
  48704. data.push(0.0);
  48705. data.push(0.0);
  48706. }
  48707. // Update VAO
  48708. this._updateBuffer = new BABYLON.Buffer(this._scene.getEngine(), data, false, 0);
  48709. this._updateVertexBuffers["position"] = this._updateBuffer.createVertexBuffer("position", 0, 3, 3);
  48710. this._updateVertexBuffers["age"] = this._updateBuffer.createVertexBuffer("age", 3, 1, 1);
  48711. this._updateVertexBuffers["life"] = this._updateBuffer.createVertexBuffer("life", 4, 1, 1);
  48712. this._updateVertexBuffers["velocity"] = this._updateBuffer.createVertexBuffer("velocity", 5, 3, 3);
  48713. this._updateVAO = this._engine.recordVertexArrayObject(this._updateVertexBuffers, null, this._updateEffect);
  48714. this._engine.bindArrayBuffer(null);
  48715. // Render VAO
  48716. this._renderBuffer = new BABYLON.Buffer(this._scene.getEngine(), data, false, 0);
  48717. this._renderVertexBuffers["position"] = this._renderBuffer.createVertexBuffer("position", 0, 3, 3);
  48718. this._renderVertexBuffers["age"] = this._renderBuffer.createVertexBuffer("age", 3, 1, 1);
  48719. this._renderVertexBuffers["life"] = this._renderBuffer.createVertexBuffer("life", 4, 1, 1);
  48720. this._renderVertexBuffers["velocity"] = this._renderBuffer.createVertexBuffer("velocity", 5, 3, 3);
  48721. this._renderVAO = this._engine.recordVertexArrayObject(this._renderVertexBuffers, null, this._renderEffect);
  48722. this._engine.bindArrayBuffer(null);
  48723. // Links
  48724. this._sourceVAO = this._updateVAO;
  48725. this._targetVAO = this._renderVAO;
  48726. this._sourceBuffer = this._updateBuffer;
  48727. this._targetBuffer = this._renderBuffer;
  48728. };
  48729. /**
  48730. * Renders the particle system in its current state.
  48731. * @returns the current number of particles.
  48732. */
  48733. GPUParticleSystem.prototype.render = function () {
  48734. if (!this.emitter || !this._updateEffect.isReady() || !this._renderEffect.isReady()) {
  48735. return 0;
  48736. }
  48737. // Get everything ready to render
  48738. this._initialize();
  48739. if (this._currentRenderId === this._scene.getRenderId()) {
  48740. return 0;
  48741. }
  48742. this._currentRenderId = this._scene.getRenderId();
  48743. // Enable update effect
  48744. this._engine.enableEffect(this._updateEffect);
  48745. this._engine.setState(false);
  48746. // Bind source VAO
  48747. this._engine.bindVertexArrayObject(this._sourceVAO, null);
  48748. // Update
  48749. this._engine.bindTransformFeedbackBuffer(this._targetBuffer.getBuffer());
  48750. this._engine.setRasterizerState(false);
  48751. this._engine.beginTransformFeedback();
  48752. this._engine.drawArraysType(BABYLON.Material.PointListDrawMode, 0, this._capacity);
  48753. this._engine.endTransformFeedback();
  48754. this._engine.setRasterizerState(true);
  48755. this._engine.bindTransformFeedbackBuffer(null);
  48756. // Enable render effect
  48757. this._engine.enableEffect(this._renderEffect);
  48758. // Bind source VAO
  48759. this._engine.bindVertexArrayObject(this._targetVAO, null);
  48760. // Render
  48761. this._engine.drawArraysType(BABYLON.Material.PointListDrawMode, 0, this._capacity);
  48762. // Switch VAOs
  48763. var tmpVAO = this._sourceVAO;
  48764. this._sourceVAO = this._targetVAO;
  48765. this._targetVAO = tmpVAO;
  48766. // Switch buffers
  48767. var tmpBuffer = this._sourceBuffer;
  48768. this._sourceBuffer = this._targetBuffer;
  48769. this._targetBuffer = tmpBuffer;
  48770. return 0;
  48771. };
  48772. /**
  48773. * Rebuilds the particle system
  48774. */
  48775. GPUParticleSystem.prototype.rebuild = function () {
  48776. };
  48777. /**
  48778. * Disposes the particle system and free the associated resources.
  48779. */
  48780. GPUParticleSystem.prototype.dispose = function () {
  48781. var index = this._scene.particleSystems.indexOf(this);
  48782. if (index > -1) {
  48783. this._scene.particleSystems.splice(index, 1);
  48784. }
  48785. //TODO: this._dataBuffer.dispose();
  48786. // Callback
  48787. this.onDisposeObservable.notifyObservers(this);
  48788. this.onDisposeObservable.clear();
  48789. };
  48790. //TODO: Clone / Parse / serialize
  48791. /**
  48792. * Clones the particle system.
  48793. * @param name The name of the cloned object
  48794. * @param newEmitter The new emitter to use
  48795. * @returns the cloned particle system
  48796. */
  48797. GPUParticleSystem.prototype.clone = function (name, newEmitter) {
  48798. return null;
  48799. };
  48800. /**
  48801. * Serializes the particle system to a JSON object.
  48802. * @returns the JSON object
  48803. */
  48804. GPUParticleSystem.prototype.serialize = function () {
  48805. };
  48806. return GPUParticleSystem;
  48807. }());
  48808. BABYLON.GPUParticleSystem = GPUParticleSystem;
  48809. })(BABYLON || (BABYLON = {}));
  48810. //# sourceMappingURL=babylon.gpuParticleSystem.js.map
  48811. var BABYLON;
  48812. (function (BABYLON) {
  48813. /**
  48814. * Represents one particle of a solid particle system.
  48815. * @see SolidParticleSystem
  48816. */
  48817. var SolidParticle = /** @class */ (function () {
  48818. /**
  48819. * Creates a Solid Particle object.
  48820. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  48821. * @param particleIndex (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  48822. * @param positionIndex (integer) is the starting index of the particle vertices in the SPS "positions" array.
  48823. * @param indiceIndex (integer) is the starting index of the particle indices in the SPS "indices" array.
  48824. * @param model (ModelShape) is a reference to the model shape on what the particle is designed.
  48825. * @param shapeId (integer) is the model shape identifier in the SPS.
  48826. * @param idxInShape (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  48827. * @param modelBoundingInfo is the reference to the model BoundingInfo used for intersection computations.
  48828. */
  48829. function SolidParticle(particleIndex, positionIndex, indiceIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  48830. if (modelBoundingInfo === void 0) { modelBoundingInfo = null; }
  48831. /**
  48832. * particle global index
  48833. */
  48834. this.idx = 0;
  48835. /**
  48836. * The color of the particle
  48837. */
  48838. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  48839. /**
  48840. * The world space position of the particle.
  48841. */
  48842. this.position = BABYLON.Vector3.Zero();
  48843. /**
  48844. * The world space rotation of the particle. (Not use if rotationQuaternion is set)
  48845. */
  48846. this.rotation = BABYLON.Vector3.Zero();
  48847. /**
  48848. * The scaling of the particle.
  48849. */
  48850. this.scaling = BABYLON.Vector3.One();
  48851. /**
  48852. * The uvs of the particle.
  48853. */
  48854. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  48855. /**
  48856. * The current speed of the particle.
  48857. */
  48858. this.velocity = BABYLON.Vector3.Zero();
  48859. /**
  48860. * The pivot point in the particle local space.
  48861. */
  48862. this.pivot = BABYLON.Vector3.Zero();
  48863. /**
  48864. * Is the particle active or not ?
  48865. */
  48866. this.alive = true;
  48867. /**
  48868. * Is the particle visible or not ?
  48869. */
  48870. this.isVisible = true;
  48871. /**
  48872. * Index of this particle in the global "positions" array (Internal use)
  48873. */
  48874. this._pos = 0;
  48875. /**
  48876. * Index of this particle in the global "indices" array (Internal use)
  48877. */
  48878. this._ind = 0;
  48879. /**
  48880. * ModelShape id of this particle
  48881. */
  48882. this.shapeId = 0;
  48883. /**
  48884. * Index of the particle in its shape id (Internal use)
  48885. */
  48886. this.idxInShape = 0;
  48887. /**
  48888. * Still set as invisible in order to skip useless computations (Internal use)
  48889. */
  48890. this._stillInvisible = false;
  48891. this.idx = particleIndex;
  48892. this._pos = positionIndex;
  48893. this._ind = indiceIndex;
  48894. this._model = model;
  48895. this.shapeId = shapeId;
  48896. this.idxInShape = idxInShape;
  48897. this._sps = sps;
  48898. if (modelBoundingInfo) {
  48899. this._modelBoundingInfo = modelBoundingInfo;
  48900. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  48901. }
  48902. }
  48903. Object.defineProperty(SolidParticle.prototype, "scale", {
  48904. /**
  48905. * Legacy support, changed scale to scaling
  48906. */
  48907. get: function () {
  48908. return this.scaling;
  48909. },
  48910. /**
  48911. * Legacy support, changed scale to scaling
  48912. */
  48913. set: function (scale) {
  48914. this.scaling = scale;
  48915. },
  48916. enumerable: true,
  48917. configurable: true
  48918. });
  48919. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  48920. /**
  48921. * Legacy support, changed quaternion to rotationQuaternion
  48922. */
  48923. get: function () {
  48924. return this.rotationQuaternion;
  48925. },
  48926. /**
  48927. * Legacy support, changed quaternion to rotationQuaternion
  48928. */
  48929. set: function (q) {
  48930. this.rotationQuaternion = q;
  48931. },
  48932. enumerable: true,
  48933. configurable: true
  48934. });
  48935. /**
  48936. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  48937. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  48938. * @param target is the object (solid particle or mesh) what the intersection is computed against.
  48939. * @returns true if it intersects
  48940. */
  48941. SolidParticle.prototype.intersectsMesh = function (target) {
  48942. if (!this._boundingInfo || !target._boundingInfo) {
  48943. return false;
  48944. }
  48945. if (this._sps._bSphereOnly) {
  48946. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  48947. }
  48948. return this._boundingInfo.intersects(target._boundingInfo, false);
  48949. };
  48950. return SolidParticle;
  48951. }());
  48952. BABYLON.SolidParticle = SolidParticle;
  48953. /**
  48954. * Represents the shape of the model used by one particle of a solid particle system.
  48955. * SPS internal tool, don't use it manually.
  48956. * @see SolidParticleSystem
  48957. */
  48958. var ModelShape = /** @class */ (function () {
  48959. /**
  48960. * 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.
  48961. * SPS internal tool, don't use it manually.
  48962. * @ignore
  48963. */
  48964. function ModelShape(id, shape, indicesLength, shapeUV, posFunction, vtxFunction) {
  48965. /**
  48966. * length of the shape in the model indices array (internal use)
  48967. */
  48968. this._indicesLength = 0;
  48969. this.shapeID = id;
  48970. this._shape = shape;
  48971. this._indicesLength = indicesLength;
  48972. this._shapeUV = shapeUV;
  48973. this._positionFunction = posFunction;
  48974. this._vertexFunction = vtxFunction;
  48975. }
  48976. return ModelShape;
  48977. }());
  48978. BABYLON.ModelShape = ModelShape;
  48979. /**
  48980. * Represents a Depth Sorted Particle in the solid particle system.
  48981. * @see SolidParticleSystem
  48982. */
  48983. var DepthSortedParticle = /** @class */ (function () {
  48984. function DepthSortedParticle() {
  48985. /**
  48986. * Index of the particle in the "indices" array
  48987. */
  48988. this.ind = 0;
  48989. /**
  48990. * Length of the particle shape in the "indices" array
  48991. */
  48992. this.indicesLength = 0;
  48993. /**
  48994. * Squared distance from the particle to the camera
  48995. */
  48996. this.sqDistance = 0.0;
  48997. }
  48998. return DepthSortedParticle;
  48999. }());
  49000. BABYLON.DepthSortedParticle = DepthSortedParticle;
  49001. })(BABYLON || (BABYLON = {}));
  49002. //# sourceMappingURL=babylon.solidParticle.js.map
  49003. var BABYLON;
  49004. (function (BABYLON) {
  49005. /**
  49006. * The SPS is a single updatable mesh. The solid particles are simply separate parts or faces fo this big mesh.
  49007. *As it is just a mesh, the SPS has all the same properties than any other BJS mesh : not more, not less. It can be scaled, rotated, translated, enlighted, textured, moved, etc.
  49008. * The SPS is also a particle system. It provides some methods to manage the particles.
  49009. * However it is behavior agnostic. This means it has no emitter, no particle physics, no particle recycler. You have to implement your own behavior.
  49010. *
  49011. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  49012. */
  49013. var SolidParticleSystem = /** @class */ (function () {
  49014. /**
  49015. * Creates a SPS (Solid Particle System) object.
  49016. * @param name (String) is the SPS name, this will be the underlying mesh name.
  49017. * @param scene (Scene) is the scene in which the SPS is added.
  49018. * @param updatable (optional boolean, default true) : if the SPS must be updatable or immutable.
  49019. * @param isPickable (optional boolean, default false) : if the solid particles must be pickable.
  49020. * @param enableDepthSort (optional boolean, default false) : if the solid particles must be sorted in the geometry according to their distance to the camera.
  49021. * @param particleIntersection (optional boolean, default false) : if the solid particle intersections must be computed.
  49022. * @param boundingSphereOnly (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  49023. * @param bSphereRadiusFactor (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  49024. * @example bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  49025. */
  49026. function SolidParticleSystem(name, scene, options) {
  49027. /**
  49028. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  49029. * Example : var p = SPS.particles[i];
  49030. */
  49031. this.particles = new Array();
  49032. /**
  49033. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  49034. */
  49035. this.nbParticles = 0;
  49036. /**
  49037. * If the particles must ever face the camera (default false). Useful for planar particles.
  49038. */
  49039. this.billboard = false;
  49040. /**
  49041. * Recompute normals when adding a shape
  49042. */
  49043. this.recomputeNormals = true;
  49044. /**
  49045. * This a counter ofr your own usage. It's not set by any SPS functions.
  49046. */
  49047. this.counter = 0;
  49048. /**
  49049. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  49050. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  49051. */
  49052. this.vars = {};
  49053. /**
  49054. * If the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster). (Internal use only)
  49055. */
  49056. this._bSphereOnly = false;
  49057. /**
  49058. * A number to multiply the boundind sphere radius by in order to reduce it for instance. (Internal use only)
  49059. */
  49060. this._bSphereRadiusFactor = 1.0;
  49061. this._positions = new Array();
  49062. this._indices = new Array();
  49063. this._normals = new Array();
  49064. this._colors = new Array();
  49065. this._uvs = new Array();
  49066. this._index = 0; // indices index
  49067. this._updatable = true;
  49068. this._pickable = false;
  49069. this._isVisibilityBoxLocked = false;
  49070. this._alwaysVisible = false;
  49071. this._depthSort = false;
  49072. this._shapeCounter = 0;
  49073. this._copy = new BABYLON.SolidParticle(0, 0, 0, null, 0, 0, this);
  49074. this._color = new BABYLON.Color4(0, 0, 0, 0);
  49075. this._computeParticleColor = true;
  49076. this._computeParticleTexture = true;
  49077. this._computeParticleRotation = true;
  49078. this._computeParticleVertex = false;
  49079. this._computeBoundingBox = false;
  49080. this._depthSortParticles = true;
  49081. this._cam_axisZ = BABYLON.Vector3.Zero();
  49082. this._cam_axisY = BABYLON.Vector3.Zero();
  49083. this._cam_axisX = BABYLON.Vector3.Zero();
  49084. this._axisZ = BABYLON.Axis.Z;
  49085. this._camDir = BABYLON.Vector3.Zero();
  49086. this._camInvertedPosition = BABYLON.Vector3.Zero();
  49087. this._rotMatrix = new BABYLON.Matrix();
  49088. this._invertMatrix = new BABYLON.Matrix();
  49089. this._rotated = BABYLON.Vector3.Zero();
  49090. this._quaternion = new BABYLON.Quaternion();
  49091. this._vertex = BABYLON.Vector3.Zero();
  49092. this._normal = BABYLON.Vector3.Zero();
  49093. this._yaw = 0.0;
  49094. this._pitch = 0.0;
  49095. this._roll = 0.0;
  49096. this._halfroll = 0.0;
  49097. this._halfpitch = 0.0;
  49098. this._halfyaw = 0.0;
  49099. this._sinRoll = 0.0;
  49100. this._cosRoll = 0.0;
  49101. this._sinPitch = 0.0;
  49102. this._cosPitch = 0.0;
  49103. this._sinYaw = 0.0;
  49104. this._cosYaw = 0.0;
  49105. this._mustUnrotateFixedNormals = false;
  49106. this._minimum = BABYLON.Tmp.Vector3[0];
  49107. this._maximum = BABYLON.Tmp.Vector3[1];
  49108. this._minBbox = BABYLON.Tmp.Vector3[4];
  49109. this._maxBbox = BABYLON.Tmp.Vector3[5];
  49110. this._particlesIntersect = false;
  49111. this._depthSortFunction = function (p1, p2) {
  49112. return (p2.sqDistance - p1.sqDistance);
  49113. };
  49114. this._needs32Bits = false;
  49115. this.name = name;
  49116. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  49117. this._camera = scene.activeCamera;
  49118. this._pickable = options ? options.isPickable : false;
  49119. this._depthSort = options ? options.enableDepthSort : false;
  49120. this._particlesIntersect = options ? options.particleIntersection : false;
  49121. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  49122. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  49123. if (options && options.updatable) {
  49124. this._updatable = options.updatable;
  49125. }
  49126. else {
  49127. this._updatable = true;
  49128. }
  49129. if (this._pickable) {
  49130. this.pickedParticles = [];
  49131. }
  49132. if (this._depthSort) {
  49133. this.depthSortedParticles = [];
  49134. }
  49135. }
  49136. /**
  49137. * Builds the SPS underlying mesh. Returns a standard Mesh.
  49138. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  49139. * @returns the created mesh
  49140. */
  49141. SolidParticleSystem.prototype.buildMesh = function () {
  49142. if (this.nbParticles === 0) {
  49143. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  49144. this.addShape(triangle, 1);
  49145. triangle.dispose();
  49146. }
  49147. this._indices32 = (this._needs32Bits) ? new Uint32Array(this._indices) : new Uint16Array(this._indices);
  49148. this._positions32 = new Float32Array(this._positions);
  49149. this._uvs32 = new Float32Array(this._uvs);
  49150. this._colors32 = new Float32Array(this._colors);
  49151. if (this.recomputeNormals) {
  49152. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals);
  49153. }
  49154. this._normals32 = new Float32Array(this._normals);
  49155. this._fixedNormal32 = new Float32Array(this._normals);
  49156. if (this._mustUnrotateFixedNormals) {
  49157. this._unrotateFixedNormals();
  49158. }
  49159. var vertexData = new BABYLON.VertexData();
  49160. vertexData.indices = (this._depthSort) ? this._indices : this._indices32;
  49161. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  49162. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  49163. if (this._uvs32) {
  49164. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  49165. ;
  49166. }
  49167. if (this._colors32) {
  49168. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  49169. }
  49170. var mesh = new BABYLON.Mesh(this.name, this._scene);
  49171. vertexData.applyToMesh(mesh, this._updatable);
  49172. this.mesh = mesh;
  49173. this.mesh.isPickable = this._pickable;
  49174. // free memory
  49175. if (!this._depthSort) {
  49176. this._indices = null;
  49177. }
  49178. this._positions = null;
  49179. this._normals = null;
  49180. this._uvs = null;
  49181. this._colors = null;
  49182. if (!this._updatable) {
  49183. this.particles.length = 0;
  49184. }
  49185. return mesh;
  49186. };
  49187. /**
  49188. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  49189. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  49190. * Thus the particles generated from `digest()` have their property `position` set yet.
  49191. * @param mesh ( Mesh ) is the mesh to be digested
  49192. * @param options {facetNb} (optional integer, default 1) is the number of mesh facets per particle, this parameter is overriden by the parameter `number` if any
  49193. * {delta} (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  49194. * {number} (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  49195. * @returns the current SPS
  49196. */
  49197. SolidParticleSystem.prototype.digest = function (mesh, options) {
  49198. var size = (options && options.facetNb) || 1;
  49199. var number = (options && options.number) || 0;
  49200. var delta = (options && options.delta) || 0;
  49201. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  49202. var meshInd = mesh.getIndices();
  49203. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  49204. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  49205. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  49206. var f = 0; // facet counter
  49207. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  49208. // compute size from number
  49209. if (number) {
  49210. number = (number > totalFacets) ? totalFacets : number;
  49211. size = Math.round(totalFacets / number);
  49212. delta = 0;
  49213. }
  49214. else {
  49215. size = (size > totalFacets) ? totalFacets : size;
  49216. }
  49217. var facetPos = []; // submesh positions
  49218. var facetInd = []; // submesh indices
  49219. var facetUV = []; // submesh UV
  49220. var facetCol = []; // submesh colors
  49221. var barycenter = BABYLON.Tmp.Vector3[0];
  49222. var sizeO = size;
  49223. while (f < totalFacets) {
  49224. size = sizeO + Math.floor((1 + delta) * Math.random());
  49225. if (f > totalFacets - size) {
  49226. size = totalFacets - f;
  49227. }
  49228. // reset temp arrays
  49229. facetPos.length = 0;
  49230. facetInd.length = 0;
  49231. facetUV.length = 0;
  49232. facetCol.length = 0;
  49233. // iterate over "size" facets
  49234. var fi = 0;
  49235. for (var j = f * 3; j < (f + size) * 3; j++) {
  49236. facetInd.push(fi);
  49237. var i = meshInd[j];
  49238. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  49239. if (meshUV) {
  49240. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  49241. }
  49242. if (meshCol) {
  49243. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  49244. }
  49245. fi++;
  49246. }
  49247. // create a model shape for each single particle
  49248. var idx = this.nbParticles;
  49249. var shape = this._posToShape(facetPos);
  49250. var shapeUV = this._uvsToShapeUV(facetUV);
  49251. // compute the barycenter of the shape
  49252. var v;
  49253. for (v = 0; v < shape.length; v++) {
  49254. barycenter.addInPlace(shape[v]);
  49255. }
  49256. barycenter.scaleInPlace(1 / shape.length);
  49257. // shift the shape from its barycenter to the origin
  49258. for (v = 0; v < shape.length; v++) {
  49259. shape[v].subtractInPlace(barycenter);
  49260. }
  49261. var bInfo;
  49262. if (this._particlesIntersect) {
  49263. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  49264. }
  49265. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, size * 3, shapeUV, null, null);
  49266. // add the particle in the SPS
  49267. var currentPos = this._positions.length;
  49268. var currentInd = this._indices.length;
  49269. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  49270. this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, 0, bInfo);
  49271. // initialize the particle position
  49272. this.particles[this.nbParticles].position.addInPlace(barycenter);
  49273. this._index += shape.length;
  49274. idx++;
  49275. this.nbParticles++;
  49276. this._shapeCounter++;
  49277. f += size;
  49278. }
  49279. return this;
  49280. };
  49281. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  49282. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  49283. var index = 0;
  49284. var idx = 0;
  49285. for (var p = 0; p < this.particles.length; p++) {
  49286. this._particle = this.particles[p];
  49287. this._shape = this._particle._model._shape;
  49288. if (this._particle.rotationQuaternion) {
  49289. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  49290. }
  49291. else {
  49292. this._yaw = this._particle.rotation.y;
  49293. this._pitch = this._particle.rotation.x;
  49294. this._roll = this._particle.rotation.z;
  49295. this._quaternionRotationYPR();
  49296. }
  49297. this._quaternionToRotationMatrix();
  49298. this._rotMatrix.invertToRef(this._invertMatrix);
  49299. for (var pt = 0; pt < this._shape.length; pt++) {
  49300. idx = index + pt * 3;
  49301. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  49302. this._fixedNormal32[idx] = this._normal.x;
  49303. this._fixedNormal32[idx + 1] = this._normal.y;
  49304. this._fixedNormal32[idx + 2] = this._normal.z;
  49305. }
  49306. index = idx + 3;
  49307. }
  49308. };
  49309. //reset copy
  49310. SolidParticleSystem.prototype._resetCopy = function () {
  49311. this._copy.position.x = 0;
  49312. this._copy.position.y = 0;
  49313. this._copy.position.z = 0;
  49314. this._copy.rotation.x = 0;
  49315. this._copy.rotation.y = 0;
  49316. this._copy.rotation.z = 0;
  49317. this._copy.rotationQuaternion = null;
  49318. this._copy.scaling.x = 1.0;
  49319. this._copy.scaling.y = 1.0;
  49320. this._copy.scaling.z = 1.0;
  49321. this._copy.uvs.x = 0;
  49322. this._copy.uvs.y = 0;
  49323. this._copy.uvs.z = 1.0;
  49324. this._copy.uvs.w = 1.0;
  49325. this._copy.color = null;
  49326. };
  49327. // _meshBuilder : inserts the shape model in the global SPS mesh
  49328. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  49329. var i;
  49330. var u = 0;
  49331. var c = 0;
  49332. var n = 0;
  49333. this._resetCopy();
  49334. if (options && options.positionFunction) {
  49335. options.positionFunction(this._copy, idx, idxInShape);
  49336. this._mustUnrotateFixedNormals = true;
  49337. }
  49338. if (this._copy.rotationQuaternion) {
  49339. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  49340. }
  49341. else {
  49342. this._yaw = this._copy.rotation.y;
  49343. this._pitch = this._copy.rotation.x;
  49344. this._roll = this._copy.rotation.z;
  49345. this._quaternionRotationYPR();
  49346. }
  49347. this._quaternionToRotationMatrix();
  49348. for (i = 0; i < shape.length; i++) {
  49349. this._vertex.x = shape[i].x;
  49350. this._vertex.y = shape[i].y;
  49351. this._vertex.z = shape[i].z;
  49352. if (options && options.vertexFunction) {
  49353. options.vertexFunction(this._copy, this._vertex, i);
  49354. }
  49355. this._vertex.x *= this._copy.scaling.x;
  49356. this._vertex.y *= this._copy.scaling.y;
  49357. this._vertex.z *= this._copy.scaling.z;
  49358. this._vertex.x += this._copy.pivot.x;
  49359. this._vertex.y += this._copy.pivot.y;
  49360. this._vertex.z += this._copy.pivot.z;
  49361. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  49362. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  49363. if (meshUV) {
  49364. 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);
  49365. u += 2;
  49366. }
  49367. if (this._copy.color) {
  49368. this._color = this._copy.color;
  49369. }
  49370. else if (meshCol && meshCol[c] !== undefined) {
  49371. this._color.r = meshCol[c];
  49372. this._color.g = meshCol[c + 1];
  49373. this._color.b = meshCol[c + 2];
  49374. this._color.a = meshCol[c + 3];
  49375. }
  49376. else {
  49377. this._color.r = 1.0;
  49378. this._color.g = 1.0;
  49379. this._color.b = 1.0;
  49380. this._color.a = 1.0;
  49381. }
  49382. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  49383. c += 4;
  49384. if (!this.recomputeNormals && meshNor) {
  49385. this._normal.x = meshNor[n];
  49386. this._normal.y = meshNor[n + 1];
  49387. this._normal.z = meshNor[n + 2];
  49388. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  49389. normals.push(this._normal.x, this._normal.y, this._normal.z);
  49390. n += 3;
  49391. }
  49392. }
  49393. for (i = 0; i < meshInd.length; i++) {
  49394. var current_ind = p + meshInd[i];
  49395. indices.push(current_ind);
  49396. if (current_ind > 65535) {
  49397. this._needs32Bits = true;
  49398. }
  49399. }
  49400. if (this._pickable) {
  49401. var nbfaces = meshInd.length / 3;
  49402. for (i = 0; i < nbfaces; i++) {
  49403. this.pickedParticles.push({ idx: idx, faceId: i });
  49404. }
  49405. }
  49406. if (this._depthSort) {
  49407. this.depthSortedParticles.push(new BABYLON.DepthSortedParticle());
  49408. }
  49409. return this._copy;
  49410. };
  49411. // returns a shape array from positions array
  49412. SolidParticleSystem.prototype._posToShape = function (positions) {
  49413. var shape = [];
  49414. for (var i = 0; i < positions.length; i += 3) {
  49415. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  49416. }
  49417. return shape;
  49418. };
  49419. // returns a shapeUV array from a Vector4 uvs
  49420. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  49421. var shapeUV = [];
  49422. if (uvs) {
  49423. for (var i = 0; i < uvs.length; i++)
  49424. shapeUV.push(uvs[i]);
  49425. }
  49426. return shapeUV;
  49427. };
  49428. // adds a new particle object in the particles array
  49429. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, idxind, model, shapeId, idxInShape, bInfo) {
  49430. if (bInfo === void 0) { bInfo = null; }
  49431. var sp = new BABYLON.SolidParticle(idx, idxpos, idxind, model, shapeId, idxInShape, this, bInfo);
  49432. this.particles.push(sp);
  49433. return sp;
  49434. };
  49435. /**
  49436. * Adds some particles to the SPS from the model shape. Returns the shape id.
  49437. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  49438. * @param mesh is any Mesh object that will be used as a model for the solid particles.
  49439. * @param nb (positive integer) the number of particles to be created from this model
  49440. * @param options {positionFunction} is an optional javascript function to called for each particle on SPS creation.
  49441. * {vertexFunction} is an optional javascript function to called for each vertex of each particle on SPS creation
  49442. * @returns the number of shapes in the system
  49443. */
  49444. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  49445. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  49446. var meshInd = mesh.getIndices();
  49447. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  49448. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  49449. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  49450. var bbInfo;
  49451. if (this._particlesIntersect) {
  49452. bbInfo = mesh.getBoundingInfo();
  49453. }
  49454. var shape = this._posToShape(meshPos);
  49455. var shapeUV = this._uvsToShapeUV(meshUV);
  49456. var posfunc = options ? options.positionFunction : null;
  49457. var vtxfunc = options ? options.vertexFunction : null;
  49458. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, meshInd.length, shapeUV, posfunc, vtxfunc);
  49459. // particles
  49460. var sp;
  49461. var currentCopy;
  49462. var idx = this.nbParticles;
  49463. for (var i = 0; i < nb; i++) {
  49464. var currentPos = this._positions.length;
  49465. var currentInd = this._indices.length;
  49466. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  49467. if (this._updatable) {
  49468. sp = this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, i, bbInfo);
  49469. sp.position.copyFrom(currentCopy.position);
  49470. sp.rotation.copyFrom(currentCopy.rotation);
  49471. if (currentCopy.rotationQuaternion && sp.rotationQuaternion) {
  49472. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  49473. }
  49474. if (currentCopy.color && sp.color) {
  49475. sp.color.copyFrom(currentCopy.color);
  49476. }
  49477. sp.scaling.copyFrom(currentCopy.scaling);
  49478. sp.uvs.copyFrom(currentCopy.uvs);
  49479. }
  49480. this._index += shape.length;
  49481. idx++;
  49482. }
  49483. this.nbParticles += nb;
  49484. this._shapeCounter++;
  49485. return this._shapeCounter - 1;
  49486. };
  49487. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  49488. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  49489. this._resetCopy();
  49490. if (particle._model._positionFunction) {
  49491. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  49492. }
  49493. if (this._copy.rotationQuaternion) {
  49494. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  49495. }
  49496. else {
  49497. this._yaw = this._copy.rotation.y;
  49498. this._pitch = this._copy.rotation.x;
  49499. this._roll = this._copy.rotation.z;
  49500. this._quaternionRotationYPR();
  49501. }
  49502. this._quaternionToRotationMatrix();
  49503. this._shape = particle._model._shape;
  49504. for (var pt = 0; pt < this._shape.length; pt++) {
  49505. this._vertex.x = this._shape[pt].x;
  49506. this._vertex.y = this._shape[pt].y;
  49507. this._vertex.z = this._shape[pt].z;
  49508. if (particle._model._vertexFunction) {
  49509. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  49510. }
  49511. this._vertex.x *= this._copy.scaling.x;
  49512. this._vertex.y *= this._copy.scaling.y;
  49513. this._vertex.z *= this._copy.scaling.z;
  49514. this._vertex.x += this._copy.pivot.x;
  49515. this._vertex.y += this._copy.pivot.y;
  49516. this._vertex.z += this._copy.pivot.z;
  49517. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  49518. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  49519. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  49520. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  49521. }
  49522. particle.position.x = 0.0;
  49523. particle.position.y = 0.0;
  49524. particle.position.z = 0.0;
  49525. particle.rotation.x = 0.0;
  49526. particle.rotation.y = 0.0;
  49527. particle.rotation.z = 0.0;
  49528. particle.rotationQuaternion = null;
  49529. particle.scaling.x = 1.0;
  49530. particle.scaling.y = 1.0;
  49531. particle.scaling.z = 1.0;
  49532. };
  49533. /**
  49534. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  49535. * @returns the SPS.
  49536. */
  49537. SolidParticleSystem.prototype.rebuildMesh = function () {
  49538. for (var p = 0; p < this.particles.length; p++) {
  49539. this._rebuildParticle(this.particles[p]);
  49540. }
  49541. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  49542. return this;
  49543. };
  49544. /**
  49545. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  49546. * This method calls `updateParticle()` for each particle of the SPS.
  49547. * For an animated SPS, it is usually called within the render loop.
  49548. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  49549. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  49550. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  49551. * @returns the SPS.
  49552. */
  49553. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  49554. if (start === void 0) { start = 0; }
  49555. if (end === void 0) { end = this.nbParticles - 1; }
  49556. if (update === void 0) { update = true; }
  49557. if (!this._updatable) {
  49558. return this;
  49559. }
  49560. // custom beforeUpdate
  49561. this.beforeUpdateParticles(start, end, update);
  49562. this._cam_axisX.x = 1.0;
  49563. this._cam_axisX.y = 0.0;
  49564. this._cam_axisX.z = 0.0;
  49565. this._cam_axisY.x = 0.0;
  49566. this._cam_axisY.y = 1.0;
  49567. this._cam_axisY.z = 0.0;
  49568. this._cam_axisZ.x = 0.0;
  49569. this._cam_axisZ.y = 0.0;
  49570. this._cam_axisZ.z = 1.0;
  49571. // cases when the World Matrix is to be computed first
  49572. if (this.billboard || this._depthSort) {
  49573. this.mesh.computeWorldMatrix(true);
  49574. this.mesh._worldMatrix.invertToRef(this._invertMatrix);
  49575. }
  49576. // if the particles will always face the camera
  49577. if (this.billboard) {
  49578. // compute the camera position and un-rotate it by the current mesh rotation
  49579. this._camera.getDirectionToRef(this._axisZ, this._camDir);
  49580. BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  49581. this._cam_axisZ.normalize();
  49582. // same for camera up vector extracted from the cam view matrix
  49583. var view = this._camera.getViewMatrix(true);
  49584. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  49585. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  49586. this._cam_axisY.normalize();
  49587. this._cam_axisX.normalize();
  49588. }
  49589. // if depthSort, compute the camera global position in the mesh local system
  49590. if (this._depthSort) {
  49591. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._camInvertedPosition); // then un-rotate the camera
  49592. }
  49593. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  49594. var idx = 0; // current position index in the global array positions32
  49595. var index = 0; // position start index in the global array positions32 of the current particle
  49596. var colidx = 0; // current color index in the global array colors32
  49597. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  49598. var uvidx = 0; // current uv index in the global array uvs32
  49599. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  49600. var pt = 0; // current index in the particle model shape
  49601. if (this.mesh.isFacetDataEnabled) {
  49602. this._computeBoundingBox = true;
  49603. }
  49604. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  49605. if (this._computeBoundingBox) {
  49606. if (start == 0 && end == this.nbParticles - 1) {
  49607. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  49608. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  49609. }
  49610. else {
  49611. if (this.mesh._boundingInfo) {
  49612. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  49613. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  49614. }
  49615. }
  49616. }
  49617. // particle loop
  49618. index = this.particles[start]._pos;
  49619. var vpos = (index / 3) | 0;
  49620. colorIndex = vpos * 4;
  49621. uvIndex = vpos * 2;
  49622. for (var p = start; p <= end; p++) {
  49623. this._particle = this.particles[p];
  49624. this._shape = this._particle._model._shape;
  49625. this._shapeUV = this._particle._model._shapeUV;
  49626. // call to custom user function to update the particle properties
  49627. this.updateParticle(this._particle);
  49628. // camera-particle distance for depth sorting
  49629. if (this._depthSort && this._depthSortParticles) {
  49630. var dsp = this.depthSortedParticles[p];
  49631. dsp.ind = this._particle._ind;
  49632. dsp.indicesLength = this._particle._model._indicesLength;
  49633. dsp.sqDistance = BABYLON.Vector3.DistanceSquared(this._particle.position, this._camInvertedPosition);
  49634. }
  49635. // skip the computations for inactive or already invisible particles
  49636. if (!this._particle.alive || (this._particle._stillInvisible && !this._particle.isVisible)) {
  49637. // increment indexes for the next particle
  49638. pt = this._shape.length;
  49639. index += pt * 3;
  49640. colorIndex += pt * 4;
  49641. uvIndex += pt * 2;
  49642. continue;
  49643. }
  49644. if (this._particle.isVisible) {
  49645. this._particle._stillInvisible = false; // un-mark permanent invisibility
  49646. // particle rotation matrix
  49647. if (this.billboard) {
  49648. this._particle.rotation.x = 0.0;
  49649. this._particle.rotation.y = 0.0;
  49650. }
  49651. if (this._computeParticleRotation || this.billboard) {
  49652. if (this._particle.rotationQuaternion) {
  49653. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  49654. }
  49655. else {
  49656. this._yaw = this._particle.rotation.y;
  49657. this._pitch = this._particle.rotation.x;
  49658. this._roll = this._particle.rotation.z;
  49659. this._quaternionRotationYPR();
  49660. }
  49661. this._quaternionToRotationMatrix();
  49662. }
  49663. // particle vertex loop
  49664. for (pt = 0; pt < this._shape.length; pt++) {
  49665. idx = index + pt * 3;
  49666. colidx = colorIndex + pt * 4;
  49667. uvidx = uvIndex + pt * 2;
  49668. this._vertex.x = this._shape[pt].x;
  49669. this._vertex.y = this._shape[pt].y;
  49670. this._vertex.z = this._shape[pt].z;
  49671. if (this._computeParticleVertex) {
  49672. this.updateParticleVertex(this._particle, this._vertex, pt);
  49673. }
  49674. // positions
  49675. this._vertex.x *= this._particle.scaling.x;
  49676. this._vertex.y *= this._particle.scaling.y;
  49677. this._vertex.z *= this._particle.scaling.z;
  49678. this._vertex.x += this._particle.pivot.x;
  49679. this._vertex.y += this._particle.pivot.y;
  49680. this._vertex.z += this._particle.pivot.z;
  49681. this._rotated.x = this._vertex.x * this._rotMatrix.m[0] + this._vertex.y * this._rotMatrix.m[4] + this._vertex.z * this._rotMatrix.m[8];
  49682. this._rotated.y = this._vertex.x * this._rotMatrix.m[1] + this._vertex.y * this._rotMatrix.m[5] + this._vertex.z * this._rotMatrix.m[9];
  49683. this._rotated.z = this._vertex.x * this._rotMatrix.m[2] + this._vertex.y * this._rotMatrix.m[6] + this._vertex.z * this._rotMatrix.m[10];
  49684. 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;
  49685. 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;
  49686. 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;
  49687. if (this._computeBoundingBox) {
  49688. if (this._positions32[idx] < this._minimum.x) {
  49689. this._minimum.x = this._positions32[idx];
  49690. }
  49691. if (this._positions32[idx] > this._maximum.x) {
  49692. this._maximum.x = this._positions32[idx];
  49693. }
  49694. if (this._positions32[idx + 1] < this._minimum.y) {
  49695. this._minimum.y = this._positions32[idx + 1];
  49696. }
  49697. if (this._positions32[idx + 1] > this._maximum.y) {
  49698. this._maximum.y = this._positions32[idx + 1];
  49699. }
  49700. if (this._positions32[idx + 2] < this._minimum.z) {
  49701. this._minimum.z = this._positions32[idx + 2];
  49702. }
  49703. if (this._positions32[idx + 2] > this._maximum.z) {
  49704. this._maximum.z = this._positions32[idx + 2];
  49705. }
  49706. }
  49707. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  49708. if (!this._computeParticleVertex) {
  49709. this._normal.x = this._fixedNormal32[idx];
  49710. this._normal.y = this._fixedNormal32[idx + 1];
  49711. this._normal.z = this._fixedNormal32[idx + 2];
  49712. this._rotated.x = this._normal.x * this._rotMatrix.m[0] + this._normal.y * this._rotMatrix.m[4] + this._normal.z * this._rotMatrix.m[8];
  49713. this._rotated.y = this._normal.x * this._rotMatrix.m[1] + this._normal.y * this._rotMatrix.m[5] + this._normal.z * this._rotMatrix.m[9];
  49714. this._rotated.z = this._normal.x * this._rotMatrix.m[2] + this._normal.y * this._rotMatrix.m[6] + this._normal.z * this._rotMatrix.m[10];
  49715. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  49716. 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;
  49717. 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;
  49718. }
  49719. if (this._computeParticleColor && this._particle.color) {
  49720. this._colors32[colidx] = this._particle.color.r;
  49721. this._colors32[colidx + 1] = this._particle.color.g;
  49722. this._colors32[colidx + 2] = this._particle.color.b;
  49723. this._colors32[colidx + 3] = this._particle.color.a;
  49724. }
  49725. if (this._computeParticleTexture) {
  49726. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  49727. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  49728. }
  49729. }
  49730. }
  49731. else {
  49732. this._particle._stillInvisible = true; // mark the particle as invisible
  49733. for (pt = 0; pt < this._shape.length; pt++) {
  49734. idx = index + pt * 3;
  49735. colidx = colorIndex + pt * 4;
  49736. uvidx = uvIndex + pt * 2;
  49737. this._positions32[idx] = 0.0;
  49738. this._positions32[idx + 1] = 0.0;
  49739. this._positions32[idx + 2] = 0.0;
  49740. this._normals32[idx] = 0.0;
  49741. this._normals32[idx + 1] = 0.0;
  49742. this._normals32[idx + 2] = 0.0;
  49743. if (this._computeParticleColor && this._particle.color) {
  49744. this._colors32[colidx] = this._particle.color.r;
  49745. this._colors32[colidx + 1] = this._particle.color.g;
  49746. this._colors32[colidx + 2] = this._particle.color.b;
  49747. this._colors32[colidx + 3] = this._particle.color.a;
  49748. }
  49749. if (this._computeParticleTexture) {
  49750. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  49751. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  49752. }
  49753. }
  49754. }
  49755. // if the particle intersections must be computed : update the bbInfo
  49756. if (this._particlesIntersect) {
  49757. var bInfo = this._particle._boundingInfo;
  49758. var bBox = bInfo.boundingBox;
  49759. var bSphere = bInfo.boundingSphere;
  49760. if (!this._bSphereOnly) {
  49761. // place, scale and rotate the particle bbox within the SPS local system, then update it
  49762. for (var b = 0; b < bBox.vectors.length; b++) {
  49763. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  49764. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  49765. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  49766. this._rotated.x = this._vertex.x * this._rotMatrix.m[0] + this._vertex.y * this._rotMatrix.m[4] + this._vertex.z * this._rotMatrix.m[8];
  49767. this._rotated.y = this._vertex.x * this._rotMatrix.m[1] + this._vertex.y * this._rotMatrix.m[5] + this._vertex.z * this._rotMatrix.m[9];
  49768. this._rotated.z = this._vertex.x * this._rotMatrix.m[2] + this._vertex.y * this._rotMatrix.m[6] + this._vertex.z * this._rotMatrix.m[10];
  49769. 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;
  49770. 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;
  49771. 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;
  49772. }
  49773. bBox._update(this.mesh._worldMatrix);
  49774. }
  49775. // place and scale the particle bouding sphere in the SPS local system, then update it
  49776. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  49777. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  49778. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  49779. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  49780. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  49781. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  49782. bSphere.center.x = this._particle.position.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  49783. bSphere.center.y = this._particle.position.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  49784. bSphere.center.z = this._particle.position.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  49785. 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));
  49786. bSphere._update(this.mesh._worldMatrix);
  49787. }
  49788. // increment indexes for the next particle
  49789. index = idx + 3;
  49790. colorIndex = colidx + 4;
  49791. uvIndex = uvidx + 2;
  49792. }
  49793. // if the VBO must be updated
  49794. if (update) {
  49795. if (this._computeParticleColor) {
  49796. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  49797. }
  49798. if (this._computeParticleTexture) {
  49799. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  49800. }
  49801. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  49802. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  49803. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  49804. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  49805. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  49806. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals32, params);
  49807. for (var i = 0; i < this._normals32.length; i++) {
  49808. this._fixedNormal32[i] = this._normals32[i];
  49809. }
  49810. }
  49811. if (!this.mesh.areNormalsFrozen) {
  49812. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  49813. }
  49814. }
  49815. if (this._depthSort && this._depthSortParticles) {
  49816. this.depthSortedParticles.sort(this._depthSortFunction);
  49817. var dspl = this.depthSortedParticles.length;
  49818. var sorted = 0;
  49819. var lind = 0;
  49820. var sind = 0;
  49821. var sid = 0;
  49822. for (sorted = 0; sorted < dspl; sorted++) {
  49823. lind = this.depthSortedParticles[sorted].indicesLength;
  49824. sind = this.depthSortedParticles[sorted].ind;
  49825. for (var i = 0; i < lind; i++) {
  49826. this._indices32[sid] = this._indices[sind + i];
  49827. sid++;
  49828. }
  49829. }
  49830. this.mesh.updateIndices(this._indices32);
  49831. }
  49832. }
  49833. if (this._computeBoundingBox) {
  49834. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  49835. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  49836. }
  49837. this.afterUpdateParticles(start, end, update);
  49838. return this;
  49839. };
  49840. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  49841. this._halfroll = this._roll * 0.5;
  49842. this._halfpitch = this._pitch * 0.5;
  49843. this._halfyaw = this._yaw * 0.5;
  49844. this._sinRoll = Math.sin(this._halfroll);
  49845. this._cosRoll = Math.cos(this._halfroll);
  49846. this._sinPitch = Math.sin(this._halfpitch);
  49847. this._cosPitch = Math.cos(this._halfpitch);
  49848. this._sinYaw = Math.sin(this._halfyaw);
  49849. this._cosYaw = Math.cos(this._halfyaw);
  49850. this._quaternion.x = this._cosYaw * this._sinPitch * this._cosRoll + this._sinYaw * this._cosPitch * this._sinRoll;
  49851. this._quaternion.y = this._sinYaw * this._cosPitch * this._cosRoll - this._cosYaw * this._sinPitch * this._sinRoll;
  49852. this._quaternion.z = this._cosYaw * this._cosPitch * this._sinRoll - this._sinYaw * this._sinPitch * this._cosRoll;
  49853. this._quaternion.w = this._cosYaw * this._cosPitch * this._cosRoll + this._sinYaw * this._sinPitch * this._sinRoll;
  49854. };
  49855. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  49856. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  49857. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  49858. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  49859. this._rotMatrix.m[3] = 0;
  49860. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  49861. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  49862. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  49863. this._rotMatrix.m[7] = 0;
  49864. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  49865. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  49866. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  49867. this._rotMatrix.m[11] = 0;
  49868. this._rotMatrix.m[12] = 0;
  49869. this._rotMatrix.m[13] = 0;
  49870. this._rotMatrix.m[14] = 0;
  49871. this._rotMatrix.m[15] = 1.0;
  49872. };
  49873. /**
  49874. * Disposes the SPS.
  49875. */
  49876. SolidParticleSystem.prototype.dispose = function () {
  49877. this.mesh.dispose();
  49878. this.vars = null;
  49879. // drop references to internal big arrays for the GC
  49880. this._positions = null;
  49881. this._indices = null;
  49882. this._normals = null;
  49883. this._uvs = null;
  49884. this._colors = null;
  49885. this._indices32 = null;
  49886. this._positions32 = null;
  49887. this._normals32 = null;
  49888. this._fixedNormal32 = null;
  49889. this._uvs32 = null;
  49890. this._colors32 = null;
  49891. this.pickedParticles = null;
  49892. };
  49893. /**
  49894. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  49895. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  49896. * @returns the SPS.
  49897. */
  49898. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  49899. if (!this._isVisibilityBoxLocked) {
  49900. this.mesh.refreshBoundingInfo();
  49901. }
  49902. return this;
  49903. };
  49904. /**
  49905. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  49906. * @param size the size (float) of the visibility box
  49907. * note : this doesn't lock the SPS mesh bounding box.
  49908. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  49909. */
  49910. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  49911. var vis = size / 2;
  49912. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  49913. };
  49914. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  49915. /**
  49916. * Gets whether the SPS as always visible or not
  49917. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  49918. */
  49919. get: function () {
  49920. return this._alwaysVisible;
  49921. },
  49922. /**
  49923. * Sets the SPS as always visible or not
  49924. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  49925. */
  49926. set: function (val) {
  49927. this._alwaysVisible = val;
  49928. this.mesh.alwaysSelectAsActiveMesh = val;
  49929. },
  49930. enumerable: true,
  49931. configurable: true
  49932. });
  49933. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  49934. /**
  49935. * Gets if the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  49936. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  49937. */
  49938. get: function () {
  49939. return this._isVisibilityBoxLocked;
  49940. },
  49941. /**
  49942. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  49943. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  49944. */
  49945. set: function (val) {
  49946. this._isVisibilityBoxLocked = val;
  49947. var boundingInfo = this.mesh.getBoundingInfo();
  49948. boundingInfo.isLocked = val;
  49949. },
  49950. enumerable: true,
  49951. configurable: true
  49952. });
  49953. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  49954. /**
  49955. * Gets if `setParticles()` computes the particle rotations or not.
  49956. * Default value : true. The SPS is faster when it's set to false.
  49957. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  49958. */
  49959. get: function () {
  49960. return this._computeParticleRotation;
  49961. },
  49962. /**
  49963. * Tells to `setParticles()` to compute the particle rotations or not.
  49964. * Default value : true. The SPS is faster when it's set to false.
  49965. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  49966. */
  49967. set: function (val) {
  49968. this._computeParticleRotation = val;
  49969. },
  49970. enumerable: true,
  49971. configurable: true
  49972. });
  49973. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  49974. /**
  49975. * Gets if `setParticles()` computes the particle colors or not.
  49976. * Default value : true. The SPS is faster when it's set to false.
  49977. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  49978. */
  49979. get: function () {
  49980. return this._computeParticleColor;
  49981. },
  49982. /**
  49983. * Tells to `setParticles()` to compute the particle colors or not.
  49984. * Default value : true. The SPS is faster when it's set to false.
  49985. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  49986. */
  49987. set: function (val) {
  49988. this._computeParticleColor = val;
  49989. },
  49990. enumerable: true,
  49991. configurable: true
  49992. });
  49993. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  49994. /**
  49995. * Gets if `setParticles()` computes the particle textures or not.
  49996. * Default value : true. The SPS is faster when it's set to false.
  49997. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  49998. */
  49999. get: function () {
  50000. return this._computeParticleTexture;
  50001. },
  50002. set: function (val) {
  50003. this._computeParticleTexture = val;
  50004. },
  50005. enumerable: true,
  50006. configurable: true
  50007. });
  50008. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  50009. /**
  50010. * Gets if `setParticles()` calls the vertex function for each vertex of each particle, or not.
  50011. * Default value : false. The SPS is faster when it's set to false.
  50012. * Note : the particle custom vertex positions aren't stored values.
  50013. */
  50014. get: function () {
  50015. return this._computeParticleVertex;
  50016. },
  50017. /**
  50018. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  50019. * Default value : false. The SPS is faster when it's set to false.
  50020. * Note : the particle custom vertex positions aren't stored values.
  50021. */
  50022. set: function (val) {
  50023. this._computeParticleVertex = val;
  50024. },
  50025. enumerable: true,
  50026. configurable: true
  50027. });
  50028. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  50029. /**
  50030. * Gets if `setParticles()` computes or not the mesh bounding box when computing the particle positions.
  50031. */
  50032. get: function () {
  50033. return this._computeBoundingBox;
  50034. },
  50035. /**
  50036. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  50037. */
  50038. set: function (val) {
  50039. this._computeBoundingBox = val;
  50040. },
  50041. enumerable: true,
  50042. configurable: true
  50043. });
  50044. Object.defineProperty(SolidParticleSystem.prototype, "depthSortParticles", {
  50045. /**
  50046. * Gets if `setParticles()` sorts or not the distance between each particle and the camera.
  50047. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  50048. * Default : `true`
  50049. */
  50050. get: function () {
  50051. return this._depthSortParticles;
  50052. },
  50053. /**
  50054. * Tells to `setParticles()` to sort or not the distance between each particle and the camera.
  50055. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  50056. * Default : `true`
  50057. */
  50058. set: function (val) {
  50059. this._depthSortParticles = val;
  50060. },
  50061. enumerable: true,
  50062. configurable: true
  50063. });
  50064. // =======================================================================
  50065. // Particle behavior logic
  50066. // these following methods may be overwritten by the user to fit his needs
  50067. /**
  50068. * This function does nothing. It may be overwritten to set all the particle first values.
  50069. * The SPS doesn't call this function, you may have to call it by your own.
  50070. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  50071. */
  50072. SolidParticleSystem.prototype.initParticles = function () {
  50073. };
  50074. /**
  50075. * This function does nothing. It may be overwritten to recycle a particle.
  50076. * The SPS doesn't call this function, you may have to call it by your own.
  50077. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  50078. * @param particle The particle to recycle
  50079. * @returns the recycled particle
  50080. */
  50081. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  50082. return particle;
  50083. };
  50084. /**
  50085. * Updates a particle : this function should be overwritten by the user.
  50086. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  50087. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  50088. * @example : just set a particle position or velocity and recycle conditions
  50089. * @param particle The particle to update
  50090. * @returns the updated particle
  50091. */
  50092. SolidParticleSystem.prototype.updateParticle = function (particle) {
  50093. return particle;
  50094. };
  50095. /**
  50096. * Updates a vertex of a particle : it can be overwritten by the user.
  50097. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  50098. * @param particle the current particle
  50099. * @param vertex the current index of the current particle
  50100. * @param pt the index of the current vertex in the particle shape
  50101. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  50102. * @example : just set a vertex particle position
  50103. * @returns the updated vertex
  50104. */
  50105. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  50106. return vertex;
  50107. };
  50108. /**
  50109. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  50110. * This does nothing and may be overwritten by the user.
  50111. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  50112. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  50113. * @param update the boolean update value actually passed to setParticles()
  50114. */
  50115. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  50116. };
  50117. /**
  50118. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  50119. * This will be passed three parameters.
  50120. * This does nothing and may be overwritten by the user.
  50121. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  50122. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  50123. * @param update the boolean update value actually passed to setParticles()
  50124. */
  50125. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  50126. };
  50127. return SolidParticleSystem;
  50128. }());
  50129. BABYLON.SolidParticleSystem = SolidParticleSystem;
  50130. })(BABYLON || (BABYLON = {}));
  50131. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  50132. var BABYLON;
  50133. (function (BABYLON) {
  50134. var ShaderMaterial = /** @class */ (function (_super) {
  50135. __extends(ShaderMaterial, _super);
  50136. function ShaderMaterial(name, scene, shaderPath, options) {
  50137. var _this = _super.call(this, name, scene) || this;
  50138. _this._textures = {};
  50139. _this._textureArrays = {};
  50140. _this._floats = {};
  50141. _this._ints = {};
  50142. _this._floatsArrays = {};
  50143. _this._colors3 = {};
  50144. _this._colors3Arrays = {};
  50145. _this._colors4 = {};
  50146. _this._vectors2 = {};
  50147. _this._vectors3 = {};
  50148. _this._vectors4 = {};
  50149. _this._matrices = {};
  50150. _this._matrices3x3 = {};
  50151. _this._matrices2x2 = {};
  50152. _this._vectors2Arrays = {};
  50153. _this._vectors3Arrays = {};
  50154. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  50155. _this._shaderPath = shaderPath;
  50156. options.needAlphaBlending = options.needAlphaBlending || false;
  50157. options.needAlphaTesting = options.needAlphaTesting || false;
  50158. options.attributes = options.attributes || ["position", "normal", "uv"];
  50159. options.uniforms = options.uniforms || ["worldViewProjection"];
  50160. options.uniformBuffers = options.uniformBuffers || [];
  50161. options.samplers = options.samplers || [];
  50162. options.defines = options.defines || [];
  50163. _this._options = options;
  50164. return _this;
  50165. }
  50166. ShaderMaterial.prototype.getClassName = function () {
  50167. return "ShaderMaterial";
  50168. };
  50169. ShaderMaterial.prototype.needAlphaBlending = function () {
  50170. return this._options.needAlphaBlending;
  50171. };
  50172. ShaderMaterial.prototype.needAlphaTesting = function () {
  50173. return this._options.needAlphaTesting;
  50174. };
  50175. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  50176. if (this._options.uniforms.indexOf(uniformName) === -1) {
  50177. this._options.uniforms.push(uniformName);
  50178. }
  50179. };
  50180. ShaderMaterial.prototype.setTexture = function (name, texture) {
  50181. if (this._options.samplers.indexOf(name) === -1) {
  50182. this._options.samplers.push(name);
  50183. }
  50184. this._textures[name] = texture;
  50185. return this;
  50186. };
  50187. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  50188. if (this._options.samplers.indexOf(name) === -1) {
  50189. this._options.samplers.push(name);
  50190. }
  50191. this._checkUniform(name);
  50192. this._textureArrays[name] = textures;
  50193. return this;
  50194. };
  50195. ShaderMaterial.prototype.setFloat = function (name, value) {
  50196. this._checkUniform(name);
  50197. this._floats[name] = value;
  50198. return this;
  50199. };
  50200. ShaderMaterial.prototype.setInt = function (name, value) {
  50201. this._checkUniform(name);
  50202. this._ints[name] = value;
  50203. return this;
  50204. };
  50205. ShaderMaterial.prototype.setFloats = function (name, value) {
  50206. this._checkUniform(name);
  50207. this._floatsArrays[name] = value;
  50208. return this;
  50209. };
  50210. ShaderMaterial.prototype.setColor3 = function (name, value) {
  50211. this._checkUniform(name);
  50212. this._colors3[name] = value;
  50213. return this;
  50214. };
  50215. ShaderMaterial.prototype.setColor3Array = function (name, value) {
  50216. this._checkUniform(name);
  50217. this._colors3Arrays[name] = value.reduce(function (arr, color) {
  50218. color.toArray(arr, arr.length);
  50219. return arr;
  50220. }, []);
  50221. return this;
  50222. };
  50223. ShaderMaterial.prototype.setColor4 = function (name, value) {
  50224. this._checkUniform(name);
  50225. this._colors4[name] = value;
  50226. return this;
  50227. };
  50228. ShaderMaterial.prototype.setVector2 = function (name, value) {
  50229. this._checkUniform(name);
  50230. this._vectors2[name] = value;
  50231. return this;
  50232. };
  50233. ShaderMaterial.prototype.setVector3 = function (name, value) {
  50234. this._checkUniform(name);
  50235. this._vectors3[name] = value;
  50236. return this;
  50237. };
  50238. ShaderMaterial.prototype.setVector4 = function (name, value) {
  50239. this._checkUniform(name);
  50240. this._vectors4[name] = value;
  50241. return this;
  50242. };
  50243. ShaderMaterial.prototype.setMatrix = function (name, value) {
  50244. this._checkUniform(name);
  50245. this._matrices[name] = value;
  50246. return this;
  50247. };
  50248. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  50249. this._checkUniform(name);
  50250. this._matrices3x3[name] = value;
  50251. return this;
  50252. };
  50253. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  50254. this._checkUniform(name);
  50255. this._matrices2x2[name] = value;
  50256. return this;
  50257. };
  50258. ShaderMaterial.prototype.setArray2 = function (name, value) {
  50259. this._checkUniform(name);
  50260. this._vectors2Arrays[name] = value;
  50261. return this;
  50262. };
  50263. ShaderMaterial.prototype.setArray3 = function (name, value) {
  50264. this._checkUniform(name);
  50265. this._vectors3Arrays[name] = value;
  50266. return this;
  50267. };
  50268. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  50269. if (!mesh) {
  50270. return true;
  50271. }
  50272. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  50273. return false;
  50274. }
  50275. return false;
  50276. };
  50277. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  50278. var scene = this.getScene();
  50279. var engine = scene.getEngine();
  50280. if (!this.checkReadyOnEveryCall) {
  50281. if (this._renderId === scene.getRenderId()) {
  50282. if (this._checkCache(scene, mesh, useInstances)) {
  50283. return true;
  50284. }
  50285. }
  50286. }
  50287. // Instances
  50288. var defines = [];
  50289. var attribs = [];
  50290. var fallbacks = new BABYLON.EffectFallbacks();
  50291. if (useInstances) {
  50292. defines.push("#define INSTANCES");
  50293. }
  50294. for (var index = 0; index < this._options.defines.length; index++) {
  50295. defines.push(this._options.defines[index]);
  50296. }
  50297. for (var index = 0; index < this._options.attributes.length; index++) {
  50298. attribs.push(this._options.attributes[index]);
  50299. }
  50300. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  50301. attribs.push(BABYLON.VertexBuffer.ColorKind);
  50302. defines.push("#define VERTEXCOLOR");
  50303. }
  50304. // Bones
  50305. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  50306. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  50307. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  50308. if (mesh.numBoneInfluencers > 4) {
  50309. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  50310. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  50311. }
  50312. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  50313. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  50314. fallbacks.addCPUSkinningFallback(0, mesh);
  50315. if (this._options.uniforms.indexOf("mBones") === -1) {
  50316. this._options.uniforms.push("mBones");
  50317. }
  50318. }
  50319. else {
  50320. defines.push("#define NUM_BONE_INFLUENCERS 0");
  50321. }
  50322. // Textures
  50323. for (var name in this._textures) {
  50324. if (!this._textures[name].isReady()) {
  50325. return false;
  50326. }
  50327. }
  50328. // Alpha test
  50329. if (mesh && this._shouldTurnAlphaTestOn(mesh)) {
  50330. defines.push("#define ALPHATEST");
  50331. }
  50332. var previousEffect = this._effect;
  50333. var join = defines.join("\n");
  50334. this._effect = engine.createEffect(this._shaderPath, {
  50335. attributes: attribs,
  50336. uniformsNames: this._options.uniforms,
  50337. uniformBuffersNames: this._options.uniformBuffers,
  50338. samplers: this._options.samplers,
  50339. defines: join,
  50340. fallbacks: fallbacks,
  50341. onCompiled: this.onCompiled,
  50342. onError: this.onError
  50343. }, engine);
  50344. if (!this._effect.isReady()) {
  50345. return false;
  50346. }
  50347. if (previousEffect !== this._effect) {
  50348. scene.resetCachedMaterial();
  50349. }
  50350. this._renderId = scene.getRenderId();
  50351. return true;
  50352. };
  50353. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  50354. var scene = this.getScene();
  50355. if (!this._effect) {
  50356. return;
  50357. }
  50358. if (this._options.uniforms.indexOf("world") !== -1) {
  50359. this._effect.setMatrix("world", world);
  50360. }
  50361. if (this._options.uniforms.indexOf("worldView") !== -1) {
  50362. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  50363. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  50364. }
  50365. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  50366. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  50367. }
  50368. };
  50369. ShaderMaterial.prototype.bind = function (world, mesh) {
  50370. // Std values
  50371. this.bindOnlyWorldMatrix(world);
  50372. if (this._effect && this.getScene().getCachedMaterial() !== this) {
  50373. if (this._options.uniforms.indexOf("view") !== -1) {
  50374. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  50375. }
  50376. if (this._options.uniforms.indexOf("projection") !== -1) {
  50377. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  50378. }
  50379. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  50380. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  50381. }
  50382. // Bones
  50383. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  50384. var name;
  50385. // Texture
  50386. for (name in this._textures) {
  50387. this._effect.setTexture(name, this._textures[name]);
  50388. }
  50389. // Texture arrays
  50390. for (name in this._textureArrays) {
  50391. this._effect.setTextureArray(name, this._textureArrays[name]);
  50392. }
  50393. // Int
  50394. for (name in this._ints) {
  50395. this._effect.setInt(name, this._ints[name]);
  50396. }
  50397. // Float
  50398. for (name in this._floats) {
  50399. this._effect.setFloat(name, this._floats[name]);
  50400. }
  50401. // Floats
  50402. for (name in this._floatsArrays) {
  50403. this._effect.setArray(name, this._floatsArrays[name]);
  50404. }
  50405. // Color3
  50406. for (name in this._colors3) {
  50407. this._effect.setColor3(name, this._colors3[name]);
  50408. }
  50409. for (name in this._colors3Arrays) {
  50410. this._effect.setArray3(name, this._colors3Arrays[name]);
  50411. }
  50412. // Color4
  50413. for (name in this._colors4) {
  50414. var color = this._colors4[name];
  50415. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  50416. }
  50417. // Vector2
  50418. for (name in this._vectors2) {
  50419. this._effect.setVector2(name, this._vectors2[name]);
  50420. }
  50421. // Vector3
  50422. for (name in this._vectors3) {
  50423. this._effect.setVector3(name, this._vectors3[name]);
  50424. }
  50425. // Vector4
  50426. for (name in this._vectors4) {
  50427. this._effect.setVector4(name, this._vectors4[name]);
  50428. }
  50429. // Matrix
  50430. for (name in this._matrices) {
  50431. this._effect.setMatrix(name, this._matrices[name]);
  50432. }
  50433. // Matrix 3x3
  50434. for (name in this._matrices3x3) {
  50435. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  50436. }
  50437. // Matrix 2x2
  50438. for (name in this._matrices2x2) {
  50439. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  50440. }
  50441. // Vector2Array
  50442. for (name in this._vectors2Arrays) {
  50443. this._effect.setArray2(name, this._vectors2Arrays[name]);
  50444. }
  50445. // Vector3Array
  50446. for (name in this._vectors3Arrays) {
  50447. this._effect.setArray3(name, this._vectors3Arrays[name]);
  50448. }
  50449. }
  50450. this._afterBind(mesh);
  50451. };
  50452. ShaderMaterial.prototype.getActiveTextures = function () {
  50453. var activeTextures = _super.prototype.getActiveTextures.call(this);
  50454. for (var name in this._textures) {
  50455. activeTextures.push(this._textures[name]);
  50456. }
  50457. for (var name in this._textureArrays) {
  50458. var array = this._textureArrays[name];
  50459. for (var index = 0; index < array.length; index++) {
  50460. activeTextures.push(array[index]);
  50461. }
  50462. }
  50463. return activeTextures;
  50464. };
  50465. ShaderMaterial.prototype.hasTexture = function (texture) {
  50466. if (_super.prototype.hasTexture.call(this, texture)) {
  50467. return true;
  50468. }
  50469. for (var name in this._textures) {
  50470. if (this._textures[name] === texture) {
  50471. return true;
  50472. }
  50473. }
  50474. for (var name in this._textureArrays) {
  50475. var array = this._textureArrays[name];
  50476. for (var index = 0; index < array.length; index++) {
  50477. if (array[index] === texture) {
  50478. return true;
  50479. }
  50480. }
  50481. }
  50482. return false;
  50483. };
  50484. ShaderMaterial.prototype.clone = function (name) {
  50485. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  50486. return newShaderMaterial;
  50487. };
  50488. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  50489. if (forceDisposeTextures) {
  50490. var name;
  50491. for (name in this._textures) {
  50492. this._textures[name].dispose();
  50493. }
  50494. for (name in this._textureArrays) {
  50495. var array = this._textureArrays[name];
  50496. for (var index = 0; index < array.length; index++) {
  50497. array[index].dispose();
  50498. }
  50499. }
  50500. }
  50501. this._textures = {};
  50502. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  50503. };
  50504. ShaderMaterial.prototype.serialize = function () {
  50505. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  50506. serializationObject.customType = "BABYLON.ShaderMaterial";
  50507. serializationObject.options = this._options;
  50508. serializationObject.shaderPath = this._shaderPath;
  50509. var name;
  50510. // Texture
  50511. serializationObject.textures = {};
  50512. for (name in this._textures) {
  50513. serializationObject.textures[name] = this._textures[name].serialize();
  50514. }
  50515. // Texture arrays
  50516. serializationObject.textureArrays = {};
  50517. for (name in this._textureArrays) {
  50518. serializationObject.textureArrays[name] = [];
  50519. var array = this._textureArrays[name];
  50520. for (var index = 0; index < array.length; index++) {
  50521. serializationObject.textureArrays[name].push(array[index].serialize());
  50522. }
  50523. }
  50524. // Float
  50525. serializationObject.floats = {};
  50526. for (name in this._floats) {
  50527. serializationObject.floats[name] = this._floats[name];
  50528. }
  50529. // Float s
  50530. serializationObject.FloatArrays = {};
  50531. for (name in this._floatsArrays) {
  50532. serializationObject.FloatArrays[name] = this._floatsArrays[name];
  50533. }
  50534. // Color3
  50535. serializationObject.colors3 = {};
  50536. for (name in this._colors3) {
  50537. serializationObject.colors3[name] = this._colors3[name].asArray();
  50538. }
  50539. // Color3 array
  50540. serializationObject.colors3Arrays = {};
  50541. for (name in this._colors3Arrays) {
  50542. serializationObject.colors3Arrays[name] = this._colors3Arrays[name];
  50543. }
  50544. // Color4
  50545. serializationObject.colors4 = {};
  50546. for (name in this._colors4) {
  50547. serializationObject.colors4[name] = this._colors4[name].asArray();
  50548. }
  50549. // Vector2
  50550. serializationObject.vectors2 = {};
  50551. for (name in this._vectors2) {
  50552. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  50553. }
  50554. // Vector3
  50555. serializationObject.vectors3 = {};
  50556. for (name in this._vectors3) {
  50557. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  50558. }
  50559. // Vector4
  50560. serializationObject.vectors4 = {};
  50561. for (name in this._vectors4) {
  50562. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  50563. }
  50564. // Matrix
  50565. serializationObject.matrices = {};
  50566. for (name in this._matrices) {
  50567. serializationObject.matrices[name] = this._matrices[name].asArray();
  50568. }
  50569. // Matrix 3x3
  50570. serializationObject.matrices3x3 = {};
  50571. for (name in this._matrices3x3) {
  50572. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  50573. }
  50574. // Matrix 2x2
  50575. serializationObject.matrices2x2 = {};
  50576. for (name in this._matrices2x2) {
  50577. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  50578. }
  50579. // Vector2Array
  50580. serializationObject.vectors2Arrays = {};
  50581. for (name in this._vectors2Arrays) {
  50582. serializationObject.vectors2Arrays[name] = this._vectors2Arrays[name];
  50583. }
  50584. // Vector3Array
  50585. serializationObject.vectors3Arrays = {};
  50586. for (name in this._vectors3Arrays) {
  50587. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  50588. }
  50589. return serializationObject;
  50590. };
  50591. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  50592. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  50593. var name;
  50594. // Texture
  50595. for (name in source.textures) {
  50596. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  50597. }
  50598. // Texture arrays
  50599. for (name in source.textureArrays) {
  50600. var array = source.textureArrays[name];
  50601. var textureArray = new Array();
  50602. for (var index = 0; index < array.length; index++) {
  50603. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  50604. }
  50605. material.setTextureArray(name, textureArray);
  50606. }
  50607. // Float
  50608. for (name in source.floats) {
  50609. material.setFloat(name, source.floats[name]);
  50610. }
  50611. // Float s
  50612. for (name in source.floatsArrays) {
  50613. material.setFloats(name, source.floatsArrays[name]);
  50614. }
  50615. // Color3
  50616. for (name in source.colors3) {
  50617. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  50618. }
  50619. // Color3 arrays
  50620. for (name in source.colors3Arrays) {
  50621. var colors = source.colors3Arrays[name].reduce(function (arr, num, i) {
  50622. if (i % 3 === 0) {
  50623. arr.push([num]);
  50624. }
  50625. else {
  50626. arr[arr.length - 1].push(num);
  50627. }
  50628. return arr;
  50629. }, []).map(function (color) { return BABYLON.Color3.FromArray(color); });
  50630. material.setColor3Array(name, colors);
  50631. }
  50632. // Color4
  50633. for (name in source.colors4) {
  50634. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  50635. }
  50636. // Vector2
  50637. for (name in source.vectors2) {
  50638. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  50639. }
  50640. // Vector3
  50641. for (name in source.vectors3) {
  50642. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  50643. }
  50644. // Vector4
  50645. for (name in source.vectors4) {
  50646. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  50647. }
  50648. // Matrix
  50649. for (name in source.matrices) {
  50650. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  50651. }
  50652. // Matrix 3x3
  50653. for (name in source.matrices3x3) {
  50654. material.setMatrix3x3(name, source.matrices3x3[name]);
  50655. }
  50656. // Matrix 2x2
  50657. for (name in source.matrices2x2) {
  50658. material.setMatrix2x2(name, source.matrices2x2[name]);
  50659. }
  50660. // Vector2Array
  50661. for (name in source.vectors2Arrays) {
  50662. material.setArray2(name, source.vectors2Arrays[name]);
  50663. }
  50664. // Vector3Array
  50665. for (name in source.vectors3Arrays) {
  50666. material.setArray3(name, source.vectors3Arrays[name]);
  50667. }
  50668. return material;
  50669. };
  50670. return ShaderMaterial;
  50671. }(BABYLON.Material));
  50672. BABYLON.ShaderMaterial = ShaderMaterial;
  50673. })(BABYLON || (BABYLON = {}));
  50674. //# sourceMappingURL=babylon.shaderMaterial.js.map
  50675. var BABYLON;
  50676. (function (BABYLON) {
  50677. var GroundMesh = /** @class */ (function (_super) {
  50678. __extends(GroundMesh, _super);
  50679. function GroundMesh(name, scene) {
  50680. var _this = _super.call(this, name, scene) || this;
  50681. _this.generateOctree = false;
  50682. return _this;
  50683. }
  50684. GroundMesh.prototype.getClassName = function () {
  50685. return "GroundMesh";
  50686. };
  50687. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  50688. get: function () {
  50689. return Math.min(this._subdivisionsX, this._subdivisionsY);
  50690. },
  50691. enumerable: true,
  50692. configurable: true
  50693. });
  50694. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  50695. get: function () {
  50696. return this._subdivisionsX;
  50697. },
  50698. enumerable: true,
  50699. configurable: true
  50700. });
  50701. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  50702. get: function () {
  50703. return this._subdivisionsY;
  50704. },
  50705. enumerable: true,
  50706. configurable: true
  50707. });
  50708. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  50709. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  50710. this._subdivisionsX = chunksCount;
  50711. this._subdivisionsY = chunksCount;
  50712. this.subdivide(chunksCount);
  50713. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  50714. };
  50715. /**
  50716. * Returns a height (y) value in the Worl system :
  50717. * the ground altitude at the coordinates (x, z) expressed in the World system.
  50718. * Returns the ground y position if (x, z) are outside the ground surface.
  50719. */
  50720. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  50721. var world = this.getWorldMatrix();
  50722. var invMat = BABYLON.Tmp.Matrix[5];
  50723. world.invertToRef(invMat);
  50724. var tmpVect = BABYLON.Tmp.Vector3[8];
  50725. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  50726. x = tmpVect.x;
  50727. z = tmpVect.z;
  50728. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  50729. return this.position.y;
  50730. }
  50731. if (!this._heightQuads || this._heightQuads.length == 0) {
  50732. this._initHeightQuads();
  50733. this._computeHeightQuads();
  50734. }
  50735. var facet = this._getFacetAt(x, z);
  50736. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  50737. // return y in the World system
  50738. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  50739. return tmpVect.y;
  50740. };
  50741. /**
  50742. * Returns a normalized vector (Vector3) orthogonal to the ground
  50743. * at the ground coordinates (x, z) expressed in the World system.
  50744. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  50745. */
  50746. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  50747. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  50748. this.getNormalAtCoordinatesToRef(x, z, normal);
  50749. return normal;
  50750. };
  50751. /**
  50752. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  50753. * at the ground coordinates (x, z) expressed in the World system.
  50754. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  50755. * Returns the GroundMesh.
  50756. */
  50757. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  50758. var world = this.getWorldMatrix();
  50759. var tmpMat = BABYLON.Tmp.Matrix[5];
  50760. world.invertToRef(tmpMat);
  50761. var tmpVect = BABYLON.Tmp.Vector3[8];
  50762. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  50763. x = tmpVect.x;
  50764. z = tmpVect.z;
  50765. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  50766. return this;
  50767. }
  50768. if (!this._heightQuads || this._heightQuads.length == 0) {
  50769. this._initHeightQuads();
  50770. this._computeHeightQuads();
  50771. }
  50772. var facet = this._getFacetAt(x, z);
  50773. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  50774. return this;
  50775. };
  50776. /**
  50777. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  50778. * if the ground has been updated.
  50779. * This can be used in the render loop.
  50780. * Returns the GroundMesh.
  50781. */
  50782. GroundMesh.prototype.updateCoordinateHeights = function () {
  50783. if (!this._heightQuads || this._heightQuads.length == 0) {
  50784. this._initHeightQuads();
  50785. }
  50786. this._computeHeightQuads();
  50787. return this;
  50788. };
  50789. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  50790. GroundMesh.prototype._getFacetAt = function (x, z) {
  50791. // retrieve col and row from x, z coordinates in the ground local system
  50792. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  50793. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  50794. var quad = this._heightQuads[row * this._subdivisionsX + col];
  50795. var facet;
  50796. if (z < quad.slope.x * x + quad.slope.y) {
  50797. facet = quad.facet1;
  50798. }
  50799. else {
  50800. facet = quad.facet2;
  50801. }
  50802. return facet;
  50803. };
  50804. // Creates and populates the heightMap array with "facet" elements :
  50805. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  50806. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  50807. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  50808. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  50809. // Returns the GroundMesh.
  50810. GroundMesh.prototype._initHeightQuads = function () {
  50811. var subdivisionsX = this._subdivisionsX;
  50812. var subdivisionsY = this._subdivisionsY;
  50813. this._heightQuads = new Array();
  50814. for (var row = 0; row < subdivisionsY; row++) {
  50815. for (var col = 0; col < subdivisionsX; col++) {
  50816. 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) };
  50817. this._heightQuads[row * subdivisionsX + col] = quad;
  50818. }
  50819. }
  50820. return this;
  50821. };
  50822. // Compute each quad element values and update the the heightMap array :
  50823. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  50824. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  50825. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  50826. // Returns the GroundMesh.
  50827. GroundMesh.prototype._computeHeightQuads = function () {
  50828. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  50829. if (!positions) {
  50830. return this;
  50831. }
  50832. var v1 = BABYLON.Tmp.Vector3[3];
  50833. var v2 = BABYLON.Tmp.Vector3[2];
  50834. var v3 = BABYLON.Tmp.Vector3[1];
  50835. var v4 = BABYLON.Tmp.Vector3[0];
  50836. var v1v2 = BABYLON.Tmp.Vector3[4];
  50837. var v1v3 = BABYLON.Tmp.Vector3[5];
  50838. var v1v4 = BABYLON.Tmp.Vector3[6];
  50839. var norm1 = BABYLON.Tmp.Vector3[7];
  50840. var norm2 = BABYLON.Tmp.Vector3[8];
  50841. var i = 0;
  50842. var j = 0;
  50843. var k = 0;
  50844. var cd = 0; // 2D slope coefficient : z = cd * x + h
  50845. var h = 0;
  50846. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  50847. var d2 = 0;
  50848. var subdivisionsX = this._subdivisionsX;
  50849. var subdivisionsY = this._subdivisionsY;
  50850. for (var row = 0; row < subdivisionsY; row++) {
  50851. for (var col = 0; col < subdivisionsX; col++) {
  50852. i = col * 3;
  50853. j = row * (subdivisionsX + 1) * 3;
  50854. k = (row + 1) * (subdivisionsX + 1) * 3;
  50855. v1.x = positions[j + i];
  50856. v1.y = positions[j + i + 1];
  50857. v1.z = positions[j + i + 2];
  50858. v2.x = positions[j + i + 3];
  50859. v2.y = positions[j + i + 4];
  50860. v2.z = positions[j + i + 5];
  50861. v3.x = positions[k + i];
  50862. v3.y = positions[k + i + 1];
  50863. v3.z = positions[k + i + 2];
  50864. v4.x = positions[k + i + 3];
  50865. v4.y = positions[k + i + 4];
  50866. v4.z = positions[k + i + 5];
  50867. // 2D slope V1V4
  50868. cd = (v4.z - v1.z) / (v4.x - v1.x);
  50869. h = v1.z - cd * v1.x; // v1 belongs to the slope
  50870. // facet equations :
  50871. // we compute each facet normal vector
  50872. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  50873. // we compute the value d by applying the equation to v1 which belongs to the plane
  50874. // then we store the facet equation in a Vector4
  50875. v2.subtractToRef(v1, v1v2);
  50876. v3.subtractToRef(v1, v1v3);
  50877. v4.subtractToRef(v1, v1v4);
  50878. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  50879. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  50880. norm1.normalize();
  50881. norm2.normalize();
  50882. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  50883. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  50884. var quad = this._heightQuads[row * subdivisionsX + col];
  50885. quad.slope.copyFromFloats(cd, h);
  50886. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  50887. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  50888. }
  50889. }
  50890. return this;
  50891. };
  50892. GroundMesh.prototype.serialize = function (serializationObject) {
  50893. _super.prototype.serialize.call(this, serializationObject);
  50894. serializationObject.subdivisionsX = this._subdivisionsX;
  50895. serializationObject.subdivisionsY = this._subdivisionsY;
  50896. serializationObject.minX = this._minX;
  50897. serializationObject.maxX = this._maxX;
  50898. serializationObject.minZ = this._minZ;
  50899. serializationObject.maxZ = this._maxZ;
  50900. serializationObject.width = this._width;
  50901. serializationObject.height = this._height;
  50902. };
  50903. GroundMesh.Parse = function (parsedMesh, scene) {
  50904. var result = new GroundMesh(parsedMesh.name, scene);
  50905. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  50906. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  50907. result._minX = parsedMesh.minX;
  50908. result._maxX = parsedMesh.maxX;
  50909. result._minZ = parsedMesh.minZ;
  50910. result._maxZ = parsedMesh.maxZ;
  50911. result._width = parsedMesh.width;
  50912. result._height = parsedMesh.height;
  50913. return result;
  50914. };
  50915. return GroundMesh;
  50916. }(BABYLON.Mesh));
  50917. BABYLON.GroundMesh = GroundMesh;
  50918. })(BABYLON || (BABYLON = {}));
  50919. //# sourceMappingURL=babylon.groundMesh.js.map
  50920. var BABYLON;
  50921. (function (BABYLON) {
  50922. /**
  50923. * Creates an instance based on a source mesh.
  50924. */
  50925. var InstancedMesh = /** @class */ (function (_super) {
  50926. __extends(InstancedMesh, _super);
  50927. function InstancedMesh(name, source) {
  50928. var _this = _super.call(this, name, source.getScene()) || this;
  50929. source.instances.push(_this);
  50930. _this._sourceMesh = source;
  50931. _this.position.copyFrom(source.position);
  50932. _this.rotation.copyFrom(source.rotation);
  50933. _this.scaling.copyFrom(source.scaling);
  50934. if (source.rotationQuaternion) {
  50935. _this.rotationQuaternion = source.rotationQuaternion.clone();
  50936. }
  50937. _this.infiniteDistance = source.infiniteDistance;
  50938. _this.setPivotMatrix(source.getPivotMatrix());
  50939. _this.refreshBoundingInfo();
  50940. _this._syncSubMeshes();
  50941. return _this;
  50942. }
  50943. /**
  50944. * Returns the string "InstancedMesh".
  50945. */
  50946. InstancedMesh.prototype.getClassName = function () {
  50947. return "InstancedMesh";
  50948. };
  50949. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  50950. // Methods
  50951. get: function () {
  50952. return this._sourceMesh.receiveShadows;
  50953. },
  50954. enumerable: true,
  50955. configurable: true
  50956. });
  50957. Object.defineProperty(InstancedMesh.prototype, "material", {
  50958. get: function () {
  50959. return this._sourceMesh.material;
  50960. },
  50961. enumerable: true,
  50962. configurable: true
  50963. });
  50964. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  50965. get: function () {
  50966. return this._sourceMesh.visibility;
  50967. },
  50968. enumerable: true,
  50969. configurable: true
  50970. });
  50971. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  50972. get: function () {
  50973. return this._sourceMesh.skeleton;
  50974. },
  50975. enumerable: true,
  50976. configurable: true
  50977. });
  50978. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  50979. get: function () {
  50980. return this._sourceMesh.renderingGroupId;
  50981. },
  50982. enumerable: true,
  50983. configurable: true
  50984. });
  50985. /**
  50986. * Returns the total number of vertices (integer).
  50987. */
  50988. InstancedMesh.prototype.getTotalVertices = function () {
  50989. return this._sourceMesh.getTotalVertices();
  50990. };
  50991. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  50992. get: function () {
  50993. return this._sourceMesh;
  50994. },
  50995. enumerable: true,
  50996. configurable: true
  50997. });
  50998. /**
  50999. * Is this node ready to be used/rendered
  51000. * @return {boolean} is it ready
  51001. */
  51002. InstancedMesh.prototype.isReady = function () {
  51003. return this._sourceMesh.isReady(true);
  51004. };
  51005. /**
  51006. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  51007. */
  51008. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  51009. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  51010. };
  51011. /**
  51012. * Sets the vertex data of the mesh geometry for the requested `kind`.
  51013. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  51014. * The `data` are either a numeric array either a Float32Array.
  51015. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  51016. * 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).
  51017. * Note that a new underlying VertexBuffer object is created each call.
  51018. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  51019. *
  51020. * Possible `kind` values :
  51021. * - BABYLON.VertexBuffer.PositionKind
  51022. * - BABYLON.VertexBuffer.UVKind
  51023. * - BABYLON.VertexBuffer.UV2Kind
  51024. * - BABYLON.VertexBuffer.UV3Kind
  51025. * - BABYLON.VertexBuffer.UV4Kind
  51026. * - BABYLON.VertexBuffer.UV5Kind
  51027. * - BABYLON.VertexBuffer.UV6Kind
  51028. * - BABYLON.VertexBuffer.ColorKind
  51029. * - BABYLON.VertexBuffer.MatricesIndicesKind
  51030. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  51031. * - BABYLON.VertexBuffer.MatricesWeightsKind
  51032. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  51033. *
  51034. * Returns the Mesh.
  51035. */
  51036. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  51037. if (this.sourceMesh) {
  51038. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  51039. }
  51040. return this.sourceMesh;
  51041. };
  51042. /**
  51043. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  51044. * If the mesh has no geometry, it is simply returned as it is.
  51045. * The `data` are either a numeric array either a Float32Array.
  51046. * No new underlying VertexBuffer object is created.
  51047. * 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.
  51048. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  51049. *
  51050. * Possible `kind` values :
  51051. * - BABYLON.VertexBuffer.PositionKind
  51052. * - BABYLON.VertexBuffer.UVKind
  51053. * - BABYLON.VertexBuffer.UV2Kind
  51054. * - BABYLON.VertexBuffer.UV3Kind
  51055. * - BABYLON.VertexBuffer.UV4Kind
  51056. * - BABYLON.VertexBuffer.UV5Kind
  51057. * - BABYLON.VertexBuffer.UV6Kind
  51058. * - BABYLON.VertexBuffer.ColorKind
  51059. * - BABYLON.VertexBuffer.MatricesIndicesKind
  51060. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  51061. * - BABYLON.VertexBuffer.MatricesWeightsKind
  51062. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  51063. *
  51064. * Returns the Mesh.
  51065. */
  51066. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  51067. if (this.sourceMesh) {
  51068. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  51069. }
  51070. return this.sourceMesh;
  51071. };
  51072. /**
  51073. * Sets the mesh indices.
  51074. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  51075. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  51076. * This method creates a new index buffer each call.
  51077. * Returns the Mesh.
  51078. */
  51079. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  51080. if (totalVertices === void 0) { totalVertices = null; }
  51081. if (this.sourceMesh) {
  51082. this.sourceMesh.setIndices(indices, totalVertices);
  51083. }
  51084. return this.sourceMesh;
  51085. };
  51086. /**
  51087. * Boolean : True if the mesh owns the requested kind of data.
  51088. */
  51089. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  51090. return this._sourceMesh.isVerticesDataPresent(kind);
  51091. };
  51092. /**
  51093. * Returns an array of indices (IndicesArray).
  51094. */
  51095. InstancedMesh.prototype.getIndices = function () {
  51096. return this._sourceMesh.getIndices();
  51097. };
  51098. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  51099. get: function () {
  51100. return this._sourceMesh._positions;
  51101. },
  51102. enumerable: true,
  51103. configurable: true
  51104. });
  51105. /**
  51106. * Sets a new updated BoundingInfo to the mesh.
  51107. * Returns the mesh.
  51108. */
  51109. InstancedMesh.prototype.refreshBoundingInfo = function () {
  51110. var meshBB = this._sourceMesh.getBoundingInfo();
  51111. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  51112. this._updateBoundingInfo();
  51113. return this;
  51114. };
  51115. InstancedMesh.prototype._preActivate = function () {
  51116. if (this._currentLOD) {
  51117. this._currentLOD._preActivate();
  51118. }
  51119. return this;
  51120. };
  51121. InstancedMesh.prototype._activate = function (renderId) {
  51122. if (this._currentLOD) {
  51123. this._currentLOD._registerInstanceForRenderId(this, renderId);
  51124. }
  51125. return this;
  51126. };
  51127. /**
  51128. * Returns the current associated LOD AbstractMesh.
  51129. */
  51130. InstancedMesh.prototype.getLOD = function (camera) {
  51131. if (!camera) {
  51132. return this;
  51133. }
  51134. var boundingInfo = this.getBoundingInfo();
  51135. this._currentLOD = this.sourceMesh.getLOD(camera, boundingInfo.boundingSphere);
  51136. if (this._currentLOD === this.sourceMesh) {
  51137. return this;
  51138. }
  51139. return this._currentLOD;
  51140. };
  51141. InstancedMesh.prototype._syncSubMeshes = function () {
  51142. this.releaseSubMeshes();
  51143. if (this._sourceMesh.subMeshes) {
  51144. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  51145. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  51146. }
  51147. }
  51148. return this;
  51149. };
  51150. InstancedMesh.prototype._generatePointsArray = function () {
  51151. return this._sourceMesh._generatePointsArray();
  51152. };
  51153. /**
  51154. * Creates a new InstancedMesh from the current mesh.
  51155. * - name (string) : the cloned mesh name
  51156. * - newParent (optional Node) : the optional Node to parent the clone to.
  51157. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  51158. *
  51159. * Returns the clone.
  51160. */
  51161. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  51162. var result = this._sourceMesh.createInstance(name);
  51163. // Deep copy
  51164. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  51165. // Bounding info
  51166. this.refreshBoundingInfo();
  51167. // Parent
  51168. if (newParent) {
  51169. result.parent = newParent;
  51170. }
  51171. if (!doNotCloneChildren) {
  51172. // Children
  51173. for (var index = 0; index < this.getScene().meshes.length; index++) {
  51174. var mesh = this.getScene().meshes[index];
  51175. if (mesh.parent === this) {
  51176. mesh.clone(mesh.name, result);
  51177. }
  51178. }
  51179. }
  51180. result.computeWorldMatrix(true);
  51181. return result;
  51182. };
  51183. /**
  51184. * Disposes the InstancedMesh.
  51185. * Returns nothing.
  51186. */
  51187. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  51188. // Remove from mesh
  51189. var index = this._sourceMesh.instances.indexOf(this);
  51190. this._sourceMesh.instances.splice(index, 1);
  51191. _super.prototype.dispose.call(this, doNotRecurse);
  51192. };
  51193. return InstancedMesh;
  51194. }(BABYLON.AbstractMesh));
  51195. BABYLON.InstancedMesh = InstancedMesh;
  51196. })(BABYLON || (BABYLON = {}));
  51197. //# sourceMappingURL=babylon.instancedMesh.js.map
  51198. var BABYLON;
  51199. (function (BABYLON) {
  51200. var LinesMesh = /** @class */ (function (_super) {
  51201. __extends(LinesMesh, _super);
  51202. function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor, useVertexAlpha) {
  51203. if (scene === void 0) { scene = null; }
  51204. if (parent === void 0) { parent = null; }
  51205. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  51206. _this.useVertexColor = useVertexColor;
  51207. _this.useVertexAlpha = useVertexAlpha;
  51208. _this.color = new BABYLON.Color3(1, 1, 1);
  51209. _this.alpha = 1;
  51210. if (source) {
  51211. _this.color = source.color.clone();
  51212. _this.alpha = source.alpha;
  51213. _this.useVertexColor = source.useVertexColor;
  51214. _this.useVertexAlpha = source.useVertexAlpha;
  51215. }
  51216. _this._intersectionThreshold = 0.1;
  51217. var defines = [];
  51218. var options = {
  51219. attributes: [BABYLON.VertexBuffer.PositionKind],
  51220. uniforms: ["world", "viewProjection"],
  51221. needAlphaBlending: true,
  51222. defines: defines
  51223. };
  51224. if (useVertexAlpha === false) {
  51225. options.needAlphaBlending = false;
  51226. }
  51227. if (!useVertexColor) {
  51228. options.uniforms.push("color");
  51229. }
  51230. else {
  51231. options.defines.push("#define VERTEXCOLOR");
  51232. options.attributes.push(BABYLON.VertexBuffer.ColorKind);
  51233. }
  51234. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", _this.getScene(), "color", options);
  51235. return _this;
  51236. }
  51237. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  51238. /**
  51239. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  51240. * This margin is expressed in world space coordinates, so its value may vary.
  51241. * Default value is 0.1
  51242. * @returns the intersection Threshold value.
  51243. */
  51244. get: function () {
  51245. return this._intersectionThreshold;
  51246. },
  51247. /**
  51248. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  51249. * This margin is expressed in world space coordinates, so its value may vary.
  51250. * @param value the new threshold to apply
  51251. */
  51252. set: function (value) {
  51253. if (this._intersectionThreshold === value) {
  51254. return;
  51255. }
  51256. this._intersectionThreshold = value;
  51257. if (this.geometry) {
  51258. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  51259. }
  51260. },
  51261. enumerable: true,
  51262. configurable: true
  51263. });
  51264. /**
  51265. * Returns the string "LineMesh"
  51266. */
  51267. LinesMesh.prototype.getClassName = function () {
  51268. return "LinesMesh";
  51269. };
  51270. Object.defineProperty(LinesMesh.prototype, "material", {
  51271. get: function () {
  51272. return this._colorShader;
  51273. },
  51274. set: function (value) {
  51275. // Do nothing
  51276. },
  51277. enumerable: true,
  51278. configurable: true
  51279. });
  51280. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  51281. get: function () {
  51282. return false;
  51283. },
  51284. enumerable: true,
  51285. configurable: true
  51286. });
  51287. LinesMesh.prototype.createInstance = function (name) {
  51288. throw new Error("LinesMeshes do not support createInstance.");
  51289. };
  51290. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  51291. if (!this._geometry) {
  51292. return this;
  51293. }
  51294. // VBOs
  51295. this._geometry._bind(this._colorShader.getEffect());
  51296. // Color
  51297. if (!this.useVertexColor) {
  51298. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  51299. }
  51300. return this;
  51301. };
  51302. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  51303. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  51304. return this;
  51305. }
  51306. var engine = this.getScene().getEngine();
  51307. // Draw order
  51308. engine.drawElementsType(BABYLON.Material.LineListDrawMode, subMesh.indexStart, subMesh.indexCount);
  51309. return this;
  51310. };
  51311. LinesMesh.prototype.dispose = function (doNotRecurse) {
  51312. this._colorShader.dispose();
  51313. _super.prototype.dispose.call(this, doNotRecurse);
  51314. };
  51315. /**
  51316. * Returns a new LineMesh object cloned from the current one.
  51317. */
  51318. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  51319. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  51320. };
  51321. return LinesMesh;
  51322. }(BABYLON.Mesh));
  51323. BABYLON.LinesMesh = LinesMesh;
  51324. })(BABYLON || (BABYLON = {}));
  51325. //# sourceMappingURL=babylon.linesMesh.js.map
  51326. var BABYLON;
  51327. (function (BABYLON) {
  51328. var MeshBuilder = /** @class */ (function () {
  51329. function MeshBuilder() {
  51330. }
  51331. MeshBuilder.updateSideOrientation = function (orientation) {
  51332. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  51333. return BABYLON.Mesh.DOUBLESIDE;
  51334. }
  51335. if (orientation === undefined || orientation === null) {
  51336. return BABYLON.Mesh.FRONTSIDE;
  51337. }
  51338. return orientation;
  51339. };
  51340. /**
  51341. * Creates a box mesh.
  51342. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  51343. * The parameter `size` sets the size (float) of each box side (default 1).
  51344. * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`).
  51345. * 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).
  51346. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  51347. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  51348. * 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).
  51349. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  51350. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  51351. */
  51352. MeshBuilder.CreateBox = function (name, options, scene) {
  51353. if (scene === void 0) { scene = null; }
  51354. var box = new BABYLON.Mesh(name, scene);
  51355. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  51356. box._originalBuilderSideOrientation = options.sideOrientation;
  51357. var vertexData = BABYLON.VertexData.CreateBox(options);
  51358. vertexData.applyToMesh(box, options.updatable);
  51359. return box;
  51360. };
  51361. /**
  51362. * Creates a sphere mesh.
  51363. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  51364. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  51365. * 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`).
  51366. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  51367. * 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
  51368. * 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).
  51369. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  51370. * 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).
  51371. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  51372. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  51373. */
  51374. MeshBuilder.CreateSphere = function (name, options, scene) {
  51375. var sphere = new BABYLON.Mesh(name, scene);
  51376. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  51377. sphere._originalBuilderSideOrientation = options.sideOrientation;
  51378. var vertexData = BABYLON.VertexData.CreateSphere(options);
  51379. vertexData.applyToMesh(sphere, options.updatable);
  51380. return sphere;
  51381. };
  51382. /**
  51383. * Creates a plane polygonal mesh. By default, this is a disc.
  51384. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#disc
  51385. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  51386. * 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.
  51387. * 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
  51388. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  51389. * 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).
  51390. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  51391. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  51392. */
  51393. MeshBuilder.CreateDisc = function (name, options, scene) {
  51394. if (scene === void 0) { scene = null; }
  51395. var disc = new BABYLON.Mesh(name, scene);
  51396. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  51397. disc._originalBuilderSideOrientation = options.sideOrientation;
  51398. var vertexData = BABYLON.VertexData.CreateDisc(options);
  51399. vertexData.applyToMesh(disc, options.updatable);
  51400. return disc;
  51401. };
  51402. /**
  51403. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  51404. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#icosphere
  51405. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  51406. * 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`).
  51407. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  51408. * 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.
  51409. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  51410. * 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).
  51411. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  51412. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  51413. */
  51414. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  51415. var sphere = new BABYLON.Mesh(name, scene);
  51416. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  51417. sphere._originalBuilderSideOrientation = options.sideOrientation;
  51418. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  51419. vertexData.applyToMesh(sphere, options.updatable);
  51420. return sphere;
  51421. };
  51422. ;
  51423. /**
  51424. * Creates a ribbon mesh.
  51425. * 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.
  51426. *
  51427. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  51428. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  51429. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  51430. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  51431. * 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.
  51432. * 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.
  51433. * 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
  51434. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  51435. * 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).
  51436. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  51437. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  51438. * 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.
  51439. * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values.
  51440. * 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
  51441. * if you set `closePath` to `true`, there's one extra vertex per path in the geometry.
  51442. * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time.
  51443. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  51444. */
  51445. MeshBuilder.CreateRibbon = function (name, options, scene) {
  51446. if (scene === void 0) { scene = null; }
  51447. var pathArray = options.pathArray;
  51448. var closeArray = options.closeArray;
  51449. var closePath = options.closePath;
  51450. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  51451. var instance = options.instance;
  51452. var updatable = options.updatable;
  51453. if (instance) {
  51454. // positionFunction : ribbon case
  51455. // only pathArray and sideOrientation parameters are taken into account for positions update
  51456. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  51457. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  51458. var positionFunction = function (positions) {
  51459. var minlg = pathArray[0].length;
  51460. var i = 0;
  51461. var ns = (instance._originalBuilderSideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  51462. for (var si = 1; si <= ns; si++) {
  51463. for (var p = 0; p < pathArray.length; p++) {
  51464. var path = pathArray[p];
  51465. var l = path.length;
  51466. minlg = (minlg < l) ? minlg : l;
  51467. var j = 0;
  51468. while (j < minlg) {
  51469. positions[i] = path[j].x;
  51470. positions[i + 1] = path[j].y;
  51471. positions[i + 2] = path[j].z;
  51472. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  51473. BABYLON.Tmp.Vector3[0].x = path[j].x;
  51474. }
  51475. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  51476. BABYLON.Tmp.Vector3[1].x = path[j].x;
  51477. }
  51478. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  51479. BABYLON.Tmp.Vector3[0].y = path[j].y;
  51480. }
  51481. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  51482. BABYLON.Tmp.Vector3[1].y = path[j].y;
  51483. }
  51484. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  51485. BABYLON.Tmp.Vector3[0].z = path[j].z;
  51486. }
  51487. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  51488. BABYLON.Tmp.Vector3[1].z = path[j].z;
  51489. }
  51490. j++;
  51491. i += 3;
  51492. }
  51493. if (instance._closePath) {
  51494. positions[i] = path[0].x;
  51495. positions[i + 1] = path[0].y;
  51496. positions[i + 2] = path[0].z;
  51497. i += 3;
  51498. }
  51499. }
  51500. }
  51501. };
  51502. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  51503. positionFunction(positions);
  51504. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  51505. instance._boundingInfo.update(instance._worldMatrix);
  51506. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  51507. if (options.colors) {
  51508. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  51509. for (var c = 0; c < options.colors.length; c++) {
  51510. colors[c * 4] = options.colors[c].r;
  51511. colors[c * 4 + 1] = options.colors[c].g;
  51512. colors[c * 4 + 2] = options.colors[c].b;
  51513. colors[c * 4 + 3] = options.colors[c].a;
  51514. }
  51515. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  51516. }
  51517. if (options.uvs) {
  51518. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  51519. for (var i = 0; i < options.uvs.length; i++) {
  51520. uvs[i * 2] = options.uvs[i].x;
  51521. uvs[i * 2 + 1] = options.uvs[i].y;
  51522. }
  51523. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  51524. }
  51525. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  51526. var indices = instance.getIndices();
  51527. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  51528. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  51529. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  51530. if (instance._closePath) {
  51531. var indexFirst = 0;
  51532. var indexLast = 0;
  51533. for (var p = 0; p < pathArray.length; p++) {
  51534. indexFirst = instance._idx[p] * 3;
  51535. if (p + 1 < pathArray.length) {
  51536. indexLast = (instance._idx[p + 1] - 1) * 3;
  51537. }
  51538. else {
  51539. indexLast = normals.length - 3;
  51540. }
  51541. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  51542. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  51543. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  51544. normals[indexLast] = normals[indexFirst];
  51545. normals[indexLast + 1] = normals[indexFirst + 1];
  51546. normals[indexLast + 2] = normals[indexFirst + 2];
  51547. }
  51548. }
  51549. if (!(instance.areNormalsFrozen)) {
  51550. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  51551. }
  51552. }
  51553. return instance;
  51554. }
  51555. else {
  51556. var ribbon = new BABYLON.Mesh(name, scene);
  51557. ribbon._originalBuilderSideOrientation = sideOrientation;
  51558. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  51559. if (closePath) {
  51560. ribbon._idx = vertexData._idx;
  51561. }
  51562. ribbon._closePath = closePath;
  51563. ribbon._closeArray = closeArray;
  51564. vertexData.applyToMesh(ribbon, updatable);
  51565. return ribbon;
  51566. }
  51567. };
  51568. /**
  51569. * Creates a cylinder or a cone mesh.
  51570. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  51571. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  51572. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  51573. * 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.
  51574. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  51575. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  51576. * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  51577. * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  51578. * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  51579. * 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).
  51580. * 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
  51581. * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  51582. * 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
  51583. * 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.
  51584. * If `enclose` is false, a ring surface is one element.
  51585. * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  51586. * 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
  51587. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  51588. * 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).
  51589. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  51590. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  51591. */
  51592. MeshBuilder.CreateCylinder = function (name, options, scene) {
  51593. var cylinder = new BABYLON.Mesh(name, scene);
  51594. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  51595. cylinder._originalBuilderSideOrientation = options.sideOrientation;
  51596. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  51597. vertexData.applyToMesh(cylinder, options.updatable);
  51598. return cylinder;
  51599. };
  51600. /**
  51601. * Creates a torus mesh.
  51602. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  51603. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  51604. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  51605. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  51606. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  51607. * 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).
  51608. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  51609. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  51610. */
  51611. MeshBuilder.CreateTorus = function (name, options, scene) {
  51612. var torus = new BABYLON.Mesh(name, scene);
  51613. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  51614. torus._originalBuilderSideOrientation = options.sideOrientation;
  51615. var vertexData = BABYLON.VertexData.CreateTorus(options);
  51616. vertexData.applyToMesh(torus, options.updatable);
  51617. return torus;
  51618. };
  51619. /**
  51620. * Creates a torus knot mesh.
  51621. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  51622. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  51623. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  51624. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  51625. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  51626. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  51627. * 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).
  51628. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  51629. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  51630. */
  51631. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  51632. var torusKnot = new BABYLON.Mesh(name, scene);
  51633. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  51634. torusKnot._originalBuilderSideOrientation = options.sideOrientation;
  51635. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  51636. vertexData.applyToMesh(torusKnot, options.updatable);
  51637. return torusKnot;
  51638. };
  51639. /**
  51640. * Creates a line system mesh.
  51641. * A line system is a pool of many lines gathered in a single mesh.
  51642. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#linesystem
  51643. * 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.
  51644. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function.
  51645. * The parameter `lines` is an array of lines, each line being an array of successive Vector3.
  51646. * 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
  51647. * The optional parameter `colors` is an array of line colors, each line colors being an array of successive Color4, one per line point.
  51648. * The optional parameter `useVertexAlpha' is to be set to `false` (default `true`) when you don't need the alpha blending (faster).
  51649. * 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
  51650. * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines.
  51651. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  51652. */
  51653. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  51654. var instance = options.instance;
  51655. var lines = options.lines;
  51656. var colors = options.colors;
  51657. if (instance) {
  51658. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  51659. var vertexColor;
  51660. var lineColors;
  51661. if (colors) {
  51662. vertexColor = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  51663. }
  51664. var i = 0;
  51665. var c = 0;
  51666. for (var l = 0; l < lines.length; l++) {
  51667. var points = lines[l];
  51668. for (var p = 0; p < points.length; p++) {
  51669. positions[i] = points[p].x;
  51670. positions[i + 1] = points[p].y;
  51671. positions[i + 2] = points[p].z;
  51672. if (colors && vertexColor) {
  51673. lineColors = colors[l];
  51674. vertexColor[c] = lineColors[p].r;
  51675. vertexColor[c + 1] = lineColors[p].g;
  51676. vertexColor[c + 2] = lineColors[p].b;
  51677. vertexColor[c + 3] = lineColors[p].a;
  51678. c += 4;
  51679. }
  51680. i += 3;
  51681. }
  51682. }
  51683. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  51684. if (colors && vertexColor) {
  51685. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, vertexColor, false, false);
  51686. }
  51687. return instance;
  51688. }
  51689. // line system creation
  51690. var useVertexColor = (colors) ? true : false;
  51691. var lineSystem = new BABYLON.LinesMesh(name, scene, null, undefined, undefined, useVertexColor, options.useVertexAlpha);
  51692. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  51693. vertexData.applyToMesh(lineSystem, options.updatable);
  51694. return lineSystem;
  51695. };
  51696. /**
  51697. * Creates a line mesh.
  51698. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lines
  51699. * 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.
  51700. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  51701. * The parameter `points` is an array successive Vector3.
  51702. * 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
  51703. * The optional parameter `colors` is an array of successive Color4, one per line point.
  51704. * The optional parameter `useVertexAlpha' is to be set to `false` (default `true`) when you don't need alpha blending (faster).
  51705. * When updating an instance, remember that only point positions can change, not the number of points.
  51706. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  51707. */
  51708. MeshBuilder.CreateLines = function (name, options, scene) {
  51709. if (scene === void 0) { scene = null; }
  51710. var colors = (options.colors) ? [options.colors] : null;
  51711. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance, colors: colors, useVertexAlpha: options.useVertexAlpha }, scene);
  51712. return lines;
  51713. };
  51714. /**
  51715. * Creates a dashed line mesh.
  51716. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#dashed-lines
  51717. * 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.
  51718. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  51719. * The parameter `points` is an array successive Vector3.
  51720. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  51721. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  51722. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  51723. * 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
  51724. * When updating an instance, remember that only point positions can change, not the number of points.
  51725. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  51726. */
  51727. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  51728. if (scene === void 0) { scene = null; }
  51729. var points = options.points;
  51730. var instance = options.instance;
  51731. var gapSize = options.gapSize || 1;
  51732. var dashSize = options.dashSize || 3;
  51733. if (instance) {
  51734. var positionFunction = function (positions) {
  51735. var curvect = BABYLON.Vector3.Zero();
  51736. var nbSeg = positions.length / 6;
  51737. var lg = 0;
  51738. var nb = 0;
  51739. var shft = 0;
  51740. var dashshft = 0;
  51741. var curshft = 0;
  51742. var p = 0;
  51743. var i = 0;
  51744. var j = 0;
  51745. for (i = 0; i < points.length - 1; i++) {
  51746. points[i + 1].subtractToRef(points[i], curvect);
  51747. lg += curvect.length();
  51748. }
  51749. shft = lg / nbSeg;
  51750. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  51751. for (i = 0; i < points.length - 1; i++) {
  51752. points[i + 1].subtractToRef(points[i], curvect);
  51753. nb = Math.floor(curvect.length() / shft);
  51754. curvect.normalize();
  51755. j = 0;
  51756. while (j < nb && p < positions.length) {
  51757. curshft = shft * j;
  51758. positions[p] = points[i].x + curshft * curvect.x;
  51759. positions[p + 1] = points[i].y + curshft * curvect.y;
  51760. positions[p + 2] = points[i].z + curshft * curvect.z;
  51761. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  51762. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  51763. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  51764. p += 6;
  51765. j++;
  51766. }
  51767. }
  51768. while (p < positions.length) {
  51769. positions[p] = points[i].x;
  51770. positions[p + 1] = points[i].y;
  51771. positions[p + 2] = points[i].z;
  51772. p += 3;
  51773. }
  51774. };
  51775. instance.updateMeshPositions(positionFunction, false);
  51776. return instance;
  51777. }
  51778. // dashed lines creation
  51779. var dashedLines = new BABYLON.LinesMesh(name, scene);
  51780. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  51781. vertexData.applyToMesh(dashedLines, options.updatable);
  51782. dashedLines.dashSize = dashSize;
  51783. dashedLines.gapSize = gapSize;
  51784. return dashedLines;
  51785. };
  51786. /**
  51787. * Creates an extruded shape mesh.
  51788. * 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.
  51789. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#extruded-shapes
  51790. *
  51791. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  51792. * 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
  51793. * extruded along the Z axis.
  51794. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  51795. * 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.
  51796. * The parameter `scale` (float, default 1) is the value to scale the shape.
  51797. * 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
  51798. * 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
  51799. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  51800. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  51801. * 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).
  51802. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  51803. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  51804. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  51805. */
  51806. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  51807. if (scene === void 0) { scene = null; }
  51808. var path = options.path;
  51809. var shape = options.shape;
  51810. var scale = options.scale || 1;
  51811. var rotation = options.rotation || 0;
  51812. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  51813. var updatable = options.updatable;
  51814. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  51815. var instance = options.instance || null;
  51816. var invertUV = options.invertUV || false;
  51817. 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);
  51818. };
  51819. /**
  51820. * Creates an custom extruded shape mesh.
  51821. * 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.
  51822. * tuto :http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#custom-extruded-shapes
  51823. *
  51824. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  51825. * 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
  51826. * extruded along the Z axis.
  51827. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  51828. * 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
  51829. * and the distance of this point from the begining of the path :
  51830. * ```javascript
  51831. * var rotationFunction = function(i, distance) {
  51832. * // do things
  51833. * return rotationValue; }
  51834. * ```
  51835. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  51836. * 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
  51837. * and the distance of this point from the begining of the path :
  51838. * ```javascript
  51839. * var scaleFunction = function(i, distance) {
  51840. * // do things
  51841. * return scaleValue;}
  51842. * ```
  51843. * It must returns a float value that will be the scale value applied to the shape on each path point.
  51844. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  51845. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  51846. * 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
  51847. * 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
  51848. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  51849. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  51850. * 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).
  51851. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  51852. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  51853. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  51854. */
  51855. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  51856. var path = options.path;
  51857. var shape = options.shape;
  51858. var scaleFunction = options.scaleFunction || (function () { return 1; });
  51859. var rotationFunction = options.rotationFunction || (function () { return 0; });
  51860. var ribbonCloseArray = options.ribbonCloseArray || false;
  51861. var ribbonClosePath = options.ribbonClosePath || false;
  51862. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  51863. var updatable = options.updatable;
  51864. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  51865. var instance = options.instance;
  51866. var invertUV = options.invertUV || false;
  51867. 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);
  51868. };
  51869. /**
  51870. * Creates lathe mesh.
  51871. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  51872. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lathe
  51873. *
  51874. * 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
  51875. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  51876. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  51877. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  51878. * 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.
  51879. * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc".
  51880. * 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
  51881. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  51882. * 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).
  51883. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  51884. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  51885. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  51886. */
  51887. MeshBuilder.CreateLathe = function (name, options, scene) {
  51888. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  51889. var closed = (options.closed === undefined) ? true : options.closed;
  51890. var shape = options.shape;
  51891. var radius = options.radius || 1;
  51892. var tessellation = options.tessellation || 64;
  51893. var updatable = options.updatable;
  51894. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  51895. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  51896. var pi2 = Math.PI * 2;
  51897. var paths = new Array();
  51898. var invertUV = options.invertUV || false;
  51899. var i = 0;
  51900. var p = 0;
  51901. var step = pi2 / tessellation * arc;
  51902. var rotated;
  51903. var path = new Array();
  51904. ;
  51905. for (i = 0; i <= tessellation; i++) {
  51906. var path = [];
  51907. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  51908. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  51909. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  51910. }
  51911. for (p = 0; p < shape.length; p++) {
  51912. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  51913. path.push(rotated);
  51914. }
  51915. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  51916. 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));
  51917. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  51918. }
  51919. paths.push(path);
  51920. }
  51921. // lathe ribbon
  51922. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  51923. return lathe;
  51924. };
  51925. /**
  51926. * Creates a plane mesh.
  51927. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  51928. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  51929. * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`).
  51930. * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane.
  51931. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  51932. * 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).
  51933. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  51934. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  51935. */
  51936. MeshBuilder.CreatePlane = function (name, options, scene) {
  51937. var plane = new BABYLON.Mesh(name, scene);
  51938. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  51939. plane._originalBuilderSideOrientation = options.sideOrientation;
  51940. var vertexData = BABYLON.VertexData.CreatePlane(options);
  51941. vertexData.applyToMesh(plane, options.updatable);
  51942. if (options.sourcePlane) {
  51943. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  51944. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  51945. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  51946. plane.rotate(vectorProduct, product);
  51947. }
  51948. return plane;
  51949. };
  51950. /**
  51951. * Creates a ground mesh.
  51952. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  51953. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  51954. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  51955. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  51956. */
  51957. MeshBuilder.CreateGround = function (name, options, scene) {
  51958. var ground = new BABYLON.GroundMesh(name, scene);
  51959. ground._setReady(false);
  51960. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  51961. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  51962. ground._width = options.width || 1;
  51963. ground._height = options.height || 1;
  51964. ground._maxX = ground._width / 2;
  51965. ground._maxZ = ground._height / 2;
  51966. ground._minX = -ground._maxX;
  51967. ground._minZ = -ground._maxZ;
  51968. var vertexData = BABYLON.VertexData.CreateGround(options);
  51969. vertexData.applyToMesh(ground, options.updatable);
  51970. ground._setReady(true);
  51971. return ground;
  51972. };
  51973. /**
  51974. * Creates a tiled ground mesh.
  51975. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  51976. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  51977. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  51978. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  51979. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  51980. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  51981. * numbers of subdivisions on the ground width and height of each tile.
  51982. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  51983. */
  51984. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  51985. var tiledGround = new BABYLON.Mesh(name, scene);
  51986. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  51987. vertexData.applyToMesh(tiledGround, options.updatable);
  51988. return tiledGround;
  51989. };
  51990. /**
  51991. * Creates a ground mesh from a height map.
  51992. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  51993. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  51994. * The parameter `url` sets the URL of the height map image resource.
  51995. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  51996. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  51997. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  51998. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  51999. * 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.
  52000. * 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).
  52001. * This function is passed the newly built mesh :
  52002. * ```javascript
  52003. * function(mesh) { // do things
  52004. * return; }
  52005. * ```
  52006. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  52007. */
  52008. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  52009. var width = options.width || 10.0;
  52010. var height = options.height || 10.0;
  52011. var subdivisions = options.subdivisions || 1 | 0;
  52012. var minHeight = options.minHeight || 0.0;
  52013. var maxHeight = options.maxHeight || 1.0;
  52014. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  52015. var updatable = options.updatable;
  52016. var onReady = options.onReady;
  52017. var ground = new BABYLON.GroundMesh(name, scene);
  52018. ground._subdivisionsX = subdivisions;
  52019. ground._subdivisionsY = subdivisions;
  52020. ground._width = width;
  52021. ground._height = height;
  52022. ground._maxX = ground._width / 2.0;
  52023. ground._maxZ = ground._height / 2.0;
  52024. ground._minX = -ground._maxX;
  52025. ground._minZ = -ground._maxZ;
  52026. ground._setReady(false);
  52027. var onload = function (img) {
  52028. // Getting height map data
  52029. var canvas = document.createElement("canvas");
  52030. var context = canvas.getContext("2d");
  52031. if (!context) {
  52032. throw new Error("Unable to get 2d context for CreateGroundFromHeightMap");
  52033. }
  52034. if (scene.isDisposed) {
  52035. return;
  52036. }
  52037. var bufferWidth = img.width;
  52038. var bufferHeight = img.height;
  52039. canvas.width = bufferWidth;
  52040. canvas.height = bufferHeight;
  52041. context.drawImage(img, 0, 0);
  52042. // Create VertexData from map data
  52043. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  52044. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  52045. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  52046. width: width, height: height,
  52047. subdivisions: subdivisions,
  52048. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  52049. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  52050. });
  52051. vertexData.applyToMesh(ground, updatable);
  52052. ground._setReady(true);
  52053. //execute ready callback, if set
  52054. if (onReady) {
  52055. onReady(ground);
  52056. }
  52057. };
  52058. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  52059. return ground;
  52060. };
  52061. /**
  52062. * Creates a polygon mesh.
  52063. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  52064. * 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.
  52065. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  52066. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  52067. * 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).
  52068. * Remember you can only change the shape positions, not their number when updating a polygon.
  52069. */
  52070. MeshBuilder.CreatePolygon = function (name, options, scene) {
  52071. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  52072. var shape = options.shape;
  52073. var holes = options.holes || [];
  52074. var depth = options.depth || 0;
  52075. var contours = [];
  52076. var hole = [];
  52077. for (var i = 0; i < shape.length; i++) {
  52078. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  52079. }
  52080. var epsilon = 0.00000001;
  52081. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  52082. contours.pop();
  52083. }
  52084. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  52085. for (var hNb = 0; hNb < holes.length; hNb++) {
  52086. hole = [];
  52087. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  52088. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  52089. }
  52090. polygonTriangulation.addHole(hole);
  52091. }
  52092. var polygon = polygonTriangulation.build(options.updatable, depth);
  52093. polygon._originalBuilderSideOrientation = options.sideOrientation;
  52094. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  52095. vertexData.applyToMesh(polygon, options.updatable);
  52096. return polygon;
  52097. };
  52098. ;
  52099. /**
  52100. * Creates an extruded polygon mesh, with depth in the Y direction.
  52101. * 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).
  52102. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  52103. */
  52104. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  52105. return MeshBuilder.CreatePolygon(name, options, scene);
  52106. };
  52107. ;
  52108. /**
  52109. * Creates a tube mesh.
  52110. * 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.
  52111. *
  52112. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  52113. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  52114. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  52115. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  52116. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  52117. * 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.
  52118. * It must return a radius value (positive float) :
  52119. * ```javascript
  52120. * var radiusFunction = function(i, distance) {
  52121. * // do things
  52122. * return radius; }
  52123. * ```
  52124. * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc.
  52125. * 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
  52126. * 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
  52127. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  52128. * 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).
  52129. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  52130. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  52131. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  52132. */
  52133. MeshBuilder.CreateTube = function (name, options, scene) {
  52134. var path = options.path;
  52135. var instance = options.instance;
  52136. var radius = 1.0;
  52137. if (instance) {
  52138. radius = instance.radius;
  52139. }
  52140. if (options.radius !== undefined) {
  52141. radius = options.radius;
  52142. }
  52143. ;
  52144. var tessellation = options.tessellation || 64 | 0;
  52145. var radiusFunction = options.radiusFunction || null;
  52146. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  52147. var invertUV = options.invertUV || false;
  52148. var updatable = options.updatable;
  52149. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  52150. options.arc = options.arc && (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  52151. // tube geometry
  52152. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  52153. var tangents = path3D.getTangents();
  52154. var normals = path3D.getNormals();
  52155. var distances = path3D.getDistances();
  52156. var pi2 = Math.PI * 2;
  52157. var step = pi2 / tessellation * arc;
  52158. var returnRadius = function () { return radius; };
  52159. var radiusFunctionFinal = radiusFunction || returnRadius;
  52160. var circlePath;
  52161. var rad;
  52162. var normal;
  52163. var rotated;
  52164. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  52165. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  52166. for (var i = 0; i < path.length; i++) {
  52167. rad = radiusFunctionFinal(i, distances[i]); // current radius
  52168. circlePath = Array(); // current circle array
  52169. normal = normals[i]; // current normal
  52170. for (var t = 0; t < tessellation; t++) {
  52171. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  52172. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  52173. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  52174. rotated.scaleInPlace(rad).addInPlace(path[i]);
  52175. circlePath[t] = rotated;
  52176. }
  52177. circlePaths[index] = circlePath;
  52178. index++;
  52179. }
  52180. // cap
  52181. var capPath = function (nbPoints, pathIndex) {
  52182. var pointCap = Array();
  52183. for (var i = 0; i < nbPoints; i++) {
  52184. pointCap.push(path[pathIndex]);
  52185. }
  52186. return pointCap;
  52187. };
  52188. switch (cap) {
  52189. case BABYLON.Mesh.NO_CAP:
  52190. break;
  52191. case BABYLON.Mesh.CAP_START:
  52192. circlePaths[0] = capPath(tessellation, 0);
  52193. circlePaths[1] = circlePaths[2].slice(0);
  52194. break;
  52195. case BABYLON.Mesh.CAP_END:
  52196. circlePaths[index] = circlePaths[index - 1].slice(0);
  52197. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  52198. break;
  52199. case BABYLON.Mesh.CAP_ALL:
  52200. circlePaths[0] = capPath(tessellation, 0);
  52201. circlePaths[1] = circlePaths[2].slice(0);
  52202. circlePaths[index] = circlePaths[index - 1].slice(0);
  52203. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  52204. break;
  52205. default:
  52206. break;
  52207. }
  52208. return circlePaths;
  52209. };
  52210. var path3D;
  52211. var pathArray;
  52212. if (instance) {
  52213. var arc = options.arc || instance.arc;
  52214. path3D = (instance.path3D).update(path);
  52215. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  52216. instance = MeshBuilder.CreateRibbon("", { pathArray: pathArray, instance: instance });
  52217. instance.path3D = path3D;
  52218. instance.pathArray = pathArray;
  52219. instance.arc = arc;
  52220. instance.radius = radius;
  52221. return instance;
  52222. }
  52223. // tube creation
  52224. path3D = new BABYLON.Path3D(path);
  52225. var newPathArray = new Array();
  52226. cap = (cap < 0 || cap > 3) ? 0 : cap;
  52227. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  52228. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  52229. tube.pathArray = pathArray;
  52230. tube.path3D = path3D;
  52231. tube.tessellation = tessellation;
  52232. tube.cap = cap;
  52233. tube.arc = options.arc;
  52234. tube.radius = radius;
  52235. return tube;
  52236. };
  52237. /**
  52238. * Creates a polyhedron mesh.
  52239. *
  52240. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#polyhedron
  52241. * 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
  52242. * to choose the wanted type.
  52243. * The parameter `size` (positive float, default 1) sets the polygon size.
  52244. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  52245. * 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`.
  52246. * 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
  52247. * 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)`).
  52248. * 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
  52249. * 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.
  52250. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  52251. * 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).
  52252. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  52253. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  52254. */
  52255. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  52256. var polyhedron = new BABYLON.Mesh(name, scene);
  52257. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  52258. polyhedron._originalBuilderSideOrientation = options.sideOrientation;
  52259. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  52260. vertexData.applyToMesh(polyhedron, options.updatable);
  52261. return polyhedron;
  52262. };
  52263. /**
  52264. * Creates a decal mesh.
  52265. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#decals
  52266. * 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.
  52267. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  52268. * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates.
  52269. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  52270. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  52271. */
  52272. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  52273. var indices = sourceMesh.getIndices();
  52274. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  52275. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  52276. var position = options.position || BABYLON.Vector3.Zero();
  52277. var normal = options.normal || BABYLON.Vector3.Up();
  52278. var size = options.size || BABYLON.Vector3.One();
  52279. var angle = options.angle || 0;
  52280. // Getting correct rotation
  52281. if (!normal) {
  52282. var target = new BABYLON.Vector3(0, 0, 1);
  52283. var camera = sourceMesh.getScene().activeCamera;
  52284. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  52285. normal = camera.globalPosition.subtract(cameraWorldTarget);
  52286. }
  52287. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  52288. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  52289. var pitch = Math.atan2(normal.y, len);
  52290. // Matrix
  52291. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  52292. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  52293. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  52294. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  52295. var vertexData = new BABYLON.VertexData();
  52296. vertexData.indices = [];
  52297. vertexData.positions = [];
  52298. vertexData.normals = [];
  52299. vertexData.uvs = [];
  52300. var currentVertexDataIndex = 0;
  52301. var extractDecalVector3 = function (indexId) {
  52302. var result = new BABYLON.PositionNormalVertex();
  52303. if (!indices || !positions || !normals) {
  52304. return result;
  52305. }
  52306. var vertexId = indices[indexId];
  52307. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  52308. // Send vector to decal local world
  52309. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  52310. // Get normal
  52311. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  52312. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  52313. return result;
  52314. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  52315. var clip = function (vertices, axis) {
  52316. if (vertices.length === 0) {
  52317. return vertices;
  52318. }
  52319. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  52320. var clipVertices = function (v0, v1) {
  52321. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  52322. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  52323. };
  52324. var result = new Array();
  52325. for (var index = 0; index < vertices.length; index += 3) {
  52326. var v1Out;
  52327. var v2Out;
  52328. var v3Out;
  52329. var total = 0;
  52330. var nV1 = null;
  52331. var nV2 = null;
  52332. var nV3 = null;
  52333. var nV4 = null;
  52334. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  52335. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  52336. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  52337. v1Out = d1 > 0;
  52338. v2Out = d2 > 0;
  52339. v3Out = d3 > 0;
  52340. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  52341. switch (total) {
  52342. case 0:
  52343. result.push(vertices[index]);
  52344. result.push(vertices[index + 1]);
  52345. result.push(vertices[index + 2]);
  52346. break;
  52347. case 1:
  52348. if (v1Out) {
  52349. nV1 = vertices[index + 1];
  52350. nV2 = vertices[index + 2];
  52351. nV3 = clipVertices(vertices[index], nV1);
  52352. nV4 = clipVertices(vertices[index], nV2);
  52353. }
  52354. if (v2Out) {
  52355. nV1 = vertices[index];
  52356. nV2 = vertices[index + 2];
  52357. nV3 = clipVertices(vertices[index + 1], nV1);
  52358. nV4 = clipVertices(vertices[index + 1], nV2);
  52359. result.push(nV3);
  52360. result.push(nV2.clone());
  52361. result.push(nV1.clone());
  52362. result.push(nV2.clone());
  52363. result.push(nV3.clone());
  52364. result.push(nV4);
  52365. break;
  52366. }
  52367. if (v3Out) {
  52368. nV1 = vertices[index];
  52369. nV2 = vertices[index + 1];
  52370. nV3 = clipVertices(vertices[index + 2], nV1);
  52371. nV4 = clipVertices(vertices[index + 2], nV2);
  52372. }
  52373. if (nV1 && nV2 && nV3 && nV4) {
  52374. result.push(nV1.clone());
  52375. result.push(nV2.clone());
  52376. result.push(nV3);
  52377. result.push(nV4);
  52378. result.push(nV3.clone());
  52379. result.push(nV2.clone());
  52380. }
  52381. break;
  52382. case 2:
  52383. if (!v1Out) {
  52384. nV1 = vertices[index].clone();
  52385. nV2 = clipVertices(nV1, vertices[index + 1]);
  52386. nV3 = clipVertices(nV1, vertices[index + 2]);
  52387. result.push(nV1);
  52388. result.push(nV2);
  52389. result.push(nV3);
  52390. }
  52391. if (!v2Out) {
  52392. nV1 = vertices[index + 1].clone();
  52393. nV2 = clipVertices(nV1, vertices[index + 2]);
  52394. nV3 = clipVertices(nV1, vertices[index]);
  52395. result.push(nV1);
  52396. result.push(nV2);
  52397. result.push(nV3);
  52398. }
  52399. if (!v3Out) {
  52400. nV1 = vertices[index + 2].clone();
  52401. nV2 = clipVertices(nV1, vertices[index]);
  52402. nV3 = clipVertices(nV1, vertices[index + 1]);
  52403. result.push(nV1);
  52404. result.push(nV2);
  52405. result.push(nV3);
  52406. }
  52407. break;
  52408. case 3:
  52409. break;
  52410. }
  52411. }
  52412. return result;
  52413. };
  52414. for (var index = 0; index < indices.length; index += 3) {
  52415. var faceVertices = new Array();
  52416. faceVertices.push(extractDecalVector3(index));
  52417. faceVertices.push(extractDecalVector3(index + 1));
  52418. faceVertices.push(extractDecalVector3(index + 2));
  52419. // Clip
  52420. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  52421. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  52422. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  52423. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  52424. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  52425. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  52426. if (faceVertices.length === 0) {
  52427. continue;
  52428. }
  52429. // Add UVs and get back to world
  52430. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  52431. var vertex = faceVertices[vIndex];
  52432. //TODO check for Int32Array | Uint32Array | Uint16Array
  52433. vertexData.indices.push(currentVertexDataIndex);
  52434. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  52435. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  52436. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  52437. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  52438. currentVertexDataIndex++;
  52439. }
  52440. }
  52441. // Return mesh
  52442. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  52443. vertexData.applyToMesh(decal);
  52444. decal.position = position.clone();
  52445. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  52446. return decal;
  52447. };
  52448. // Privates
  52449. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  52450. // extrusion geometry
  52451. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  52452. var tangents = path3D.getTangents();
  52453. var normals = path3D.getNormals();
  52454. var binormals = path3D.getBinormals();
  52455. var distances = path3D.getDistances();
  52456. var angle = 0;
  52457. var returnScale = function () { return scale !== null ? scale : 1; };
  52458. var returnRotation = function () { return rotation !== null ? rotation : 0; };
  52459. var rotate = custom && rotateFunction ? rotateFunction : returnRotation;
  52460. var scl = custom && scaleFunction ? scaleFunction : returnScale;
  52461. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  52462. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  52463. for (var i = 0; i < curve.length; i++) {
  52464. var shapePath = new Array();
  52465. var angleStep = rotate(i, distances[i]);
  52466. var scaleRatio = scl(i, distances[i]);
  52467. for (var p = 0; p < shape.length; p++) {
  52468. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  52469. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  52470. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  52471. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  52472. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  52473. shapePath[p] = rotated;
  52474. }
  52475. shapePaths[index] = shapePath;
  52476. angle += angleStep;
  52477. index++;
  52478. }
  52479. // cap
  52480. var capPath = function (shapePath) {
  52481. var pointCap = Array();
  52482. var barycenter = BABYLON.Vector3.Zero();
  52483. var i;
  52484. for (i = 0; i < shapePath.length; i++) {
  52485. barycenter.addInPlace(shapePath[i]);
  52486. }
  52487. barycenter.scaleInPlace(1.0 / shapePath.length);
  52488. for (i = 0; i < shapePath.length; i++) {
  52489. pointCap.push(barycenter);
  52490. }
  52491. return pointCap;
  52492. };
  52493. switch (cap) {
  52494. case BABYLON.Mesh.NO_CAP:
  52495. break;
  52496. case BABYLON.Mesh.CAP_START:
  52497. shapePaths[0] = capPath(shapePaths[2]);
  52498. shapePaths[1] = shapePaths[2];
  52499. break;
  52500. case BABYLON.Mesh.CAP_END:
  52501. shapePaths[index] = shapePaths[index - 1];
  52502. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  52503. break;
  52504. case BABYLON.Mesh.CAP_ALL:
  52505. shapePaths[0] = capPath(shapePaths[2]);
  52506. shapePaths[1] = shapePaths[2];
  52507. shapePaths[index] = shapePaths[index - 1];
  52508. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  52509. break;
  52510. default:
  52511. break;
  52512. }
  52513. return shapePaths;
  52514. };
  52515. var path3D;
  52516. var pathArray;
  52517. if (instance) {
  52518. path3D = (instance.path3D).update(curve);
  52519. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  52520. instance = BABYLON.Mesh.CreateRibbon("", pathArray, false, false, 0, scene || undefined, false, 0, instance);
  52521. return instance;
  52522. }
  52523. // extruded shape creation
  52524. path3D = new BABYLON.Path3D(curve);
  52525. var newShapePaths = new Array();
  52526. cap = (cap < 0 || cap > 3) ? 0 : cap;
  52527. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  52528. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs || undefined, backUVs: backUVs || undefined }, scene);
  52529. extrudedGeneric.pathArray = pathArray;
  52530. extrudedGeneric.path3D = path3D;
  52531. extrudedGeneric.cap = cap;
  52532. return extrudedGeneric;
  52533. };
  52534. return MeshBuilder;
  52535. }());
  52536. BABYLON.MeshBuilder = MeshBuilder;
  52537. })(BABYLON || (BABYLON = {}));
  52538. //# sourceMappingURL=babylon.meshBuilder.js.map
  52539. var BABYLON;
  52540. (function (BABYLON) {
  52541. var AudioEngine = /** @class */ (function () {
  52542. function AudioEngine() {
  52543. this._audioContext = null;
  52544. this._audioContextInitialized = false;
  52545. this.canUseWebAudio = false;
  52546. this.WarnedWebAudioUnsupported = false;
  52547. this.unlocked = false;
  52548. this.isMP3supported = false;
  52549. this.isOGGsupported = false;
  52550. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  52551. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  52552. this.canUseWebAudio = true;
  52553. }
  52554. var audioElem = document.createElement('audio');
  52555. try {
  52556. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  52557. this.isMP3supported = true;
  52558. }
  52559. }
  52560. catch (e) {
  52561. // protect error during capability check.
  52562. }
  52563. try {
  52564. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  52565. this.isOGGsupported = true;
  52566. }
  52567. }
  52568. catch (e) {
  52569. // protect error during capability check.
  52570. }
  52571. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  52572. this._unlockiOSaudio();
  52573. }
  52574. else {
  52575. this.unlocked = true;
  52576. }
  52577. }
  52578. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  52579. get: function () {
  52580. if (!this._audioContextInitialized) {
  52581. this._initializeAudioContext();
  52582. }
  52583. return this._audioContext;
  52584. },
  52585. enumerable: true,
  52586. configurable: true
  52587. });
  52588. AudioEngine.prototype._unlockiOSaudio = function () {
  52589. var _this = this;
  52590. var unlockaudio = function () {
  52591. if (!_this.audioContext) {
  52592. return;
  52593. }
  52594. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  52595. var source = _this.audioContext.createBufferSource();
  52596. source.buffer = buffer;
  52597. source.connect(_this.audioContext.destination);
  52598. source.start(0);
  52599. setTimeout(function () {
  52600. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  52601. _this.unlocked = true;
  52602. window.removeEventListener('touchend', unlockaudio, false);
  52603. if (_this.onAudioUnlocked) {
  52604. _this.onAudioUnlocked();
  52605. }
  52606. }
  52607. }, 0);
  52608. };
  52609. window.addEventListener('touchend', unlockaudio, false);
  52610. };
  52611. AudioEngine.prototype._initializeAudioContext = function () {
  52612. try {
  52613. if (this.canUseWebAudio) {
  52614. this._audioContext = new AudioContext();
  52615. // create a global volume gain node
  52616. this.masterGain = this._audioContext.createGain();
  52617. this.masterGain.gain.value = 1;
  52618. this.masterGain.connect(this._audioContext.destination);
  52619. this._audioContextInitialized = true;
  52620. }
  52621. }
  52622. catch (e) {
  52623. this.canUseWebAudio = false;
  52624. BABYLON.Tools.Error("Web Audio: " + e.message);
  52625. }
  52626. };
  52627. AudioEngine.prototype.dispose = function () {
  52628. if (this.canUseWebAudio && this._audioContextInitialized) {
  52629. if (this._connectedAnalyser && this._audioContext) {
  52630. this._connectedAnalyser.stopDebugCanvas();
  52631. this._connectedAnalyser.dispose();
  52632. this.masterGain.disconnect();
  52633. this.masterGain.connect(this._audioContext.destination);
  52634. this._connectedAnalyser = null;
  52635. }
  52636. this.masterGain.gain.value = 1;
  52637. }
  52638. this.WarnedWebAudioUnsupported = false;
  52639. };
  52640. AudioEngine.prototype.getGlobalVolume = function () {
  52641. if (this.canUseWebAudio && this._audioContextInitialized) {
  52642. return this.masterGain.gain.value;
  52643. }
  52644. else {
  52645. return -1;
  52646. }
  52647. };
  52648. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  52649. if (this.canUseWebAudio && this._audioContextInitialized) {
  52650. this.masterGain.gain.value = newVolume;
  52651. }
  52652. };
  52653. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  52654. if (this._connectedAnalyser) {
  52655. this._connectedAnalyser.stopDebugCanvas();
  52656. }
  52657. if (this.canUseWebAudio && this._audioContextInitialized && this._audioContext) {
  52658. this._connectedAnalyser = analyser;
  52659. this.masterGain.disconnect();
  52660. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  52661. }
  52662. };
  52663. return AudioEngine;
  52664. }());
  52665. BABYLON.AudioEngine = AudioEngine;
  52666. })(BABYLON || (BABYLON = {}));
  52667. //# sourceMappingURL=babylon.audioEngine.js.map
  52668. var BABYLON;
  52669. (function (BABYLON) {
  52670. var Sound = /** @class */ (function () {
  52671. /**
  52672. * Create a sound and attach it to a scene
  52673. * @param name Name of your sound
  52674. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  52675. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  52676. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  52677. */
  52678. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  52679. if (readyToPlayCallback === void 0) { readyToPlayCallback = null; }
  52680. var _this = this;
  52681. this.autoplay = false;
  52682. this.loop = false;
  52683. this.useCustomAttenuation = false;
  52684. this.spatialSound = false;
  52685. this.refDistance = 1;
  52686. this.rolloffFactor = 1;
  52687. this.maxDistance = 100;
  52688. this.distanceModel = "linear";
  52689. this._panningModel = "equalpower";
  52690. this._playbackRate = 1;
  52691. this._streaming = false;
  52692. this._startTime = 0;
  52693. this._startOffset = 0;
  52694. this._position = BABYLON.Vector3.Zero();
  52695. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  52696. this._volume = 1;
  52697. this._isReadyToPlay = false;
  52698. this.isPlaying = false;
  52699. this.isPaused = false;
  52700. this._isDirectional = false;
  52701. // Used if you'd like to create a directional sound.
  52702. // If not set, the sound will be omnidirectional
  52703. this._coneInnerAngle = 360;
  52704. this._coneOuterAngle = 360;
  52705. this._coneOuterGain = 0;
  52706. this._isOutputConnected = false;
  52707. this._urlType = "Unknown";
  52708. this.name = name;
  52709. this._scene = scene;
  52710. this._readyToPlayCallback = readyToPlayCallback;
  52711. // Default custom attenuation function is a linear attenuation
  52712. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  52713. if (currentDistance < maxDistance) {
  52714. return currentVolume * (1 - currentDistance / maxDistance);
  52715. }
  52716. else {
  52717. return 0;
  52718. }
  52719. };
  52720. if (options) {
  52721. this.autoplay = options.autoplay || false;
  52722. this.loop = options.loop || false;
  52723. // if volume === 0, we need another way to check this option
  52724. if (options.volume !== undefined) {
  52725. this._volume = options.volume;
  52726. }
  52727. this.spatialSound = options.spatialSound || false;
  52728. this.maxDistance = options.maxDistance || 100;
  52729. this.useCustomAttenuation = options.useCustomAttenuation || false;
  52730. this.rolloffFactor = options.rolloffFactor || 1;
  52731. this.refDistance = options.refDistance || 1;
  52732. this.distanceModel = options.distanceModel || "linear";
  52733. this._playbackRate = options.playbackRate || 1;
  52734. this._streaming = options.streaming || false;
  52735. }
  52736. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  52737. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  52738. this._soundGain.gain.value = this._volume;
  52739. this._inputAudioNode = this._soundGain;
  52740. this._ouputAudioNode = this._soundGain;
  52741. if (this.spatialSound) {
  52742. this._createSpatialParameters();
  52743. }
  52744. this._scene.mainSoundTrack.AddSound(this);
  52745. var validParameter = true;
  52746. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  52747. if (urlOrArrayBuffer) {
  52748. if (typeof (urlOrArrayBuffer) === "string")
  52749. this._urlType = "String";
  52750. if (Array.isArray(urlOrArrayBuffer))
  52751. this._urlType = "Array";
  52752. if (urlOrArrayBuffer instanceof ArrayBuffer)
  52753. this._urlType = "ArrayBuffer";
  52754. var urls = [];
  52755. var codecSupportedFound = false;
  52756. switch (this._urlType) {
  52757. case "ArrayBuffer":
  52758. if (urlOrArrayBuffer.byteLength > 0) {
  52759. codecSupportedFound = true;
  52760. this._soundLoaded(urlOrArrayBuffer);
  52761. }
  52762. break;
  52763. case "String":
  52764. urls.push(urlOrArrayBuffer);
  52765. case "Array":
  52766. if (urls.length === 0)
  52767. urls = urlOrArrayBuffer;
  52768. // If we found a supported format, we load it immediately and stop the loop
  52769. for (var i = 0; i < urls.length; i++) {
  52770. var url = urls[i];
  52771. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  52772. codecSupportedFound = true;
  52773. }
  52774. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  52775. codecSupportedFound = true;
  52776. }
  52777. if (url.indexOf(".wav", url.length - 4) !== -1) {
  52778. codecSupportedFound = true;
  52779. }
  52780. if (url.indexOf("blob:") !== -1) {
  52781. codecSupportedFound = true;
  52782. }
  52783. if (codecSupportedFound) {
  52784. // Loading sound using XHR2
  52785. if (!this._streaming) {
  52786. this._scene._loadFile(url, function (data) { _this._soundLoaded(data); }, undefined, true, true);
  52787. }
  52788. else {
  52789. this._htmlAudioElement = new Audio(url);
  52790. this._htmlAudioElement.controls = false;
  52791. this._htmlAudioElement.loop = this.loop;
  52792. BABYLON.Tools.SetCorsBehavior(url, this._htmlAudioElement);
  52793. this._htmlAudioElement.preload = "auto";
  52794. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  52795. _this._isReadyToPlay = true;
  52796. if (_this.autoplay) {
  52797. _this.play();
  52798. }
  52799. if (_this._readyToPlayCallback) {
  52800. _this._readyToPlayCallback();
  52801. }
  52802. });
  52803. document.body.appendChild(this._htmlAudioElement);
  52804. }
  52805. break;
  52806. }
  52807. }
  52808. break;
  52809. default:
  52810. validParameter = false;
  52811. break;
  52812. }
  52813. if (!validParameter) {
  52814. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  52815. }
  52816. else {
  52817. if (!codecSupportedFound) {
  52818. this._isReadyToPlay = true;
  52819. // Simulating a ready to play event to avoid breaking code path
  52820. if (this._readyToPlayCallback) {
  52821. window.setTimeout(function () {
  52822. if (_this._readyToPlayCallback) {
  52823. _this._readyToPlayCallback();
  52824. }
  52825. }, 1000);
  52826. }
  52827. }
  52828. }
  52829. }
  52830. }
  52831. else {
  52832. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  52833. this._scene.mainSoundTrack.AddSound(this);
  52834. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  52835. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  52836. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  52837. }
  52838. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  52839. if (this._readyToPlayCallback) {
  52840. window.setTimeout(function () {
  52841. if (_this._readyToPlayCallback) {
  52842. _this._readyToPlayCallback();
  52843. }
  52844. }, 1000);
  52845. }
  52846. }
  52847. }
  52848. Sound.prototype.dispose = function () {
  52849. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  52850. if (this.isPlaying) {
  52851. this.stop();
  52852. }
  52853. this._isReadyToPlay = false;
  52854. if (this.soundTrackId === -1) {
  52855. this._scene.mainSoundTrack.RemoveSound(this);
  52856. }
  52857. else {
  52858. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  52859. }
  52860. if (this._soundGain) {
  52861. this._soundGain.disconnect();
  52862. this._soundGain = null;
  52863. }
  52864. if (this._soundPanner) {
  52865. this._soundPanner.disconnect();
  52866. this._soundPanner = null;
  52867. }
  52868. if (this._soundSource) {
  52869. this._soundSource.disconnect();
  52870. this._soundSource = null;
  52871. }
  52872. this._audioBuffer = null;
  52873. if (this._htmlAudioElement) {
  52874. this._htmlAudioElement.pause();
  52875. this._htmlAudioElement.src = "";
  52876. document.body.removeChild(this._htmlAudioElement);
  52877. }
  52878. if (this._connectedMesh && this._registerFunc) {
  52879. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  52880. this._connectedMesh = null;
  52881. }
  52882. }
  52883. };
  52884. Sound.prototype.isReady = function () {
  52885. return this._isReadyToPlay;
  52886. };
  52887. Sound.prototype._soundLoaded = function (audioData) {
  52888. var _this = this;
  52889. if (!BABYLON.Engine.audioEngine.audioContext) {
  52890. return;
  52891. }
  52892. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  52893. _this._audioBuffer = buffer;
  52894. _this._isReadyToPlay = true;
  52895. if (_this.autoplay) {
  52896. _this.play();
  52897. }
  52898. if (_this._readyToPlayCallback) {
  52899. _this._readyToPlayCallback();
  52900. }
  52901. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  52902. };
  52903. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  52904. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  52905. this._audioBuffer = audioBuffer;
  52906. this._isReadyToPlay = true;
  52907. }
  52908. };
  52909. Sound.prototype.updateOptions = function (options) {
  52910. if (options) {
  52911. this.loop = options.loop || this.loop;
  52912. this.maxDistance = options.maxDistance || this.maxDistance;
  52913. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  52914. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  52915. this.refDistance = options.refDistance || this.refDistance;
  52916. this.distanceModel = options.distanceModel || this.distanceModel;
  52917. this._playbackRate = options.playbackRate || this._playbackRate;
  52918. this._updateSpatialParameters();
  52919. if (this.isPlaying) {
  52920. if (this._streaming) {
  52921. this._htmlAudioElement.playbackRate = this._playbackRate;
  52922. }
  52923. else {
  52924. if (this._soundSource) {
  52925. this._soundSource.playbackRate.value = this._playbackRate;
  52926. }
  52927. }
  52928. }
  52929. }
  52930. };
  52931. Sound.prototype._createSpatialParameters = function () {
  52932. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  52933. if (this._scene.headphone) {
  52934. this._panningModel = "HRTF";
  52935. }
  52936. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  52937. this._updateSpatialParameters();
  52938. this._soundPanner.connect(this._ouputAudioNode);
  52939. this._inputAudioNode = this._soundPanner;
  52940. }
  52941. };
  52942. Sound.prototype._updateSpatialParameters = function () {
  52943. if (this.spatialSound && this._soundPanner) {
  52944. if (this.useCustomAttenuation) {
  52945. // Tricks to disable in a way embedded Web Audio attenuation
  52946. this._soundPanner.distanceModel = "linear";
  52947. this._soundPanner.maxDistance = Number.MAX_VALUE;
  52948. this._soundPanner.refDistance = 1;
  52949. this._soundPanner.rolloffFactor = 1;
  52950. this._soundPanner.panningModel = this._panningModel;
  52951. }
  52952. else {
  52953. this._soundPanner.distanceModel = this.distanceModel;
  52954. this._soundPanner.maxDistance = this.maxDistance;
  52955. this._soundPanner.refDistance = this.refDistance;
  52956. this._soundPanner.rolloffFactor = this.rolloffFactor;
  52957. this._soundPanner.panningModel = this._panningModel;
  52958. }
  52959. }
  52960. };
  52961. Sound.prototype.switchPanningModelToHRTF = function () {
  52962. this._panningModel = "HRTF";
  52963. this._switchPanningModel();
  52964. };
  52965. Sound.prototype.switchPanningModelToEqualPower = function () {
  52966. this._panningModel = "equalpower";
  52967. this._switchPanningModel();
  52968. };
  52969. Sound.prototype._switchPanningModel = function () {
  52970. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  52971. this._soundPanner.panningModel = this._panningModel;
  52972. }
  52973. };
  52974. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  52975. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  52976. if (this._isOutputConnected) {
  52977. this._ouputAudioNode.disconnect();
  52978. }
  52979. this._ouputAudioNode.connect(soundTrackAudioNode);
  52980. this._isOutputConnected = true;
  52981. }
  52982. };
  52983. /**
  52984. * Transform this sound into a directional source
  52985. * @param coneInnerAngle Size of the inner cone in degree
  52986. * @param coneOuterAngle Size of the outer cone in degree
  52987. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  52988. */
  52989. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  52990. if (coneOuterAngle < coneInnerAngle) {
  52991. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  52992. return;
  52993. }
  52994. this._coneInnerAngle = coneInnerAngle;
  52995. this._coneOuterAngle = coneOuterAngle;
  52996. this._coneOuterGain = coneOuterGain;
  52997. this._isDirectional = true;
  52998. if (this.isPlaying && this.loop) {
  52999. this.stop();
  53000. this.play();
  53001. }
  53002. };
  53003. Sound.prototype.setPosition = function (newPosition) {
  53004. this._position = newPosition;
  53005. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  53006. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  53007. }
  53008. };
  53009. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  53010. this._localDirection = newLocalDirection;
  53011. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  53012. this._updateDirection();
  53013. }
  53014. };
  53015. Sound.prototype._updateDirection = function () {
  53016. if (!this._connectedMesh || !this._soundPanner) {
  53017. return;
  53018. }
  53019. var mat = this._connectedMesh.getWorldMatrix();
  53020. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  53021. direction.normalize();
  53022. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  53023. };
  53024. Sound.prototype.updateDistanceFromListener = function () {
  53025. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation && this._soundGain && this._scene.activeCamera) {
  53026. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  53027. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  53028. }
  53029. };
  53030. Sound.prototype.setAttenuationFunction = function (callback) {
  53031. this._customAttenuationFunction = callback;
  53032. };
  53033. /**
  53034. * Play the sound
  53035. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  53036. * @param offset (optional) Start the sound setting it at a specific time
  53037. */
  53038. Sound.prototype.play = function (time, offset) {
  53039. var _this = this;
  53040. if (this._isReadyToPlay && this._scene.audioEnabled && BABYLON.Engine.audioEngine.audioContext) {
  53041. try {
  53042. if (this._startOffset < 0) {
  53043. time = -this._startOffset;
  53044. this._startOffset = 0;
  53045. }
  53046. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  53047. if (!this._soundSource || !this._streamingSource) {
  53048. if (this.spatialSound && this._soundPanner) {
  53049. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  53050. if (this._isDirectional) {
  53051. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  53052. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  53053. this._soundPanner.coneOuterGain = this._coneOuterGain;
  53054. if (this._connectedMesh) {
  53055. this._updateDirection();
  53056. }
  53057. else {
  53058. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  53059. }
  53060. }
  53061. }
  53062. }
  53063. if (this._streaming) {
  53064. if (!this._streamingSource) {
  53065. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  53066. this._htmlAudioElement.onended = function () { _this._onended(); };
  53067. this._htmlAudioElement.playbackRate = this._playbackRate;
  53068. }
  53069. this._streamingSource.disconnect();
  53070. this._streamingSource.connect(this._inputAudioNode);
  53071. this._htmlAudioElement.play();
  53072. }
  53073. else {
  53074. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  53075. this._soundSource.buffer = this._audioBuffer;
  53076. this._soundSource.connect(this._inputAudioNode);
  53077. this._soundSource.loop = this.loop;
  53078. this._soundSource.playbackRate.value = this._playbackRate;
  53079. this._soundSource.onended = function () { _this._onended(); };
  53080. if (this._soundSource.buffer) {
  53081. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  53082. }
  53083. }
  53084. this._startTime = startTime;
  53085. this.isPlaying = true;
  53086. this.isPaused = false;
  53087. }
  53088. catch (ex) {
  53089. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  53090. }
  53091. }
  53092. };
  53093. Sound.prototype._onended = function () {
  53094. this.isPlaying = false;
  53095. if (this.onended) {
  53096. this.onended();
  53097. }
  53098. };
  53099. /**
  53100. * Stop the sound
  53101. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  53102. */
  53103. Sound.prototype.stop = function (time) {
  53104. if (this.isPlaying) {
  53105. if (this._streaming) {
  53106. this._htmlAudioElement.pause();
  53107. // Test needed for Firefox or it will generate an Invalid State Error
  53108. if (this._htmlAudioElement.currentTime > 0) {
  53109. this._htmlAudioElement.currentTime = 0;
  53110. }
  53111. }
  53112. else if (BABYLON.Engine.audioEngine.audioContext && this._soundSource) {
  53113. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  53114. this._soundSource.stop(stopTime);
  53115. this._soundSource.onended = function () { };
  53116. if (!this.isPaused) {
  53117. this._startOffset = 0;
  53118. }
  53119. }
  53120. this.isPlaying = false;
  53121. }
  53122. };
  53123. Sound.prototype.pause = function () {
  53124. if (this.isPlaying) {
  53125. this.isPaused = true;
  53126. if (this._streaming) {
  53127. this._htmlAudioElement.pause();
  53128. }
  53129. else if (BABYLON.Engine.audioEngine.audioContext) {
  53130. this.stop(0);
  53131. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  53132. }
  53133. }
  53134. };
  53135. Sound.prototype.setVolume = function (newVolume, time) {
  53136. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._soundGain) {
  53137. if (time && BABYLON.Engine.audioEngine.audioContext) {
  53138. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  53139. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  53140. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  53141. }
  53142. else {
  53143. this._soundGain.gain.value = newVolume;
  53144. }
  53145. }
  53146. this._volume = newVolume;
  53147. };
  53148. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  53149. this._playbackRate = newPlaybackRate;
  53150. if (this.isPlaying) {
  53151. if (this._streaming) {
  53152. this._htmlAudioElement.playbackRate = this._playbackRate;
  53153. }
  53154. else if (this._soundSource) {
  53155. this._soundSource.playbackRate.value = this._playbackRate;
  53156. }
  53157. }
  53158. };
  53159. Sound.prototype.getVolume = function () {
  53160. return this._volume;
  53161. };
  53162. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  53163. var _this = this;
  53164. if (this._connectedMesh && this._registerFunc) {
  53165. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  53166. this._registerFunc = null;
  53167. }
  53168. this._connectedMesh = meshToConnectTo;
  53169. if (!this.spatialSound) {
  53170. this.spatialSound = true;
  53171. this._createSpatialParameters();
  53172. if (this.isPlaying && this.loop) {
  53173. this.stop();
  53174. this.play();
  53175. }
  53176. }
  53177. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  53178. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  53179. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  53180. };
  53181. Sound.prototype.detachFromMesh = function () {
  53182. if (this._connectedMesh && this._registerFunc) {
  53183. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  53184. this._registerFunc = null;
  53185. this._connectedMesh = null;
  53186. }
  53187. };
  53188. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (node) {
  53189. if (!node.getBoundingInfo) {
  53190. return;
  53191. }
  53192. var mesh = node;
  53193. var boundingInfo = mesh.getBoundingInfo();
  53194. this.setPosition(boundingInfo.boundingSphere.centerWorld);
  53195. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  53196. this._updateDirection();
  53197. }
  53198. };
  53199. Sound.prototype.clone = function () {
  53200. var _this = this;
  53201. if (!this._streaming) {
  53202. var setBufferAndRun = function () {
  53203. if (_this._isReadyToPlay) {
  53204. clonedSound._audioBuffer = _this.getAudioBuffer();
  53205. clonedSound._isReadyToPlay = true;
  53206. if (clonedSound.autoplay) {
  53207. clonedSound.play();
  53208. }
  53209. }
  53210. else {
  53211. window.setTimeout(setBufferAndRun, 300);
  53212. }
  53213. };
  53214. var currentOptions = {
  53215. autoplay: this.autoplay, loop: this.loop,
  53216. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  53217. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  53218. refDistance: this.refDistance, distanceModel: this.distanceModel
  53219. };
  53220. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  53221. if (this.useCustomAttenuation) {
  53222. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  53223. }
  53224. clonedSound.setPosition(this._position);
  53225. clonedSound.setPlaybackRate(this._playbackRate);
  53226. setBufferAndRun();
  53227. return clonedSound;
  53228. }
  53229. else {
  53230. return null;
  53231. }
  53232. };
  53233. Sound.prototype.getAudioBuffer = function () {
  53234. return this._audioBuffer;
  53235. };
  53236. Sound.prototype.serialize = function () {
  53237. var serializationObject = {
  53238. name: this.name,
  53239. url: this.name,
  53240. autoplay: this.autoplay,
  53241. loop: this.loop,
  53242. volume: this._volume,
  53243. spatialSound: this.spatialSound,
  53244. maxDistance: this.maxDistance,
  53245. rolloffFactor: this.rolloffFactor,
  53246. refDistance: this.refDistance,
  53247. distanceModel: this.distanceModel,
  53248. playbackRate: this._playbackRate,
  53249. panningModel: this._panningModel,
  53250. soundTrackId: this.soundTrackId
  53251. };
  53252. if (this.spatialSound) {
  53253. if (this._connectedMesh)
  53254. serializationObject.connectedMeshId = this._connectedMesh.id;
  53255. serializationObject.position = this._position.asArray();
  53256. serializationObject.refDistance = this.refDistance;
  53257. serializationObject.distanceModel = this.distanceModel;
  53258. serializationObject.isDirectional = this._isDirectional;
  53259. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  53260. serializationObject.coneInnerAngle = this._coneInnerAngle;
  53261. serializationObject.coneOuterAngle = this._coneOuterAngle;
  53262. serializationObject.coneOuterGain = this._coneOuterGain;
  53263. }
  53264. return serializationObject;
  53265. };
  53266. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  53267. var soundName = parsedSound.name;
  53268. var soundUrl;
  53269. if (parsedSound.url) {
  53270. soundUrl = rootUrl + parsedSound.url;
  53271. }
  53272. else {
  53273. soundUrl = rootUrl + soundName;
  53274. }
  53275. var options = {
  53276. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  53277. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  53278. rolloffFactor: parsedSound.rolloffFactor,
  53279. refDistance: parsedSound.refDistance,
  53280. distanceModel: parsedSound.distanceModel,
  53281. playbackRate: parsedSound.playbackRate
  53282. };
  53283. var newSound;
  53284. if (!sourceSound) {
  53285. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  53286. scene._addPendingData(newSound);
  53287. }
  53288. else {
  53289. var setBufferAndRun = function () {
  53290. if (sourceSound._isReadyToPlay) {
  53291. newSound._audioBuffer = sourceSound.getAudioBuffer();
  53292. newSound._isReadyToPlay = true;
  53293. if (newSound.autoplay) {
  53294. newSound.play();
  53295. }
  53296. }
  53297. else {
  53298. window.setTimeout(setBufferAndRun, 300);
  53299. }
  53300. };
  53301. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  53302. setBufferAndRun();
  53303. }
  53304. if (parsedSound.position) {
  53305. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  53306. newSound.setPosition(soundPosition);
  53307. }
  53308. if (parsedSound.isDirectional) {
  53309. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  53310. if (parsedSound.localDirectionToMesh) {
  53311. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  53312. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  53313. }
  53314. }
  53315. if (parsedSound.connectedMeshId) {
  53316. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  53317. if (connectedMesh) {
  53318. newSound.attachToMesh(connectedMesh);
  53319. }
  53320. }
  53321. return newSound;
  53322. };
  53323. return Sound;
  53324. }());
  53325. BABYLON.Sound = Sound;
  53326. })(BABYLON || (BABYLON = {}));
  53327. //# sourceMappingURL=babylon.sound.js.map
  53328. var BABYLON;
  53329. (function (BABYLON) {
  53330. var SoundTrack = /** @class */ (function () {
  53331. function SoundTrack(scene, options) {
  53332. this.id = -1;
  53333. this._isMainTrack = false;
  53334. this._isInitialized = false;
  53335. this._scene = scene;
  53336. this.soundCollection = new Array();
  53337. this._options = options;
  53338. if (!this._isMainTrack) {
  53339. this._scene.soundTracks.push(this);
  53340. this.id = this._scene.soundTracks.length - 1;
  53341. }
  53342. }
  53343. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  53344. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  53345. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  53346. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  53347. if (this._options) {
  53348. if (this._options.volume) {
  53349. this._outputAudioNode.gain.value = this._options.volume;
  53350. }
  53351. if (this._options.mainTrack) {
  53352. this._isMainTrack = this._options.mainTrack;
  53353. }
  53354. }
  53355. this._isInitialized = true;
  53356. }
  53357. };
  53358. SoundTrack.prototype.dispose = function () {
  53359. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  53360. if (this._connectedAnalyser) {
  53361. this._connectedAnalyser.stopDebugCanvas();
  53362. }
  53363. while (this.soundCollection.length) {
  53364. this.soundCollection[0].dispose();
  53365. }
  53366. if (this._outputAudioNode) {
  53367. this._outputAudioNode.disconnect();
  53368. }
  53369. this._outputAudioNode = null;
  53370. }
  53371. };
  53372. SoundTrack.prototype.AddSound = function (sound) {
  53373. if (!this._isInitialized) {
  53374. this._initializeSoundTrackAudioGraph();
  53375. }
  53376. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  53377. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  53378. }
  53379. if (sound.soundTrackId) {
  53380. if (sound.soundTrackId === -1) {
  53381. this._scene.mainSoundTrack.RemoveSound(sound);
  53382. }
  53383. else {
  53384. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  53385. }
  53386. }
  53387. this.soundCollection.push(sound);
  53388. sound.soundTrackId = this.id;
  53389. };
  53390. SoundTrack.prototype.RemoveSound = function (sound) {
  53391. var index = this.soundCollection.indexOf(sound);
  53392. if (index !== -1) {
  53393. this.soundCollection.splice(index, 1);
  53394. }
  53395. };
  53396. SoundTrack.prototype.setVolume = function (newVolume) {
  53397. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  53398. this._outputAudioNode.gain.value = newVolume;
  53399. }
  53400. };
  53401. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  53402. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  53403. for (var i = 0; i < this.soundCollection.length; i++) {
  53404. this.soundCollection[i].switchPanningModelToHRTF();
  53405. }
  53406. }
  53407. };
  53408. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  53409. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  53410. for (var i = 0; i < this.soundCollection.length; i++) {
  53411. this.soundCollection[i].switchPanningModelToEqualPower();
  53412. }
  53413. }
  53414. };
  53415. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  53416. if (this._connectedAnalyser) {
  53417. this._connectedAnalyser.stopDebugCanvas();
  53418. }
  53419. this._connectedAnalyser = analyser;
  53420. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  53421. this._outputAudioNode.disconnect();
  53422. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  53423. }
  53424. };
  53425. return SoundTrack;
  53426. }());
  53427. BABYLON.SoundTrack = SoundTrack;
  53428. })(BABYLON || (BABYLON = {}));
  53429. //# sourceMappingURL=babylon.soundtrack.js.map
  53430. var BABYLON;
  53431. (function (BABYLON) {
  53432. var Analyser = /** @class */ (function () {
  53433. function Analyser(scene) {
  53434. this.SMOOTHING = 0.75;
  53435. this.FFT_SIZE = 512;
  53436. this.BARGRAPHAMPLITUDE = 256;
  53437. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  53438. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  53439. this._scene = scene;
  53440. this._audioEngine = BABYLON.Engine.audioEngine;
  53441. if (this._audioEngine.canUseWebAudio && this._audioEngine.audioContext) {
  53442. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  53443. this._webAudioAnalyser.minDecibels = -140;
  53444. this._webAudioAnalyser.maxDecibels = 0;
  53445. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  53446. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  53447. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  53448. }
  53449. }
  53450. Analyser.prototype.getFrequencyBinCount = function () {
  53451. if (this._audioEngine.canUseWebAudio) {
  53452. return this._webAudioAnalyser.frequencyBinCount;
  53453. }
  53454. else {
  53455. return 0;
  53456. }
  53457. };
  53458. Analyser.prototype.getByteFrequencyData = function () {
  53459. if (this._audioEngine.canUseWebAudio) {
  53460. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  53461. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  53462. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  53463. }
  53464. return this._byteFreqs;
  53465. };
  53466. Analyser.prototype.getByteTimeDomainData = function () {
  53467. if (this._audioEngine.canUseWebAudio) {
  53468. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  53469. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  53470. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  53471. }
  53472. return this._byteTime;
  53473. };
  53474. Analyser.prototype.getFloatFrequencyData = function () {
  53475. if (this._audioEngine.canUseWebAudio) {
  53476. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  53477. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  53478. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  53479. }
  53480. return this._floatFreqs;
  53481. };
  53482. Analyser.prototype.drawDebugCanvas = function () {
  53483. var _this = this;
  53484. if (this._audioEngine.canUseWebAudio) {
  53485. if (!this._debugCanvas) {
  53486. this._debugCanvas = document.createElement("canvas");
  53487. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  53488. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  53489. this._debugCanvas.style.position = "absolute";
  53490. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  53491. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  53492. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  53493. document.body.appendChild(this._debugCanvas);
  53494. this._registerFunc = function () {
  53495. _this.drawDebugCanvas();
  53496. };
  53497. this._scene.registerBeforeRender(this._registerFunc);
  53498. }
  53499. if (this._registerFunc && this._debugCanvasContext) {
  53500. var workingArray = this.getByteFrequencyData();
  53501. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  53502. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  53503. // Draw the frequency domain chart.
  53504. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  53505. var value = workingArray[i];
  53506. var percent = value / this.BARGRAPHAMPLITUDE;
  53507. var height = this.DEBUGCANVASSIZE.height * percent;
  53508. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  53509. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  53510. var hue = i / this.getFrequencyBinCount() * 360;
  53511. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  53512. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  53513. }
  53514. }
  53515. }
  53516. };
  53517. Analyser.prototype.stopDebugCanvas = function () {
  53518. if (this._debugCanvas) {
  53519. if (this._registerFunc) {
  53520. this._scene.unregisterBeforeRender(this._registerFunc);
  53521. this._registerFunc = null;
  53522. }
  53523. document.body.removeChild(this._debugCanvas);
  53524. this._debugCanvas = null;
  53525. this._debugCanvasContext = null;
  53526. }
  53527. };
  53528. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  53529. if (this._audioEngine.canUseWebAudio) {
  53530. inputAudioNode.connect(this._webAudioAnalyser);
  53531. this._webAudioAnalyser.connect(outputAudioNode);
  53532. }
  53533. };
  53534. Analyser.prototype.dispose = function () {
  53535. if (this._audioEngine.canUseWebAudio) {
  53536. this._webAudioAnalyser.disconnect();
  53537. }
  53538. };
  53539. return Analyser;
  53540. }());
  53541. BABYLON.Analyser = Analyser;
  53542. })(BABYLON || (BABYLON = {}));
  53543. //# sourceMappingURL=babylon.analyser.js.map
  53544. var BABYLON;
  53545. (function (BABYLON) {
  53546. var CubeTexture = /** @class */ (function (_super) {
  53547. __extends(CubeTexture, _super);
  53548. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format, prefiltered, forcedExtension) {
  53549. if (extensions === void 0) { extensions = null; }
  53550. if (noMipmap === void 0) { noMipmap = false; }
  53551. if (files === void 0) { files = null; }
  53552. if (onLoad === void 0) { onLoad = null; }
  53553. if (onError === void 0) { onError = null; }
  53554. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  53555. if (prefiltered === void 0) { prefiltered = false; }
  53556. if (forcedExtension === void 0) { forcedExtension = null; }
  53557. var _this = _super.call(this, scene) || this;
  53558. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  53559. _this.name = rootUrl;
  53560. _this.url = rootUrl;
  53561. _this._noMipmap = noMipmap;
  53562. _this.hasAlpha = false;
  53563. _this._format = format;
  53564. _this._prefiltered = prefiltered;
  53565. _this.isCube = true;
  53566. _this._textureMatrix = BABYLON.Matrix.Identity();
  53567. if (prefiltered) {
  53568. _this.gammaSpace = false;
  53569. }
  53570. if (!rootUrl && !files) {
  53571. return _this;
  53572. }
  53573. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  53574. var lastDot = rootUrl.lastIndexOf(".");
  53575. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  53576. var isDDS = (extension === ".dds");
  53577. if (!files) {
  53578. if (!isDDS && !extensions) {
  53579. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  53580. }
  53581. files = [];
  53582. if (extensions) {
  53583. for (var index = 0; index < extensions.length; index++) {
  53584. files.push(rootUrl + extensions[index]);
  53585. }
  53586. }
  53587. }
  53588. _this._files = files;
  53589. if (!_this._texture) {
  53590. if (!scene.useDelayedTextureLoading) {
  53591. if (prefiltered) {
  53592. _this._texture = scene.getEngine().createPrefilteredCubeTexture(rootUrl, scene, _this.lodGenerationScale, _this.lodGenerationOffset, onLoad, onError, format, forcedExtension);
  53593. }
  53594. else {
  53595. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format, forcedExtension);
  53596. }
  53597. }
  53598. else {
  53599. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  53600. }
  53601. }
  53602. else if (onLoad) {
  53603. if (_this._texture.isReady) {
  53604. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  53605. }
  53606. else {
  53607. _this._texture.onLoadedObservable.add(onLoad);
  53608. }
  53609. }
  53610. return _this;
  53611. }
  53612. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  53613. return new CubeTexture("", scene, null, noMipmap, files);
  53614. };
  53615. CubeTexture.CreateFromPrefilteredData = function (url, scene, forcedExtension) {
  53616. if (forcedExtension === void 0) { forcedExtension = null; }
  53617. return new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension);
  53618. };
  53619. // Methods
  53620. CubeTexture.prototype.delayLoad = function () {
  53621. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  53622. return;
  53623. }
  53624. var scene = this.getScene();
  53625. if (!scene) {
  53626. return;
  53627. }
  53628. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  53629. this._texture = this._getFromCache(this.url, this._noMipmap);
  53630. if (!this._texture) {
  53631. if (this._prefiltered) {
  53632. this._texture = scene.getEngine().createPrefilteredCubeTexture(this.url, scene, this.lodGenerationScale, this.lodGenerationOffset, undefined, undefined, this._format);
  53633. }
  53634. else {
  53635. this._texture = scene.getEngine().createCubeTexture(this.url, scene, this._files, this._noMipmap, undefined, undefined, this._format);
  53636. }
  53637. }
  53638. };
  53639. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  53640. return this._textureMatrix;
  53641. };
  53642. CubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  53643. this._textureMatrix = value;
  53644. };
  53645. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  53646. var texture = BABYLON.SerializationHelper.Parse(function () {
  53647. return new CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  53648. }, parsedTexture, scene);
  53649. // Animations
  53650. if (parsedTexture.animations) {
  53651. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  53652. var parsedAnimation = parsedTexture.animations[animationIndex];
  53653. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  53654. }
  53655. }
  53656. return texture;
  53657. };
  53658. CubeTexture.prototype.clone = function () {
  53659. var _this = this;
  53660. return BABYLON.SerializationHelper.Clone(function () {
  53661. var scene = _this.getScene();
  53662. if (!scene) {
  53663. return _this;
  53664. }
  53665. return new CubeTexture(_this.url, scene, _this._extensions, _this._noMipmap, _this._files);
  53666. }, this);
  53667. };
  53668. return CubeTexture;
  53669. }(BABYLON.BaseTexture));
  53670. BABYLON.CubeTexture = CubeTexture;
  53671. })(BABYLON || (BABYLON = {}));
  53672. //# sourceMappingURL=babylon.cubeTexture.js.map
  53673. var BABYLON;
  53674. (function (BABYLON) {
  53675. var RenderTargetTexture = /** @class */ (function (_super) {
  53676. __extends(RenderTargetTexture, _super);
  53677. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti) {
  53678. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  53679. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  53680. if (isCube === void 0) { isCube = false; }
  53681. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  53682. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  53683. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  53684. if (isMulti === void 0) { isMulti = false; }
  53685. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  53686. _this.isCube = isCube;
  53687. /**
  53688. * Use this list to define the list of mesh you want to render.
  53689. */
  53690. _this.renderList = new Array();
  53691. _this.renderParticles = true;
  53692. _this.renderSprites = false;
  53693. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  53694. _this.ignoreCameraViewport = false;
  53695. // Events
  53696. /**
  53697. * An event triggered when the texture is unbind.
  53698. * @type {BABYLON.Observable}
  53699. */
  53700. _this.onBeforeBindObservable = new BABYLON.Observable();
  53701. /**
  53702. * An event triggered when the texture is unbind.
  53703. * @type {BABYLON.Observable}
  53704. */
  53705. _this.onAfterUnbindObservable = new BABYLON.Observable();
  53706. /**
  53707. * An event triggered before rendering the texture
  53708. * @type {BABYLON.Observable}
  53709. */
  53710. _this.onBeforeRenderObservable = new BABYLON.Observable();
  53711. /**
  53712. * An event triggered after rendering the texture
  53713. * @type {BABYLON.Observable}
  53714. */
  53715. _this.onAfterRenderObservable = new BABYLON.Observable();
  53716. /**
  53717. * An event triggered after the texture clear
  53718. * @type {BABYLON.Observable}
  53719. */
  53720. _this.onClearObservable = new BABYLON.Observable();
  53721. _this._currentRefreshId = -1;
  53722. _this._refreshRate = 1;
  53723. _this._samples = 1;
  53724. scene = _this.getScene();
  53725. if (!scene) {
  53726. return _this;
  53727. }
  53728. _this._engine = scene.getEngine();
  53729. _this.name = name;
  53730. _this.isRenderTarget = true;
  53731. _this._initialSizeParameter = size;
  53732. _this._processSizeParameter(size);
  53733. _this._resizeObserver = _this.getScene().getEngine().onResizeObservable.add(function () {
  53734. });
  53735. _this._generateMipMaps = generateMipMaps ? true : false;
  53736. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  53737. // Rendering groups
  53738. _this._renderingManager = new BABYLON.RenderingManager(scene);
  53739. if (isMulti) {
  53740. return _this;
  53741. }
  53742. _this._renderTargetOptions = {
  53743. generateMipMaps: generateMipMaps,
  53744. type: type,
  53745. samplingMode: samplingMode,
  53746. generateDepthBuffer: generateDepthBuffer,
  53747. generateStencilBuffer: generateStencilBuffer
  53748. };
  53749. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  53750. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  53751. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  53752. }
  53753. if (isCube) {
  53754. _this._texture = scene.getEngine().createRenderTargetCubeTexture(_this.getRenderSize(), _this._renderTargetOptions);
  53755. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  53756. _this._textureMatrix = BABYLON.Matrix.Identity();
  53757. }
  53758. else {
  53759. _this._texture = scene.getEngine().createRenderTargetTexture(_this._size, _this._renderTargetOptions);
  53760. }
  53761. return _this;
  53762. }
  53763. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  53764. get: function () {
  53765. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  53766. },
  53767. enumerable: true,
  53768. configurable: true
  53769. });
  53770. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  53771. get: function () {
  53772. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  53773. },
  53774. enumerable: true,
  53775. configurable: true
  53776. });
  53777. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  53778. get: function () {
  53779. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  53780. },
  53781. enumerable: true,
  53782. configurable: true
  53783. });
  53784. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  53785. set: function (callback) {
  53786. if (this._onAfterUnbindObserver) {
  53787. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  53788. }
  53789. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  53790. },
  53791. enumerable: true,
  53792. configurable: true
  53793. });
  53794. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  53795. set: function (callback) {
  53796. if (this._onBeforeRenderObserver) {
  53797. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  53798. }
  53799. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  53800. },
  53801. enumerable: true,
  53802. configurable: true
  53803. });
  53804. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  53805. set: function (callback) {
  53806. if (this._onAfterRenderObserver) {
  53807. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  53808. }
  53809. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  53810. },
  53811. enumerable: true,
  53812. configurable: true
  53813. });
  53814. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  53815. set: function (callback) {
  53816. if (this._onClearObserver) {
  53817. this.onClearObservable.remove(this._onClearObserver);
  53818. }
  53819. this._onClearObserver = this.onClearObservable.add(callback);
  53820. },
  53821. enumerable: true,
  53822. configurable: true
  53823. });
  53824. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  53825. get: function () {
  53826. return this._renderTargetOptions;
  53827. },
  53828. enumerable: true,
  53829. configurable: true
  53830. });
  53831. RenderTargetTexture.prototype._onRatioRescale = function () {
  53832. if (this._sizeRatio) {
  53833. this.resize(this._initialSizeParameter);
  53834. }
  53835. };
  53836. RenderTargetTexture.prototype._processSizeParameter = function (size) {
  53837. if (size.ratio) {
  53838. this._sizeRatio = size.ratio;
  53839. this._size = {
  53840. width: this._bestReflectionRenderTargetDimension(this._engine.getRenderWidth(), this._sizeRatio),
  53841. height: this._bestReflectionRenderTargetDimension(this._engine.getRenderHeight(), this._sizeRatio)
  53842. };
  53843. }
  53844. else {
  53845. this._size = size;
  53846. }
  53847. };
  53848. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  53849. get: function () {
  53850. return this._samples;
  53851. },
  53852. set: function (value) {
  53853. if (this._samples === value) {
  53854. return;
  53855. }
  53856. var scene = this.getScene();
  53857. if (!scene) {
  53858. return;
  53859. }
  53860. this._samples = scene.getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  53861. },
  53862. enumerable: true,
  53863. configurable: true
  53864. });
  53865. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  53866. this._currentRefreshId = -1;
  53867. };
  53868. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  53869. get: function () {
  53870. return this._refreshRate;
  53871. },
  53872. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  53873. set: function (value) {
  53874. this._refreshRate = value;
  53875. this.resetRefreshCounter();
  53876. },
  53877. enumerable: true,
  53878. configurable: true
  53879. });
  53880. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  53881. if (!this._postProcessManager) {
  53882. var scene = this.getScene();
  53883. if (!scene) {
  53884. return;
  53885. }
  53886. this._postProcessManager = new BABYLON.PostProcessManager(scene);
  53887. this._postProcesses = new Array();
  53888. }
  53889. this._postProcesses.push(postProcess);
  53890. this._postProcesses[0].autoClear = false;
  53891. };
  53892. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  53893. if (!this._postProcesses) {
  53894. return;
  53895. }
  53896. if (dispose) {
  53897. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  53898. var postProcess = _a[_i];
  53899. postProcess.dispose();
  53900. }
  53901. }
  53902. this._postProcesses = [];
  53903. };
  53904. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  53905. if (!this._postProcesses) {
  53906. return;
  53907. }
  53908. var index = this._postProcesses.indexOf(postProcess);
  53909. if (index === -1) {
  53910. return;
  53911. }
  53912. this._postProcesses.splice(index, 1);
  53913. if (this._postProcesses.length > 0) {
  53914. this._postProcesses[0].autoClear = false;
  53915. }
  53916. };
  53917. RenderTargetTexture.prototype._shouldRender = function () {
  53918. if (this._currentRefreshId === -1) {
  53919. this._currentRefreshId = 1;
  53920. return true;
  53921. }
  53922. if (this.refreshRate === this._currentRefreshId) {
  53923. this._currentRefreshId = 1;
  53924. return true;
  53925. }
  53926. this._currentRefreshId++;
  53927. return false;
  53928. };
  53929. RenderTargetTexture.prototype.getRenderSize = function () {
  53930. if (this._size.width) {
  53931. return this._size.width;
  53932. }
  53933. return this._size;
  53934. };
  53935. RenderTargetTexture.prototype.getRenderWidth = function () {
  53936. if (this._size.width) {
  53937. return this._size.width;
  53938. }
  53939. return this._size;
  53940. };
  53941. RenderTargetTexture.prototype.getRenderHeight = function () {
  53942. if (this._size.width) {
  53943. return this._size.height;
  53944. }
  53945. return this._size;
  53946. };
  53947. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  53948. get: function () {
  53949. return true;
  53950. },
  53951. enumerable: true,
  53952. configurable: true
  53953. });
  53954. RenderTargetTexture.prototype.scale = function (ratio) {
  53955. var newSize = this.getRenderSize() * ratio;
  53956. this.resize(newSize);
  53957. };
  53958. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  53959. if (this.isCube) {
  53960. return this._textureMatrix;
  53961. }
  53962. return _super.prototype.getReflectionTextureMatrix.call(this);
  53963. };
  53964. RenderTargetTexture.prototype.resize = function (size) {
  53965. this.releaseInternalTexture();
  53966. var scene = this.getScene();
  53967. if (!scene) {
  53968. return;
  53969. }
  53970. this._processSizeParameter(size);
  53971. if (this.isCube) {
  53972. this._texture = scene.getEngine().createRenderTargetCubeTexture(this.getRenderSize(), this._renderTargetOptions);
  53973. }
  53974. else {
  53975. this._texture = scene.getEngine().createRenderTargetTexture(this._size, this._renderTargetOptions);
  53976. }
  53977. };
  53978. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  53979. if (useCameraPostProcess === void 0) { useCameraPostProcess = false; }
  53980. if (dumpForDebug === void 0) { dumpForDebug = false; }
  53981. var scene = this.getScene();
  53982. if (!scene) {
  53983. return;
  53984. }
  53985. var engine = scene.getEngine();
  53986. if (this.useCameraPostProcesses !== undefined) {
  53987. useCameraPostProcess = this.useCameraPostProcesses;
  53988. }
  53989. if (this._waitingRenderList) {
  53990. this.renderList = [];
  53991. for (var index = 0; index < this._waitingRenderList.length; index++) {
  53992. var id = this._waitingRenderList[index];
  53993. var mesh_1 = scene.getMeshByID(id);
  53994. if (mesh_1) {
  53995. this.renderList.push(mesh_1);
  53996. }
  53997. }
  53998. delete this._waitingRenderList;
  53999. }
  54000. // Is predicate defined?
  54001. if (this.renderListPredicate) {
  54002. if (this.renderList) {
  54003. this.renderList.splice(0); // Clear previous renderList
  54004. }
  54005. else {
  54006. this.renderList = [];
  54007. }
  54008. var scene = this.getScene();
  54009. if (!scene) {
  54010. return;
  54011. }
  54012. var sceneMeshes = scene.meshes;
  54013. for (var index = 0; index < sceneMeshes.length; index++) {
  54014. var mesh = sceneMeshes[index];
  54015. if (this.renderListPredicate(mesh)) {
  54016. this.renderList.push(mesh);
  54017. }
  54018. }
  54019. }
  54020. this.onBeforeBindObservable.notifyObservers(this);
  54021. // Set custom projection.
  54022. // Needs to be before binding to prevent changing the aspect ratio.
  54023. var camera;
  54024. if (this.activeCamera) {
  54025. camera = this.activeCamera;
  54026. engine.setViewport(this.activeCamera.viewport, this.getRenderWidth(), this.getRenderHeight());
  54027. if (this.activeCamera !== scene.activeCamera) {
  54028. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  54029. }
  54030. }
  54031. else {
  54032. camera = scene.activeCamera;
  54033. if (camera) {
  54034. engine.setViewport(camera.viewport, this.getRenderWidth(), this.getRenderHeight());
  54035. }
  54036. }
  54037. // Prepare renderingManager
  54038. this._renderingManager.reset();
  54039. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  54040. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  54041. var sceneRenderId = scene.getRenderId();
  54042. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  54043. var mesh = currentRenderList[meshIndex];
  54044. if (mesh) {
  54045. if (!mesh.isReady()) {
  54046. // Reset _currentRefreshId
  54047. this.resetRefreshCounter();
  54048. continue;
  54049. }
  54050. mesh._preActivateForIntermediateRendering(sceneRenderId);
  54051. var isMasked = void 0;
  54052. if (!this.renderList && camera) {
  54053. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  54054. }
  54055. else {
  54056. isMasked = false;
  54057. }
  54058. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  54059. mesh._activate(sceneRenderId);
  54060. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  54061. var subMesh = mesh.subMeshes[subIndex];
  54062. scene._activeIndices.addCount(subMesh.indexCount, false);
  54063. this._renderingManager.dispatch(subMesh, mesh);
  54064. }
  54065. }
  54066. }
  54067. }
  54068. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  54069. var particleSystem = scene.particleSystems[particleIndex];
  54070. var emitter = particleSystem.emitter;
  54071. if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {
  54072. continue;
  54073. }
  54074. if (currentRenderList.indexOf(emitter) >= 0) {
  54075. this._renderingManager.dispatchParticles(particleSystem);
  54076. }
  54077. }
  54078. if (this.isCube) {
  54079. for (var face = 0; face < 6; face++) {
  54080. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  54081. scene.incrementRenderId();
  54082. scene.resetCachedMaterial();
  54083. }
  54084. }
  54085. else {
  54086. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  54087. }
  54088. this.onAfterUnbindObservable.notifyObservers(this);
  54089. if (scene.activeCamera) {
  54090. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  54091. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  54092. }
  54093. engine.setViewport(scene.activeCamera.viewport);
  54094. }
  54095. scene.resetCachedMaterial();
  54096. };
  54097. RenderTargetTexture.prototype._bestReflectionRenderTargetDimension = function (renderDimension, scale) {
  54098. var minimum = 128;
  54099. var x = renderDimension * scale;
  54100. var curved = BABYLON.Tools.NearestPOT(x + (minimum * minimum / (minimum + x)));
  54101. // Ensure we don't exceed the render dimension (while staying POT)
  54102. return Math.min(BABYLON.Tools.FloorPOT(renderDimension), curved);
  54103. };
  54104. RenderTargetTexture.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  54105. var _this = this;
  54106. if (!this._texture) {
  54107. return;
  54108. }
  54109. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  54110. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  54111. });
  54112. };
  54113. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  54114. var scene = this.getScene();
  54115. if (!scene) {
  54116. return;
  54117. }
  54118. var engine = scene.getEngine();
  54119. if (!this._texture) {
  54120. return;
  54121. }
  54122. // Bind
  54123. if (this._postProcessManager) {
  54124. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  54125. }
  54126. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  54127. if (this._texture) {
  54128. engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport);
  54129. }
  54130. }
  54131. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  54132. // Clear
  54133. if (this.onClearObservable.hasObservers()) {
  54134. this.onClearObservable.notifyObservers(engine);
  54135. }
  54136. else {
  54137. engine.clear(this.clearColor || scene.clearColor, true, true, true);
  54138. }
  54139. if (!this._doNotChangeAspectRatio) {
  54140. scene.updateTransformMatrix(true);
  54141. }
  54142. // Render
  54143. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  54144. if (this._postProcessManager) {
  54145. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses, this.ignoreCameraViewport);
  54146. }
  54147. else if (useCameraPostProcess) {
  54148. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  54149. }
  54150. if (!this._doNotChangeAspectRatio) {
  54151. scene.updateTransformMatrix(true);
  54152. }
  54153. // Dump ?
  54154. if (dumpForDebug) {
  54155. BABYLON.Tools.DumpFramebuffer(this.getRenderWidth(), this.getRenderHeight(), engine);
  54156. }
  54157. // Unbind
  54158. if (!this.isCube || faceIndex === 5) {
  54159. if (this.isCube) {
  54160. if (faceIndex === 5) {
  54161. engine.generateMipMapsForCubemap(this._texture);
  54162. }
  54163. }
  54164. this.unbindFrameBuffer(engine, faceIndex);
  54165. }
  54166. else {
  54167. this.onAfterRenderObservable.notifyObservers(faceIndex);
  54168. }
  54169. };
  54170. /**
  54171. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  54172. * This allowed control for front to back rendering or reversly depending of the special needs.
  54173. *
  54174. * @param renderingGroupId The rendering group id corresponding to its index
  54175. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  54176. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  54177. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  54178. */
  54179. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  54180. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  54181. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  54182. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  54183. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  54184. };
  54185. /**
  54186. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  54187. *
  54188. * @param renderingGroupId The rendering group id corresponding to its index
  54189. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  54190. */
  54191. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  54192. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  54193. };
  54194. RenderTargetTexture.prototype.clone = function () {
  54195. var textureSize = this.getSize();
  54196. 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);
  54197. // Base texture
  54198. newTexture.hasAlpha = this.hasAlpha;
  54199. newTexture.level = this.level;
  54200. // RenderTarget Texture
  54201. newTexture.coordinatesMode = this.coordinatesMode;
  54202. if (this.renderList) {
  54203. newTexture.renderList = this.renderList.slice(0);
  54204. }
  54205. return newTexture;
  54206. };
  54207. RenderTargetTexture.prototype.serialize = function () {
  54208. if (!this.name) {
  54209. return null;
  54210. }
  54211. var serializationObject = _super.prototype.serialize.call(this);
  54212. serializationObject.renderTargetSize = this.getRenderSize();
  54213. serializationObject.renderList = [];
  54214. if (this.renderList) {
  54215. for (var index = 0; index < this.renderList.length; index++) {
  54216. serializationObject.renderList.push(this.renderList[index].id);
  54217. }
  54218. }
  54219. return serializationObject;
  54220. };
  54221. // This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  54222. RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
  54223. var objBuffer = this.getInternalTexture();
  54224. var scene = this.getScene();
  54225. if (objBuffer && scene) {
  54226. scene.getEngine()._releaseFramebufferObjects(objBuffer);
  54227. }
  54228. };
  54229. RenderTargetTexture.prototype.dispose = function () {
  54230. if (this._postProcessManager) {
  54231. this._postProcessManager.dispose();
  54232. this._postProcessManager = null;
  54233. }
  54234. this.clearPostProcesses(true);
  54235. if (this._resizeObserver) {
  54236. this.getScene().getEngine().onResizeObservable.remove(this._resizeObserver);
  54237. this._resizeObserver = null;
  54238. }
  54239. this.renderList = null;
  54240. // Remove from custom render targets
  54241. var scene = this.getScene();
  54242. if (!scene) {
  54243. return;
  54244. }
  54245. var index = scene.customRenderTargets.indexOf(this);
  54246. if (index >= 0) {
  54247. scene.customRenderTargets.splice(index, 1);
  54248. }
  54249. for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
  54250. var camera = _a[_i];
  54251. index = camera.customRenderTargets.indexOf(this);
  54252. if (index >= 0) {
  54253. camera.customRenderTargets.splice(index, 1);
  54254. }
  54255. }
  54256. _super.prototype.dispose.call(this);
  54257. };
  54258. RenderTargetTexture.prototype._rebuild = function () {
  54259. if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  54260. this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  54261. }
  54262. if (this._postProcessManager) {
  54263. this._postProcessManager._rebuild();
  54264. }
  54265. };
  54266. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  54267. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  54268. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  54269. return RenderTargetTexture;
  54270. }(BABYLON.Texture));
  54271. BABYLON.RenderTargetTexture = RenderTargetTexture;
  54272. })(BABYLON || (BABYLON = {}));
  54273. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  54274. var BABYLON;
  54275. (function (BABYLON) {
  54276. ;
  54277. var MultiRenderTarget = /** @class */ (function (_super) {
  54278. __extends(MultiRenderTarget, _super);
  54279. function MultiRenderTarget(name, size, count, scene, options) {
  54280. var _this = this;
  54281. var generateMipMaps = options && options.generateMipMaps ? options.generateMipMaps : false;
  54282. var generateDepthTexture = options && options.generateDepthTexture ? options.generateDepthTexture : false;
  54283. var doNotChangeAspectRatio = !options || options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  54284. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  54285. _this._engine = scene.getEngine();
  54286. if (!_this.isSupported) {
  54287. _this.dispose();
  54288. return;
  54289. }
  54290. var types = [];
  54291. var samplingModes = [];
  54292. for (var i = 0; i < count; i++) {
  54293. if (options && options.types && options.types[i] !== undefined) {
  54294. types.push(options.types[i]);
  54295. }
  54296. else {
  54297. types.push(options && options.defaultType ? options.defaultType : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  54298. }
  54299. if (options && options.samplingModes && options.samplingModes[i] !== undefined) {
  54300. samplingModes.push(options.samplingModes[i]);
  54301. }
  54302. else {
  54303. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  54304. }
  54305. }
  54306. var generateDepthBuffer = !options || options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  54307. var generateStencilBuffer = !options || options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  54308. _this._size = size;
  54309. _this._multiRenderTargetOptions = {
  54310. samplingModes: samplingModes,
  54311. generateMipMaps: generateMipMaps,
  54312. generateDepthBuffer: generateDepthBuffer,
  54313. generateStencilBuffer: generateStencilBuffer,
  54314. generateDepthTexture: generateDepthTexture,
  54315. types: types,
  54316. textureCount: count
  54317. };
  54318. _this._createInternalTextures();
  54319. _this._createTextures();
  54320. return _this;
  54321. }
  54322. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  54323. get: function () {
  54324. return this._engine.webGLVersion > 1 || this._engine.getCaps().drawBuffersExtension;
  54325. },
  54326. enumerable: true,
  54327. configurable: true
  54328. });
  54329. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  54330. get: function () {
  54331. return this._textures;
  54332. },
  54333. enumerable: true,
  54334. configurable: true
  54335. });
  54336. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  54337. get: function () {
  54338. return this._textures[this._textures.length - 1];
  54339. },
  54340. enumerable: true,
  54341. configurable: true
  54342. });
  54343. Object.defineProperty(MultiRenderTarget.prototype, "wrapU", {
  54344. set: function (wrap) {
  54345. if (this._textures) {
  54346. for (var i = 0; i < this._textures.length; i++) {
  54347. this._textures[i].wrapU = wrap;
  54348. }
  54349. }
  54350. },
  54351. enumerable: true,
  54352. configurable: true
  54353. });
  54354. Object.defineProperty(MultiRenderTarget.prototype, "wrapV", {
  54355. set: function (wrap) {
  54356. if (this._textures) {
  54357. for (var i = 0; i < this._textures.length; i++) {
  54358. this._textures[i].wrapV = wrap;
  54359. }
  54360. }
  54361. },
  54362. enumerable: true,
  54363. configurable: true
  54364. });
  54365. MultiRenderTarget.prototype._rebuild = function () {
  54366. this.releaseInternalTextures();
  54367. this._createInternalTextures();
  54368. for (var i = 0; i < this._internalTextures.length; i++) {
  54369. var texture = this._textures[i];
  54370. texture._texture = this._internalTextures[i];
  54371. }
  54372. // Keeps references to frame buffer and stencil/depth buffer
  54373. this._texture = this._internalTextures[0];
  54374. };
  54375. MultiRenderTarget.prototype._createInternalTextures = function () {
  54376. this._internalTextures = this._engine.createMultipleRenderTarget(this._size, this._multiRenderTargetOptions);
  54377. };
  54378. MultiRenderTarget.prototype._createTextures = function () {
  54379. this._textures = [];
  54380. for (var i = 0; i < this._internalTextures.length; i++) {
  54381. var texture = new BABYLON.Texture(null, this.getScene());
  54382. texture._texture = this._internalTextures[i];
  54383. this._textures.push(texture);
  54384. }
  54385. // Keeps references to frame buffer and stencil/depth buffer
  54386. this._texture = this._internalTextures[0];
  54387. };
  54388. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  54389. get: function () {
  54390. return this._samples;
  54391. },
  54392. set: function (value) {
  54393. if (this._samples === value) {
  54394. return;
  54395. }
  54396. this._samples = this._engine.updateMultipleRenderTargetTextureSampleCount(this._internalTextures, value);
  54397. },
  54398. enumerable: true,
  54399. configurable: true
  54400. });
  54401. MultiRenderTarget.prototype.resize = function (size) {
  54402. this.releaseInternalTextures();
  54403. this._internalTextures = this._engine.createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  54404. this._createInternalTextures();
  54405. };
  54406. MultiRenderTarget.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  54407. var _this = this;
  54408. engine.unBindMultiColorAttachmentFramebuffer(this._internalTextures, this.isCube, function () {
  54409. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  54410. });
  54411. };
  54412. MultiRenderTarget.prototype.dispose = function () {
  54413. this.releaseInternalTextures();
  54414. _super.prototype.dispose.call(this);
  54415. };
  54416. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  54417. if (!this._internalTextures) {
  54418. return;
  54419. }
  54420. for (var i = this._internalTextures.length - 1; i >= 0; i--) {
  54421. if (this._internalTextures[i] !== undefined) {
  54422. this._internalTextures[i].dispose();
  54423. this._internalTextures.splice(i, 1);
  54424. }
  54425. }
  54426. };
  54427. return MultiRenderTarget;
  54428. }(BABYLON.RenderTargetTexture));
  54429. BABYLON.MultiRenderTarget = MultiRenderTarget;
  54430. })(BABYLON || (BABYLON = {}));
  54431. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  54432. var BABYLON;
  54433. (function (BABYLON) {
  54434. var MirrorTexture = /** @class */ (function (_super) {
  54435. __extends(MirrorTexture, _super);
  54436. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  54437. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  54438. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  54439. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  54440. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  54441. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  54442. _this._transformMatrix = BABYLON.Matrix.Zero();
  54443. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  54444. _this._adaptiveBlurKernel = 0;
  54445. _this._blurKernelX = 0;
  54446. _this._blurKernelY = 0;
  54447. _this._blurRatio = 1.0;
  54448. _this.ignoreCameraViewport = true;
  54449. _this.onBeforeRenderObservable.add(function () {
  54450. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  54451. _this._savedViewMatrix = scene.getViewMatrix();
  54452. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  54453. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  54454. scene.clipPlane = _this.mirrorPlane;
  54455. scene.getEngine().cullBackFaces = false;
  54456. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.globalPosition, _this._mirrorMatrix);
  54457. });
  54458. _this.onAfterRenderObservable.add(function () {
  54459. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  54460. scene.getEngine().cullBackFaces = true;
  54461. scene._mirroredCameraPosition = null;
  54462. delete scene.clipPlane;
  54463. });
  54464. return _this;
  54465. }
  54466. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  54467. get: function () {
  54468. return this._blurRatio;
  54469. },
  54470. set: function (value) {
  54471. if (this._blurRatio === value) {
  54472. return;
  54473. }
  54474. this._blurRatio = value;
  54475. this._preparePostProcesses();
  54476. },
  54477. enumerable: true,
  54478. configurable: true
  54479. });
  54480. Object.defineProperty(MirrorTexture.prototype, "adaptiveBlurKernel", {
  54481. set: function (value) {
  54482. this._adaptiveBlurKernel = value;
  54483. this._autoComputeBlurKernel();
  54484. },
  54485. enumerable: true,
  54486. configurable: true
  54487. });
  54488. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  54489. set: function (value) {
  54490. this.blurKernelX = value;
  54491. this.blurKernelY = value;
  54492. },
  54493. enumerable: true,
  54494. configurable: true
  54495. });
  54496. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  54497. get: function () {
  54498. return this._blurKernelX;
  54499. },
  54500. set: function (value) {
  54501. if (this._blurKernelX === value) {
  54502. return;
  54503. }
  54504. this._blurKernelX = value;
  54505. this._preparePostProcesses();
  54506. },
  54507. enumerable: true,
  54508. configurable: true
  54509. });
  54510. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  54511. get: function () {
  54512. return this._blurKernelY;
  54513. },
  54514. set: function (value) {
  54515. if (this._blurKernelY === value) {
  54516. return;
  54517. }
  54518. this._blurKernelY = value;
  54519. this._preparePostProcesses();
  54520. },
  54521. enumerable: true,
  54522. configurable: true
  54523. });
  54524. MirrorTexture.prototype._autoComputeBlurKernel = function () {
  54525. var engine = this.getScene().getEngine();
  54526. var dw = this.getRenderWidth() / engine.getRenderWidth();
  54527. var dh = this.getRenderHeight() / engine.getRenderHeight();
  54528. this.blurKernelX = this._adaptiveBlurKernel * dw;
  54529. this.blurKernelY = this._adaptiveBlurKernel * dh;
  54530. };
  54531. MirrorTexture.prototype._onRatioRescale = function () {
  54532. if (this._sizeRatio) {
  54533. this.resize(this._initialSizeParameter);
  54534. if (!this._adaptiveBlurKernel) {
  54535. this._preparePostProcesses();
  54536. }
  54537. }
  54538. if (this._adaptiveBlurKernel) {
  54539. this._autoComputeBlurKernel();
  54540. }
  54541. };
  54542. MirrorTexture.prototype._preparePostProcesses = function () {
  54543. this.clearPostProcesses(true);
  54544. if (this._blurKernelX && this._blurKernelY) {
  54545. var engine = this.getScene().getEngine();
  54546. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  54547. 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);
  54548. this._blurX.autoClear = false;
  54549. if (this._blurRatio === 1 && this.samples < 2 && this._texture) {
  54550. this._blurX.outputTexture = this._texture;
  54551. }
  54552. else {
  54553. this._blurX.alwaysForcePOT = true;
  54554. }
  54555. 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);
  54556. this._blurY.autoClear = false;
  54557. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  54558. this.addPostProcess(this._blurX);
  54559. this.addPostProcess(this._blurY);
  54560. }
  54561. else {
  54562. if (this._blurY) {
  54563. this.removePostProcess(this._blurY);
  54564. this._blurY.dispose();
  54565. this._blurY = null;
  54566. }
  54567. if (this._blurX) {
  54568. this.removePostProcess(this._blurX);
  54569. this._blurX.dispose();
  54570. this._blurX = null;
  54571. }
  54572. }
  54573. };
  54574. MirrorTexture.prototype.clone = function () {
  54575. var scene = this.getScene();
  54576. if (!scene) {
  54577. return this;
  54578. }
  54579. var textureSize = this.getSize();
  54580. var newTexture = new MirrorTexture(this.name, textureSize.width, scene, this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  54581. // Base texture
  54582. newTexture.hasAlpha = this.hasAlpha;
  54583. newTexture.level = this.level;
  54584. // Mirror Texture
  54585. newTexture.mirrorPlane = this.mirrorPlane.clone();
  54586. if (this.renderList) {
  54587. newTexture.renderList = this.renderList.slice(0);
  54588. }
  54589. return newTexture;
  54590. };
  54591. MirrorTexture.prototype.serialize = function () {
  54592. if (!this.name) {
  54593. return null;
  54594. }
  54595. var serializationObject = _super.prototype.serialize.call(this);
  54596. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  54597. return serializationObject;
  54598. };
  54599. return MirrorTexture;
  54600. }(BABYLON.RenderTargetTexture));
  54601. BABYLON.MirrorTexture = MirrorTexture;
  54602. })(BABYLON || (BABYLON = {}));
  54603. //# sourceMappingURL=babylon.mirrorTexture.js.map
  54604. var BABYLON;
  54605. (function (BABYLON) {
  54606. /**
  54607. * Creates a refraction texture used by refraction channel of the standard material.
  54608. * @param name the texture name
  54609. * @param size size of the underlying texture
  54610. * @param scene root scene
  54611. */
  54612. var RefractionTexture = /** @class */ (function (_super) {
  54613. __extends(RefractionTexture, _super);
  54614. function RefractionTexture(name, size, scene, generateMipMaps) {
  54615. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  54616. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  54617. _this.depth = 2.0;
  54618. _this.onBeforeRenderObservable.add(function () {
  54619. scene.clipPlane = _this.refractionPlane;
  54620. });
  54621. _this.onAfterRenderObservable.add(function () {
  54622. delete scene.clipPlane;
  54623. });
  54624. return _this;
  54625. }
  54626. RefractionTexture.prototype.clone = function () {
  54627. var scene = this.getScene();
  54628. if (!scene) {
  54629. return this;
  54630. }
  54631. var textureSize = this.getSize();
  54632. var newTexture = new RefractionTexture(this.name, textureSize.width, scene, this._generateMipMaps);
  54633. // Base texture
  54634. newTexture.hasAlpha = this.hasAlpha;
  54635. newTexture.level = this.level;
  54636. // Refraction Texture
  54637. newTexture.refractionPlane = this.refractionPlane.clone();
  54638. if (this.renderList) {
  54639. newTexture.renderList = this.renderList.slice(0);
  54640. }
  54641. newTexture.depth = this.depth;
  54642. return newTexture;
  54643. };
  54644. RefractionTexture.prototype.serialize = function () {
  54645. if (!this.name) {
  54646. return null;
  54647. }
  54648. var serializationObject = _super.prototype.serialize.call(this);
  54649. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  54650. serializationObject.depth = this.depth;
  54651. return serializationObject;
  54652. };
  54653. return RefractionTexture;
  54654. }(BABYLON.RenderTargetTexture));
  54655. BABYLON.RefractionTexture = RefractionTexture;
  54656. })(BABYLON || (BABYLON = {}));
  54657. //# sourceMappingURL=babylon.refractionTexture.js.map
  54658. var BABYLON;
  54659. (function (BABYLON) {
  54660. var DynamicTexture = /** @class */ (function (_super) {
  54661. __extends(DynamicTexture, _super);
  54662. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  54663. if (scene === void 0) { scene = null; }
  54664. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  54665. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  54666. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  54667. _this.name = name;
  54668. _this._engine = _this.getScene().getEngine();
  54669. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  54670. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  54671. _this._generateMipMaps = generateMipMaps;
  54672. if (options.getContext) {
  54673. _this._canvas = options;
  54674. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  54675. }
  54676. else {
  54677. _this._canvas = document.createElement("canvas");
  54678. if (options.width) {
  54679. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  54680. }
  54681. else {
  54682. _this._texture = _this._engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  54683. }
  54684. }
  54685. var textureSize = _this.getSize();
  54686. _this._canvas.width = textureSize.width;
  54687. _this._canvas.height = textureSize.height;
  54688. _this._context = _this._canvas.getContext("2d");
  54689. return _this;
  54690. }
  54691. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  54692. get: function () {
  54693. return true;
  54694. },
  54695. enumerable: true,
  54696. configurable: true
  54697. });
  54698. DynamicTexture.prototype._recreate = function (textureSize) {
  54699. this._canvas.width = textureSize.width;
  54700. this._canvas.height = textureSize.height;
  54701. this.releaseInternalTexture();
  54702. this._texture = this._engine.createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  54703. };
  54704. DynamicTexture.prototype.scale = function (ratio) {
  54705. var textureSize = this.getSize();
  54706. textureSize.width *= ratio;
  54707. textureSize.height *= ratio;
  54708. this._recreate(textureSize);
  54709. };
  54710. DynamicTexture.prototype.scaleTo = function (width, height) {
  54711. var textureSize = this.getSize();
  54712. textureSize.width = width;
  54713. textureSize.height = height;
  54714. this._recreate(textureSize);
  54715. };
  54716. DynamicTexture.prototype.getContext = function () {
  54717. return this._context;
  54718. };
  54719. DynamicTexture.prototype.clear = function () {
  54720. var size = this.getSize();
  54721. this._context.fillRect(0, 0, size.width, size.height);
  54722. };
  54723. DynamicTexture.prototype.update = function (invertY) {
  54724. this._engine.updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, undefined, this._format || undefined);
  54725. };
  54726. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  54727. if (update === void 0) { update = true; }
  54728. var size = this.getSize();
  54729. if (clearColor) {
  54730. this._context.fillStyle = clearColor;
  54731. this._context.fillRect(0, 0, size.width, size.height);
  54732. }
  54733. this._context.font = font;
  54734. if (x === null || x === undefined) {
  54735. var textSize = this._context.measureText(text);
  54736. x = (size.width - textSize.width) / 2;
  54737. }
  54738. if (y === null || y === undefined) {
  54739. var fontSize = parseInt((font.replace(/\D/g, '')));
  54740. ;
  54741. y = (size.height / 2) + (fontSize / 3.65);
  54742. }
  54743. this._context.fillStyle = color;
  54744. this._context.fillText(text, x, y);
  54745. if (update) {
  54746. this.update(invertY);
  54747. }
  54748. };
  54749. DynamicTexture.prototype.clone = function () {
  54750. var scene = this.getScene();
  54751. if (!scene) {
  54752. return this;
  54753. }
  54754. var textureSize = this.getSize();
  54755. var newTexture = new DynamicTexture(this.name, textureSize, scene, this._generateMipMaps);
  54756. // Base texture
  54757. newTexture.hasAlpha = this.hasAlpha;
  54758. newTexture.level = this.level;
  54759. // Dynamic Texture
  54760. newTexture.wrapU = this.wrapU;
  54761. newTexture.wrapV = this.wrapV;
  54762. return newTexture;
  54763. };
  54764. DynamicTexture.prototype._rebuild = function () {
  54765. this.update();
  54766. };
  54767. return DynamicTexture;
  54768. }(BABYLON.Texture));
  54769. BABYLON.DynamicTexture = DynamicTexture;
  54770. })(BABYLON || (BABYLON = {}));
  54771. //# sourceMappingURL=babylon.dynamicTexture.js.map
  54772. var BABYLON;
  54773. (function (BABYLON) {
  54774. var VideoTexture = /** @class */ (function (_super) {
  54775. __extends(VideoTexture, _super);
  54776. /**
  54777. * Creates a video texture.
  54778. * Sample : https://doc.babylonjs.com/how_to/video_texture
  54779. * @param {string | null} name optional name, will detect from video source, if not defined
  54780. * @param {(string | string[] | HTMLVideoElement)} src can be used to provide an url, array of urls or an already setup HTML video element.
  54781. * @param {BABYLON.Scene} scene is obviously the current scene.
  54782. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  54783. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  54784. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  54785. * @param {VideoTextureSettings} [settings] allows finer control over video usage
  54786. */
  54787. function VideoTexture(name, src, scene, generateMipMaps, invertY, samplingMode, settings) {
  54788. if (generateMipMaps === void 0) { generateMipMaps = false; }
  54789. if (invertY === void 0) { invertY = false; }
  54790. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  54791. if (settings === void 0) { settings = {
  54792. autoPlay: true,
  54793. loop: true,
  54794. autoUpdateTexture: true,
  54795. }; }
  54796. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  54797. _this._createInternalTexture = function () {
  54798. if (_this._texture != null) {
  54799. return;
  54800. }
  54801. if (!_this._engine.needPOTTextures ||
  54802. (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight))) {
  54803. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  54804. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  54805. }
  54806. else {
  54807. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  54808. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  54809. _this._generateMipMaps = false;
  54810. }
  54811. _this._texture = _this._engine.createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, _this._generateMipMaps, _this._samplingMode);
  54812. _this._texture.isReady = true;
  54813. _this._updateInternalTexture();
  54814. };
  54815. _this.reset = function () {
  54816. if (_this._texture == null) {
  54817. return;
  54818. }
  54819. _this._texture.dispose();
  54820. _this._texture = null;
  54821. };
  54822. _this._updateInternalTexture = function (e) {
  54823. if (_this._texture == null || !_this._texture.isReady) {
  54824. return;
  54825. }
  54826. if (_this.video.readyState < _this.video.HAVE_CURRENT_DATA) {
  54827. return;
  54828. }
  54829. _this._engine.updateVideoTexture(_this._texture, _this.video, _this._invertY);
  54830. };
  54831. _this._engine = _this.getScene().getEngine();
  54832. _this._generateMipMaps = generateMipMaps;
  54833. _this._samplingMode = samplingMode;
  54834. _this.autoUpdateTexture = settings.autoUpdateTexture;
  54835. _this.name = name || _this._getName(src);
  54836. _this.video = _this._getVideo(src);
  54837. if (settings.autoPlay !== undefined) {
  54838. _this.video.autoplay = settings.autoPlay;
  54839. }
  54840. if (settings.loop !== undefined) {
  54841. _this.video.loop = settings.loop;
  54842. }
  54843. _this.video.addEventListener("canplay", _this._createInternalTexture);
  54844. _this.video.addEventListener("paused", _this._updateInternalTexture);
  54845. _this.video.addEventListener("seeked", _this._updateInternalTexture);
  54846. _this.video.addEventListener("emptied", _this.reset);
  54847. if (_this.video.readyState >= _this.video.HAVE_CURRENT_DATA) {
  54848. _this._createInternalTexture();
  54849. }
  54850. return _this;
  54851. }
  54852. VideoTexture.prototype._getName = function (src) {
  54853. if (src instanceof HTMLVideoElement) {
  54854. return src.currentSrc;
  54855. }
  54856. if (typeof src === "object") {
  54857. return src.toString();
  54858. }
  54859. return src;
  54860. };
  54861. ;
  54862. VideoTexture.prototype._getVideo = function (src) {
  54863. if (src instanceof HTMLVideoElement) {
  54864. return src;
  54865. }
  54866. var video = document.createElement("video");
  54867. if (typeof src === "string") {
  54868. video.src = src;
  54869. }
  54870. else {
  54871. src.forEach(function (url) {
  54872. var source = document.createElement("source");
  54873. source.src = url;
  54874. video.appendChild(source);
  54875. });
  54876. }
  54877. return video;
  54878. };
  54879. ;
  54880. /**
  54881. * Internal method to initiate `update`.
  54882. */
  54883. VideoTexture.prototype._rebuild = function () {
  54884. this.update();
  54885. };
  54886. /**
  54887. * Update Texture in the `auto` mode. Does not do anything if `settings.autoUpdateTexture` is false.
  54888. */
  54889. VideoTexture.prototype.update = function () {
  54890. if (!this.autoUpdateTexture) {
  54891. // Expecting user to call `updateTexture` manually
  54892. return;
  54893. }
  54894. this.updateTexture(true);
  54895. };
  54896. /**
  54897. * Update Texture in `manual` mode. Does not do anything if not visible or paused.
  54898. * @param isVisible Visibility state, detected by user using `scene.getActiveMeshes()` or othervise.
  54899. */
  54900. VideoTexture.prototype.updateTexture = function (isVisible) {
  54901. if (!isVisible) {
  54902. return;
  54903. }
  54904. if (this.video.paused) {
  54905. return;
  54906. }
  54907. this._updateInternalTexture();
  54908. };
  54909. /**
  54910. * Change video content. Changing video instance or setting multiple urls (as in constructor) is not supported.
  54911. * @param url New url.
  54912. */
  54913. VideoTexture.prototype.updateURL = function (url) {
  54914. this.video.src = url;
  54915. };
  54916. VideoTexture.prototype.dispose = function () {
  54917. _super.prototype.dispose.call(this);
  54918. this.video.removeEventListener("canplay", this._createInternalTexture);
  54919. this.video.removeEventListener("paused", this._updateInternalTexture);
  54920. this.video.removeEventListener("seeked", this._updateInternalTexture);
  54921. this.video.removeEventListener("emptied", this.reset);
  54922. };
  54923. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  54924. var video = document.createElement("video");
  54925. var constraintsDeviceId;
  54926. if (constraints && constraints.deviceId) {
  54927. constraintsDeviceId = {
  54928. exact: constraints.deviceId,
  54929. };
  54930. }
  54931. navigator.getUserMedia =
  54932. navigator.getUserMedia ||
  54933. navigator.webkitGetUserMedia ||
  54934. navigator.mozGetUserMedia ||
  54935. navigator.msGetUserMedia;
  54936. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  54937. if (navigator.getUserMedia) {
  54938. navigator.getUserMedia({
  54939. video: {
  54940. deviceId: constraintsDeviceId,
  54941. width: {
  54942. min: (constraints && constraints.minWidth) || 256,
  54943. max: (constraints && constraints.maxWidth) || 640,
  54944. },
  54945. height: {
  54946. min: (constraints && constraints.minHeight) || 256,
  54947. max: (constraints && constraints.maxHeight) || 480,
  54948. },
  54949. },
  54950. }, function (stream) {
  54951. if (video.mozSrcObject !== undefined) {
  54952. // hack for Firefox < 19
  54953. video.mozSrcObject = stream;
  54954. }
  54955. else {
  54956. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  54957. }
  54958. video.play();
  54959. if (onReady) {
  54960. onReady(new VideoTexture("video", video, scene, true, true));
  54961. }
  54962. }, function (e) {
  54963. BABYLON.Tools.Error(e.name);
  54964. });
  54965. }
  54966. };
  54967. return VideoTexture;
  54968. }(BABYLON.Texture));
  54969. BABYLON.VideoTexture = VideoTexture;
  54970. })(BABYLON || (BABYLON = {}));
  54971. //# sourceMappingURL=babylon.videoTexture.js.map
  54972. var BABYLON;
  54973. (function (BABYLON) {
  54974. var RawTexture = /** @class */ (function (_super) {
  54975. __extends(RawTexture, _super);
  54976. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode, type) {
  54977. if (generateMipMaps === void 0) { generateMipMaps = true; }
  54978. if (invertY === void 0) { invertY = false; }
  54979. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  54980. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  54981. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  54982. _this.format = format;
  54983. _this._engine = scene.getEngine();
  54984. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode, null, type);
  54985. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  54986. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  54987. return _this;
  54988. }
  54989. RawTexture.prototype.update = function (data) {
  54990. this._engine.updateRawTexture(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  54991. };
  54992. // Statics
  54993. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  54994. if (generateMipMaps === void 0) { generateMipMaps = true; }
  54995. if (invertY === void 0) { invertY = false; }
  54996. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  54997. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  54998. };
  54999. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  55000. if (generateMipMaps === void 0) { generateMipMaps = true; }
  55001. if (invertY === void 0) { invertY = false; }
  55002. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  55003. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  55004. };
  55005. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  55006. if (generateMipMaps === void 0) { generateMipMaps = true; }
  55007. if (invertY === void 0) { invertY = false; }
  55008. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  55009. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  55010. };
  55011. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  55012. if (generateMipMaps === void 0) { generateMipMaps = true; }
  55013. if (invertY === void 0) { invertY = false; }
  55014. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  55015. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  55016. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode, type);
  55017. };
  55018. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  55019. if (generateMipMaps === void 0) { generateMipMaps = true; }
  55020. if (invertY === void 0) { invertY = false; }
  55021. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  55022. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  55023. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode, type);
  55024. };
  55025. return RawTexture;
  55026. }(BABYLON.Texture));
  55027. BABYLON.RawTexture = RawTexture;
  55028. })(BABYLON || (BABYLON = {}));
  55029. //# sourceMappingURL=babylon.rawTexture.js.map
  55030. var BABYLON;
  55031. (function (BABYLON) {
  55032. var PostProcess = /** @class */ (function () {
  55033. function PostProcess(name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  55034. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  55035. if (defines === void 0) { defines = null; }
  55036. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  55037. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  55038. if (blockCompilation === void 0) { blockCompilation = false; }
  55039. this.name = name;
  55040. this.width = -1;
  55041. this.height = -1;
  55042. this.autoClear = true;
  55043. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  55044. this.animations = new Array();
  55045. /*
  55046. Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  55047. Can only be used on a single postprocess or on the last one of a chain.
  55048. */
  55049. this.enablePixelPerfectMode = false;
  55050. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  55051. this.alwaysForcePOT = false;
  55052. this.samples = 1;
  55053. this.adaptScaleToCurrentViewport = false;
  55054. this._reusable = false;
  55055. this._textures = new BABYLON.SmartArray(2);
  55056. this._currentRenderTextureInd = 0;
  55057. this._scaleRatio = new BABYLON.Vector2(1, 1);
  55058. this._texelSize = BABYLON.Vector2.Zero();
  55059. // Events
  55060. /**
  55061. * An event triggered when the postprocess is activated.
  55062. * @type {BABYLON.Observable}
  55063. */
  55064. this.onActivateObservable = new BABYLON.Observable();
  55065. /**
  55066. * An event triggered when the postprocess changes its size.
  55067. * @type {BABYLON.Observable}
  55068. */
  55069. this.onSizeChangedObservable = new BABYLON.Observable();
  55070. /**
  55071. * An event triggered when the postprocess applies its effect.
  55072. * @type {BABYLON.Observable}
  55073. */
  55074. this.onApplyObservable = new BABYLON.Observable();
  55075. /**
  55076. * An event triggered before rendering the postprocess
  55077. * @type {BABYLON.Observable}
  55078. */
  55079. this.onBeforeRenderObservable = new BABYLON.Observable();
  55080. /**
  55081. * An event triggered after rendering the postprocess
  55082. * @type {BABYLON.Observable}
  55083. */
  55084. this.onAfterRenderObservable = new BABYLON.Observable();
  55085. if (camera != null) {
  55086. this._camera = camera;
  55087. this._scene = camera.getScene();
  55088. camera.attachPostProcess(this);
  55089. this._engine = this._scene.getEngine();
  55090. this._scene.postProcesses.push(this);
  55091. }
  55092. else if (engine) {
  55093. this._engine = engine;
  55094. this._engine.postProcesses.push(this);
  55095. }
  55096. this._options = options;
  55097. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  55098. this._reusable = reusable || false;
  55099. this._textureType = textureType;
  55100. this._samplers = samplers || [];
  55101. this._samplers.push("textureSampler");
  55102. this._fragmentUrl = fragmentUrl;
  55103. this._vertexUrl = vertexUrl;
  55104. this._parameters = parameters || [];
  55105. this._parameters.push("scale");
  55106. this._indexParameters = indexParameters;
  55107. if (!blockCompilation) {
  55108. this.updateEffect(defines);
  55109. }
  55110. }
  55111. Object.defineProperty(PostProcess.prototype, "onActivate", {
  55112. set: function (callback) {
  55113. if (this._onActivateObserver) {
  55114. this.onActivateObservable.remove(this._onActivateObserver);
  55115. }
  55116. if (callback) {
  55117. this._onActivateObserver = this.onActivateObservable.add(callback);
  55118. }
  55119. },
  55120. enumerable: true,
  55121. configurable: true
  55122. });
  55123. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  55124. set: function (callback) {
  55125. if (this._onSizeChangedObserver) {
  55126. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  55127. }
  55128. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  55129. },
  55130. enumerable: true,
  55131. configurable: true
  55132. });
  55133. Object.defineProperty(PostProcess.prototype, "onApply", {
  55134. set: function (callback) {
  55135. if (this._onApplyObserver) {
  55136. this.onApplyObservable.remove(this._onApplyObserver);
  55137. }
  55138. this._onApplyObserver = this.onApplyObservable.add(callback);
  55139. },
  55140. enumerable: true,
  55141. configurable: true
  55142. });
  55143. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  55144. set: function (callback) {
  55145. if (this._onBeforeRenderObserver) {
  55146. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  55147. }
  55148. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  55149. },
  55150. enumerable: true,
  55151. configurable: true
  55152. });
  55153. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  55154. set: function (callback) {
  55155. if (this._onAfterRenderObserver) {
  55156. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  55157. }
  55158. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  55159. },
  55160. enumerable: true,
  55161. configurable: true
  55162. });
  55163. Object.defineProperty(PostProcess.prototype, "outputTexture", {
  55164. get: function () {
  55165. return this._textures.data[this._currentRenderTextureInd];
  55166. },
  55167. set: function (value) {
  55168. this._forcedOutputTexture = value;
  55169. },
  55170. enumerable: true,
  55171. configurable: true
  55172. });
  55173. PostProcess.prototype.getCamera = function () {
  55174. return this._camera;
  55175. };
  55176. Object.defineProperty(PostProcess.prototype, "texelSize", {
  55177. get: function () {
  55178. if (this._shareOutputWithPostProcess) {
  55179. return this._shareOutputWithPostProcess.texelSize;
  55180. }
  55181. if (this._forcedOutputTexture) {
  55182. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture.width, 1.0 / this._forcedOutputTexture.height);
  55183. }
  55184. return this._texelSize;
  55185. },
  55186. enumerable: true,
  55187. configurable: true
  55188. });
  55189. PostProcess.prototype.getEngine = function () {
  55190. return this._engine;
  55191. };
  55192. PostProcess.prototype.getEffect = function () {
  55193. return this._effect;
  55194. };
  55195. PostProcess.prototype.shareOutputWith = function (postProcess) {
  55196. this._disposeTextures();
  55197. this._shareOutputWithPostProcess = postProcess;
  55198. return this;
  55199. };
  55200. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  55201. if (defines === void 0) { defines = null; }
  55202. if (uniforms === void 0) { uniforms = null; }
  55203. if (samplers === void 0) { samplers = null; }
  55204. 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);
  55205. };
  55206. PostProcess.prototype.isReusable = function () {
  55207. return this._reusable;
  55208. };
  55209. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  55210. PostProcess.prototype.markTextureDirty = function () {
  55211. this.width = -1;
  55212. };
  55213. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  55214. var _this = this;
  55215. if (sourceTexture === void 0) { sourceTexture = null; }
  55216. camera = camera || this._camera;
  55217. var scene = camera.getScene();
  55218. var engine = scene.getEngine();
  55219. var maxSize = engine.getCaps().maxTextureSize;
  55220. var requiredWidth = ((sourceTexture ? sourceTexture.width : this._engine.getRenderWidth(true)) * this._options) | 0;
  55221. var requiredHeight = ((sourceTexture ? sourceTexture.height : this._engine.getRenderHeight(true)) * this._options) | 0;
  55222. var desiredWidth = (this._options.width || requiredWidth);
  55223. var desiredHeight = this._options.height || requiredHeight;
  55224. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  55225. if (this.adaptScaleToCurrentViewport) {
  55226. var currentViewport = engine.currentViewport;
  55227. if (currentViewport) {
  55228. desiredWidth *= currentViewport.width;
  55229. desiredHeight *= currentViewport.height;
  55230. }
  55231. }
  55232. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  55233. if (!this._options.width) {
  55234. desiredWidth = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;
  55235. }
  55236. if (!this._options.height) {
  55237. desiredHeight = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;
  55238. }
  55239. }
  55240. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  55241. if (this._textures.length > 0) {
  55242. for (var i = 0; i < this._textures.length; i++) {
  55243. this._engine._releaseTexture(this._textures.data[i]);
  55244. }
  55245. this._textures.reset();
  55246. }
  55247. this.width = desiredWidth;
  55248. this.height = desiredHeight;
  55249. var textureSize = { width: this.width, height: this.height };
  55250. var textureOptions = {
  55251. generateMipMaps: false,
  55252. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  55253. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  55254. samplingMode: this.renderTargetSamplingMode,
  55255. type: this._textureType
  55256. };
  55257. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  55258. if (this._reusable) {
  55259. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  55260. }
  55261. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  55262. this.onSizeChangedObservable.notifyObservers(this);
  55263. }
  55264. this._textures.forEach(function (texture) {
  55265. if (texture.samples !== _this.samples) {
  55266. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  55267. }
  55268. });
  55269. }
  55270. var target;
  55271. if (this._shareOutputWithPostProcess) {
  55272. target = this._shareOutputWithPostProcess.outputTexture;
  55273. }
  55274. else if (this._forcedOutputTexture) {
  55275. target = this._forcedOutputTexture;
  55276. this.width = this._forcedOutputTexture.width;
  55277. this.height = this._forcedOutputTexture.height;
  55278. }
  55279. else {
  55280. target = this.outputTexture;
  55281. }
  55282. if (this.enablePixelPerfectMode) {
  55283. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  55284. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, true);
  55285. }
  55286. else {
  55287. this._scaleRatio.copyFromFloats(1, 1);
  55288. this._engine.bindFramebuffer(target, 0, undefined, undefined, true);
  55289. }
  55290. this.onActivateObservable.notifyObservers(camera);
  55291. // Clear
  55292. if (this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  55293. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, true, true, true);
  55294. }
  55295. if (this._reusable) {
  55296. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  55297. }
  55298. };
  55299. Object.defineProperty(PostProcess.prototype, "isSupported", {
  55300. get: function () {
  55301. return this._effect.isSupported;
  55302. },
  55303. enumerable: true,
  55304. configurable: true
  55305. });
  55306. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  55307. get: function () {
  55308. if (this._shareOutputWithPostProcess) {
  55309. return this._shareOutputWithPostProcess.aspectRatio;
  55310. }
  55311. if (this._forcedOutputTexture) {
  55312. return this._forcedOutputTexture.width / this._forcedOutputTexture.height;
  55313. }
  55314. return this.width / this.height;
  55315. },
  55316. enumerable: true,
  55317. configurable: true
  55318. });
  55319. /**
  55320. * Get a value indicating if the post-process is ready to be used
  55321. * @returns true if the post-process is ready (shader is compiled)
  55322. */
  55323. PostProcess.prototype.isReady = function () {
  55324. return this._effect && this._effect.isReady();
  55325. };
  55326. PostProcess.prototype.apply = function () {
  55327. // Check
  55328. if (!this._effect || !this._effect.isReady())
  55329. return null;
  55330. // States
  55331. this._engine.enableEffect(this._effect);
  55332. this._engine.setState(false);
  55333. this._engine.setDepthBuffer(false);
  55334. this._engine.setDepthWrite(false);
  55335. // Alpha
  55336. this._engine.setAlphaMode(this.alphaMode);
  55337. if (this.alphaConstants) {
  55338. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  55339. }
  55340. // Texture
  55341. var source;
  55342. if (this._shareOutputWithPostProcess) {
  55343. source = this._shareOutputWithPostProcess.outputTexture;
  55344. }
  55345. else if (this._forcedOutputTexture) {
  55346. source = this._forcedOutputTexture;
  55347. }
  55348. else {
  55349. source = this.outputTexture;
  55350. }
  55351. this._effect._bindTexture("textureSampler", source);
  55352. // Parameters
  55353. this._effect.setVector2("scale", this._scaleRatio);
  55354. this.onApplyObservable.notifyObservers(this._effect);
  55355. return this._effect;
  55356. };
  55357. PostProcess.prototype._disposeTextures = function () {
  55358. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  55359. return;
  55360. }
  55361. if (this._textures.length > 0) {
  55362. for (var i = 0; i < this._textures.length; i++) {
  55363. this._engine._releaseTexture(this._textures.data[i]);
  55364. }
  55365. }
  55366. this._textures.dispose();
  55367. };
  55368. PostProcess.prototype.dispose = function (camera) {
  55369. camera = camera || this._camera;
  55370. this._disposeTextures();
  55371. if (this._scene) {
  55372. var index_1 = this._scene.postProcesses.indexOf(this);
  55373. if (index_1 !== -1) {
  55374. this._scene.postProcesses.splice(index_1, 1);
  55375. }
  55376. }
  55377. else {
  55378. var index_2 = this._engine.postProcesses.indexOf(this);
  55379. if (index_2 !== -1) {
  55380. this._engine.postProcesses.splice(index_2, 1);
  55381. }
  55382. }
  55383. if (!camera) {
  55384. return;
  55385. }
  55386. camera.detachPostProcess(this);
  55387. var index = camera._postProcesses.indexOf(this);
  55388. if (index === 0 && camera._postProcesses.length > 0) {
  55389. this._camera._postProcesses[0].markTextureDirty();
  55390. }
  55391. this.onActivateObservable.clear();
  55392. this.onAfterRenderObservable.clear();
  55393. this.onApplyObservable.clear();
  55394. this.onBeforeRenderObservable.clear();
  55395. this.onSizeChangedObservable.clear();
  55396. };
  55397. return PostProcess;
  55398. }());
  55399. BABYLON.PostProcess = PostProcess;
  55400. })(BABYLON || (BABYLON = {}));
  55401. //# sourceMappingURL=babylon.postProcess.js.map
  55402. var BABYLON;
  55403. (function (BABYLON) {
  55404. var PassPostProcess = /** @class */ (function (_super) {
  55405. __extends(PassPostProcess, _super);
  55406. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  55407. if (camera === void 0) { camera = null; }
  55408. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  55409. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, undefined, textureType) || this;
  55410. }
  55411. return PassPostProcess;
  55412. }(BABYLON.PostProcess));
  55413. BABYLON.PassPostProcess = PassPostProcess;
  55414. })(BABYLON || (BABYLON = {}));
  55415. //# sourceMappingURL=babylon.passPostProcess.js.map
  55416. var __assign = (this && this.__assign) || Object.assign || function(t) {
  55417. for (var s, i = 1, n = arguments.length; i < n; i++) {
  55418. s = arguments[i];
  55419. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  55420. t[p] = s[p];
  55421. }
  55422. return t;
  55423. };
  55424. var BABYLON;
  55425. (function (BABYLON) {
  55426. var ShadowGenerator = /** @class */ (function () {
  55427. /**
  55428. * Creates a ShadowGenerator object.
  55429. * A ShadowGenerator is the required tool to use the shadows.
  55430. * Each light casting shadows needs to use its own ShadowGenerator.
  55431. * Required parameters :
  55432. * - `mapSize` (integer): the size of the texture what stores the shadows. Example : 1024.
  55433. * - `light`: the light object generating the shadows.
  55434. * - `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.
  55435. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  55436. */
  55437. function ShadowGenerator(mapSize, light, useFullFloatFirst) {
  55438. // Members
  55439. this._bias = 0.00005;
  55440. this._blurBoxOffset = 1;
  55441. this._blurScale = 2;
  55442. this._blurKernel = 1;
  55443. this._useKernelBlur = false;
  55444. this._filter = ShadowGenerator.FILTER_NONE;
  55445. this._darkness = 0;
  55446. this._transparencyShadow = false;
  55447. /**
  55448. * Controls the extent to which the shadows fade out at the edge of the frustum
  55449. * Used only by directionals and spots
  55450. */
  55451. this.frustumEdgeFalloff = 0;
  55452. this.forceBackFacesOnly = false;
  55453. this._lightDirection = BABYLON.Vector3.Zero();
  55454. this._viewMatrix = BABYLON.Matrix.Zero();
  55455. this._projectionMatrix = BABYLON.Matrix.Zero();
  55456. this._transformMatrix = BABYLON.Matrix.Zero();
  55457. this._currentFaceIndex = 0;
  55458. this._currentFaceIndexCache = 0;
  55459. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  55460. this._mapSize = mapSize;
  55461. this._light = light;
  55462. this._scene = light.getScene();
  55463. light._shadowGenerator = this;
  55464. // Texture type fallback from float to int if not supported.
  55465. var caps = this._scene.getEngine().getCaps();
  55466. if (!useFullFloatFirst) {
  55467. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  55468. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  55469. }
  55470. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  55471. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  55472. }
  55473. else {
  55474. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  55475. }
  55476. }
  55477. else {
  55478. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  55479. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  55480. }
  55481. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  55482. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  55483. }
  55484. else {
  55485. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  55486. }
  55487. }
  55488. this._initializeGenerator();
  55489. }
  55490. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  55491. // Static
  55492. get: function () {
  55493. return ShadowGenerator._FILTER_NONE;
  55494. },
  55495. enumerable: true,
  55496. configurable: true
  55497. });
  55498. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  55499. get: function () {
  55500. return ShadowGenerator._FILTER_POISSONSAMPLING;
  55501. },
  55502. enumerable: true,
  55503. configurable: true
  55504. });
  55505. Object.defineProperty(ShadowGenerator, "FILTER_EXPONENTIALSHADOWMAP", {
  55506. get: function () {
  55507. return ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP;
  55508. },
  55509. enumerable: true,
  55510. configurable: true
  55511. });
  55512. Object.defineProperty(ShadowGenerator, "FILTER_BLUREXPONENTIALSHADOWMAP", {
  55513. get: function () {
  55514. return ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP;
  55515. },
  55516. enumerable: true,
  55517. configurable: true
  55518. });
  55519. Object.defineProperty(ShadowGenerator, "FILTER_CLOSEEXPONENTIALSHADOWMAP", {
  55520. get: function () {
  55521. return ShadowGenerator._FILTER_CLOSEEXPONENTIALSHADOWMAP;
  55522. },
  55523. enumerable: true,
  55524. configurable: true
  55525. });
  55526. Object.defineProperty(ShadowGenerator, "FILTER_BLURCLOSEEXPONENTIALSHADOWMAP", {
  55527. get: function () {
  55528. return ShadowGenerator._FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  55529. },
  55530. enumerable: true,
  55531. configurable: true
  55532. });
  55533. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  55534. get: function () {
  55535. return this._bias;
  55536. },
  55537. set: function (bias) {
  55538. this._bias = bias;
  55539. },
  55540. enumerable: true,
  55541. configurable: true
  55542. });
  55543. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  55544. get: function () {
  55545. return this._blurBoxOffset;
  55546. },
  55547. set: function (value) {
  55548. if (this._blurBoxOffset === value) {
  55549. return;
  55550. }
  55551. this._blurBoxOffset = value;
  55552. this._disposeBlurPostProcesses();
  55553. },
  55554. enumerable: true,
  55555. configurable: true
  55556. });
  55557. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  55558. get: function () {
  55559. return this._blurScale;
  55560. },
  55561. set: function (value) {
  55562. if (this._blurScale === value) {
  55563. return;
  55564. }
  55565. this._blurScale = value;
  55566. this._disposeBlurPostProcesses();
  55567. },
  55568. enumerable: true,
  55569. configurable: true
  55570. });
  55571. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  55572. get: function () {
  55573. return this._blurKernel;
  55574. },
  55575. set: function (value) {
  55576. if (this._blurKernel === value) {
  55577. return;
  55578. }
  55579. this._blurKernel = value;
  55580. this._disposeBlurPostProcesses();
  55581. },
  55582. enumerable: true,
  55583. configurable: true
  55584. });
  55585. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  55586. get: function () {
  55587. return this._useKernelBlur;
  55588. },
  55589. set: function (value) {
  55590. if (this._useKernelBlur === value) {
  55591. return;
  55592. }
  55593. this._useKernelBlur = value;
  55594. this._disposeBlurPostProcesses();
  55595. },
  55596. enumerable: true,
  55597. configurable: true
  55598. });
  55599. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  55600. get: function () {
  55601. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  55602. },
  55603. set: function (value) {
  55604. this._depthScale = value;
  55605. },
  55606. enumerable: true,
  55607. configurable: true
  55608. });
  55609. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  55610. get: function () {
  55611. return this._filter;
  55612. },
  55613. set: function (value) {
  55614. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  55615. if (this._light.needCube()) {
  55616. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  55617. this.useExponentialShadowMap = true;
  55618. return;
  55619. }
  55620. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  55621. this.useCloseExponentialShadowMap = true;
  55622. return;
  55623. }
  55624. }
  55625. if (this._filter === value) {
  55626. return;
  55627. }
  55628. this._filter = value;
  55629. this._disposeBlurPostProcesses();
  55630. this._applyFilterValues();
  55631. this._light._markMeshesAsLightDirty();
  55632. },
  55633. enumerable: true,
  55634. configurable: true
  55635. });
  55636. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  55637. get: function () {
  55638. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  55639. },
  55640. set: function (value) {
  55641. if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) {
  55642. return;
  55643. }
  55644. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  55645. },
  55646. enumerable: true,
  55647. configurable: true
  55648. });
  55649. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  55650. get: function () {
  55651. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  55652. return this.useExponentialShadowMap;
  55653. },
  55654. set: function (value) {
  55655. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  55656. this.useExponentialShadowMap = value;
  55657. },
  55658. enumerable: true,
  55659. configurable: true
  55660. });
  55661. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  55662. get: function () {
  55663. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  55664. return this.useBlurExponentialShadowMap;
  55665. },
  55666. set: function (value) {
  55667. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  55668. this.useBlurExponentialShadowMap = value;
  55669. },
  55670. enumerable: true,
  55671. configurable: true
  55672. });
  55673. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  55674. get: function () {
  55675. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  55676. },
  55677. set: function (value) {
  55678. if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) {
  55679. return;
  55680. }
  55681. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  55682. },
  55683. enumerable: true,
  55684. configurable: true
  55685. });
  55686. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  55687. get: function () {
  55688. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  55689. },
  55690. set: function (value) {
  55691. if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  55692. return;
  55693. }
  55694. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  55695. },
  55696. enumerable: true,
  55697. configurable: true
  55698. });
  55699. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  55700. get: function () {
  55701. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  55702. },
  55703. set: function (value) {
  55704. if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) {
  55705. return;
  55706. }
  55707. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  55708. },
  55709. enumerable: true,
  55710. configurable: true
  55711. });
  55712. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  55713. get: function () {
  55714. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  55715. },
  55716. set: function (value) {
  55717. if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  55718. return;
  55719. }
  55720. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  55721. },
  55722. enumerable: true,
  55723. configurable: true
  55724. });
  55725. /**
  55726. * Returns the darkness value (float).
  55727. */
  55728. ShadowGenerator.prototype.getDarkness = function () {
  55729. return this._darkness;
  55730. };
  55731. /**
  55732. * Sets the ShadowGenerator darkness value (float <= 1.0).
  55733. * Returns the ShadowGenerator.
  55734. */
  55735. ShadowGenerator.prototype.setDarkness = function (darkness) {
  55736. if (darkness >= 1.0)
  55737. this._darkness = 1.0;
  55738. else if (darkness <= 0.0)
  55739. this._darkness = 0.0;
  55740. else
  55741. this._darkness = darkness;
  55742. return this;
  55743. };
  55744. /**
  55745. * Sets the ability to have transparent shadow (boolean).
  55746. * Returns the ShadowGenerator.
  55747. */
  55748. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  55749. this._transparencyShadow = hasShadow;
  55750. return this;
  55751. };
  55752. /**
  55753. * Returns a RenderTargetTexture object : the shadow map texture.
  55754. */
  55755. ShadowGenerator.prototype.getShadowMap = function () {
  55756. return this._shadowMap;
  55757. };
  55758. /**
  55759. * Returns the most ready computed shadow map as a RenderTargetTexture object.
  55760. */
  55761. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  55762. if (this._shadowMap2) {
  55763. return this._shadowMap2;
  55764. }
  55765. return this._shadowMap;
  55766. };
  55767. /**
  55768. * Helper function to add a mesh and its descendants to the list of shadow casters
  55769. * @param mesh Mesh to add
  55770. * @param includeDescendants boolean indicating if the descendants should be added. Default to true
  55771. */
  55772. ShadowGenerator.prototype.addShadowCaster = function (mesh, includeDescendants) {
  55773. if (includeDescendants === void 0) { includeDescendants = true; }
  55774. if (!this._shadowMap) {
  55775. return this;
  55776. }
  55777. if (!this._shadowMap.renderList) {
  55778. this._shadowMap.renderList = [];
  55779. }
  55780. this._shadowMap.renderList.push(mesh);
  55781. if (includeDescendants) {
  55782. (_a = this._shadowMap.renderList).push.apply(_a, mesh.getChildMeshes());
  55783. }
  55784. return this;
  55785. var _a;
  55786. };
  55787. /**
  55788. * Helper function to remove a mesh and its descendants from the list of shadow casters
  55789. * @param mesh Mesh to remove
  55790. * @param includeDescendants boolean indicating if the descendants should be removed. Default to true
  55791. */
  55792. ShadowGenerator.prototype.removeShadowCaster = function (mesh, includeDescendants) {
  55793. if (includeDescendants === void 0) { includeDescendants = true; }
  55794. if (!this._shadowMap || !this._shadowMap.renderList) {
  55795. return this;
  55796. }
  55797. var index = this._shadowMap.renderList.indexOf(mesh);
  55798. if (index !== -1) {
  55799. this._shadowMap.renderList.splice(index, 1);
  55800. }
  55801. if (includeDescendants) {
  55802. for (var _i = 0, _a = mesh.getChildren(); _i < _a.length; _i++) {
  55803. var child = _a[_i];
  55804. this.removeShadowCaster(child);
  55805. }
  55806. }
  55807. return this;
  55808. };
  55809. /**
  55810. * Returns the associated light object.
  55811. */
  55812. ShadowGenerator.prototype.getLight = function () {
  55813. return this._light;
  55814. };
  55815. ShadowGenerator.prototype._initializeGenerator = function () {
  55816. this._light._markMeshesAsLightDirty();
  55817. this._initializeShadowMap();
  55818. };
  55819. ShadowGenerator.prototype._initializeShadowMap = function () {
  55820. var _this = this;
  55821. // Render target
  55822. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  55823. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  55824. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  55825. this._shadowMap.anisotropicFilteringLevel = 1;
  55826. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  55827. this._shadowMap.renderParticles = false;
  55828. this._shadowMap.ignoreCameraViewport = true;
  55829. // Record Face Index before render.
  55830. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  55831. _this._currentFaceIndex = faceIndex;
  55832. });
  55833. // Custom render function.
  55834. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  55835. // Blur if required afer render.
  55836. this._shadowMap.onAfterUnbindObservable.add(function () {
  55837. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  55838. return;
  55839. }
  55840. var shadowMap = _this.getShadowMapForRendering();
  55841. if (shadowMap) {
  55842. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, shadowMap.getInternalTexture(), true);
  55843. }
  55844. });
  55845. // Clear according to the chosen filter.
  55846. this._shadowMap.onClearObservable.add(function (engine) {
  55847. if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  55848. engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true, true);
  55849. }
  55850. else {
  55851. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  55852. }
  55853. });
  55854. };
  55855. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  55856. var _this = this;
  55857. var engine = this._scene.getEngine();
  55858. var targetSize = this._mapSize / this.blurScale;
  55859. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  55860. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  55861. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  55862. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  55863. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  55864. }
  55865. if (this.useKernelBlur) {
  55866. 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);
  55867. this._kernelBlurXPostprocess.width = targetSize;
  55868. this._kernelBlurXPostprocess.height = targetSize;
  55869. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  55870. effect.setTexture("textureSampler", _this._shadowMap);
  55871. });
  55872. 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);
  55873. this._kernelBlurXPostprocess.autoClear = false;
  55874. this._kernelBlurYPostprocess.autoClear = false;
  55875. if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  55876. this._kernelBlurXPostprocess.packedFloat = true;
  55877. this._kernelBlurYPostprocess.packedFloat = true;
  55878. }
  55879. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  55880. }
  55881. else {
  55882. 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);
  55883. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  55884. effect.setFloat2("screenSize", targetSize, targetSize);
  55885. effect.setTexture("textureSampler", _this._shadowMap);
  55886. });
  55887. this._boxBlurPostprocess.autoClear = false;
  55888. this._blurPostProcesses = [this._boxBlurPostprocess];
  55889. }
  55890. };
  55891. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  55892. var index;
  55893. var engine = this._scene.getEngine();
  55894. if (depthOnlySubMeshes.length) {
  55895. engine.setColorWrite(false);
  55896. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  55897. this._renderSubMeshForShadowMap(depthOnlySubMeshes.data[index]);
  55898. }
  55899. engine.setColorWrite(true);
  55900. }
  55901. for (index = 0; index < opaqueSubMeshes.length; index++) {
  55902. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  55903. }
  55904. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  55905. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  55906. }
  55907. if (this._transparencyShadow) {
  55908. for (index = 0; index < transparentSubMeshes.length; index++) {
  55909. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  55910. }
  55911. }
  55912. };
  55913. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  55914. var _this = this;
  55915. var mesh = subMesh.getRenderingMesh();
  55916. var scene = this._scene;
  55917. var engine = scene.getEngine();
  55918. var material = subMesh.getMaterial();
  55919. if (!material) {
  55920. return;
  55921. }
  55922. // Culling
  55923. engine.setState(material.backFaceCulling);
  55924. // Managing instances
  55925. var batch = mesh._getInstancesRenderList(subMesh._id);
  55926. if (batch.mustReturn) {
  55927. return;
  55928. }
  55929. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  55930. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  55931. engine.enableEffect(this._effect);
  55932. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  55933. this._effect.setFloat2("biasAndScale", this.bias, this.depthScale);
  55934. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  55935. this._effect.setVector3("lightPosition", this.getLight().position);
  55936. if (scene.activeCamera) {
  55937. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  55938. }
  55939. // Alpha test
  55940. if (material && material.needAlphaTesting()) {
  55941. var alphaTexture = material.getAlphaTestTexture();
  55942. if (alphaTexture) {
  55943. this._effect.setTexture("diffuseSampler", alphaTexture);
  55944. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  55945. }
  55946. }
  55947. // Bones
  55948. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  55949. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices((mesh)));
  55950. }
  55951. if (this.forceBackFacesOnly) {
  55952. engine.setState(true, 0, false, true);
  55953. }
  55954. // Draw
  55955. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  55956. if (this.forceBackFacesOnly) {
  55957. engine.setState(true, 0, false, false);
  55958. }
  55959. }
  55960. else {
  55961. // Need to reset refresh rate of the shadowMap
  55962. if (this._shadowMap) {
  55963. this._shadowMap.resetRefreshCounter();
  55964. }
  55965. }
  55966. };
  55967. ShadowGenerator.prototype._applyFilterValues = function () {
  55968. if (!this._shadowMap) {
  55969. return;
  55970. }
  55971. if (this.filter === ShadowGenerator.FILTER_NONE) {
  55972. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  55973. }
  55974. else {
  55975. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  55976. }
  55977. };
  55978. /**
  55979. * Force shader compilation including textures ready check
  55980. */
  55981. ShadowGenerator.prototype.forceCompilation = function (onCompiled, options) {
  55982. var _this = this;
  55983. var localOptions = __assign({ useInstances: false }, options);
  55984. var shadowMap = this.getShadowMap();
  55985. if (!shadowMap) {
  55986. if (onCompiled) {
  55987. onCompiled(this);
  55988. }
  55989. return;
  55990. }
  55991. var renderList = shadowMap.renderList;
  55992. if (!renderList) {
  55993. if (onCompiled) {
  55994. onCompiled(this);
  55995. }
  55996. return;
  55997. }
  55998. var subMeshes = new Array();
  55999. for (var _i = 0, renderList_1 = renderList; _i < renderList_1.length; _i++) {
  56000. var mesh = renderList_1[_i];
  56001. subMeshes.push.apply(subMeshes, mesh.subMeshes);
  56002. }
  56003. if (subMeshes.length === 0) {
  56004. if (onCompiled) {
  56005. onCompiled(this);
  56006. }
  56007. return;
  56008. }
  56009. var currentIndex = 0;
  56010. var checkReady = function () {
  56011. if (!_this._scene || !_this._scene.getEngine()) {
  56012. return;
  56013. }
  56014. while (_this.isReady(subMeshes[currentIndex], localOptions.useInstances)) {
  56015. currentIndex++;
  56016. if (currentIndex >= subMeshes.length) {
  56017. if (onCompiled) {
  56018. onCompiled(_this);
  56019. }
  56020. return;
  56021. }
  56022. }
  56023. setTimeout(checkReady, 16);
  56024. };
  56025. checkReady();
  56026. };
  56027. /**
  56028. * Boolean : true when the ShadowGenerator is finally computed.
  56029. */
  56030. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  56031. var defines = [];
  56032. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  56033. defines.push("#define FLOAT");
  56034. }
  56035. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  56036. defines.push("#define ESM");
  56037. }
  56038. var attribs = [BABYLON.VertexBuffer.PositionKind];
  56039. var mesh = subMesh.getMesh();
  56040. var material = subMesh.getMaterial();
  56041. // Alpha test
  56042. if (material && material.needAlphaTesting()) {
  56043. var alphaTexture = material.getAlphaTestTexture();
  56044. if (alphaTexture) {
  56045. defines.push("#define ALPHATEST");
  56046. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  56047. attribs.push(BABYLON.VertexBuffer.UVKind);
  56048. defines.push("#define UV1");
  56049. }
  56050. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  56051. if (alphaTexture.coordinatesIndex === 1) {
  56052. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  56053. defines.push("#define UV2");
  56054. }
  56055. }
  56056. }
  56057. }
  56058. // Bones
  56059. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  56060. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  56061. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  56062. if (mesh.numBoneInfluencers > 4) {
  56063. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  56064. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  56065. }
  56066. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  56067. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  56068. }
  56069. else {
  56070. defines.push("#define NUM_BONE_INFLUENCERS 0");
  56071. }
  56072. // Instances
  56073. if (useInstances) {
  56074. defines.push("#define INSTANCES");
  56075. attribs.push("world0");
  56076. attribs.push("world1");
  56077. attribs.push("world2");
  56078. attribs.push("world3");
  56079. }
  56080. // Get correct effect
  56081. var join = defines.join("\n");
  56082. if (this._cachedDefines !== join) {
  56083. this._cachedDefines = join;
  56084. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightPosition", "depthValues", "biasAndScale"], ["diffuseSampler"], join);
  56085. }
  56086. if (!this._effect.isReady()) {
  56087. return false;
  56088. }
  56089. if (this.useBlurExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  56090. if (!this._blurPostProcesses || !this._blurPostProcesses.length) {
  56091. this._initializeBlurRTTAndPostProcesses();
  56092. }
  56093. }
  56094. if (this._kernelBlurXPostprocess && !this._kernelBlurXPostprocess.isReady()) {
  56095. return false;
  56096. }
  56097. if (this._kernelBlurYPostprocess && !this._kernelBlurYPostprocess.isReady()) {
  56098. return false;
  56099. }
  56100. if (this._boxBlurPostprocess && !this._boxBlurPostprocess.isReady()) {
  56101. return false;
  56102. }
  56103. return true;
  56104. };
  56105. /**
  56106. * This creates the defines related to the standard BJS materials.
  56107. */
  56108. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  56109. var scene = this._scene;
  56110. var light = this._light;
  56111. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  56112. return;
  56113. }
  56114. defines["SHADOW" + lightIndex] = true;
  56115. if (this.usePoissonSampling) {
  56116. defines["SHADOWPCF" + lightIndex] = true;
  56117. }
  56118. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  56119. defines["SHADOWESM" + lightIndex] = true;
  56120. }
  56121. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  56122. defines["SHADOWCLOSEESM" + lightIndex] = true;
  56123. }
  56124. if (light.needCube()) {
  56125. defines["SHADOWCUBE" + lightIndex] = true;
  56126. }
  56127. };
  56128. /**
  56129. * This binds shadow lights related to the standard BJS materials.
  56130. * It implies the unifroms available on the materials are the standard BJS ones.
  56131. */
  56132. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  56133. var light = this._light;
  56134. var scene = this._scene;
  56135. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  56136. return;
  56137. }
  56138. var camera = scene.activeCamera;
  56139. if (!camera) {
  56140. return;
  56141. }
  56142. var shadowMap = this.getShadowMap();
  56143. if (!shadowMap) {
  56144. return;
  56145. }
  56146. if (!light.needCube()) {
  56147. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  56148. }
  56149. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  56150. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / shadowMap.getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);
  56151. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(camera), this.getLight().getDepthMinZ(camera) + this.getLight().getDepthMaxZ(camera), lightIndex);
  56152. };
  56153. // Methods
  56154. /**
  56155. * Returns a Matrix object : the updated transformation matrix.
  56156. */
  56157. ShadowGenerator.prototype.getTransformMatrix = function () {
  56158. var scene = this._scene;
  56159. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  56160. return this._transformMatrix;
  56161. }
  56162. this._currentRenderID = scene.getRenderId();
  56163. this._currentFaceIndexCache = this._currentFaceIndex;
  56164. var lightPosition = this._light.position;
  56165. if (this._light.computeTransformedInformation()) {
  56166. lightPosition = this._light.transformedPosition;
  56167. }
  56168. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  56169. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  56170. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  56171. }
  56172. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  56173. this._cachedPosition = lightPosition.clone();
  56174. this._cachedDirection = this._lightDirection.clone();
  56175. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  56176. var shadowMap = this.getShadowMap();
  56177. if (shadowMap) {
  56178. var renderList = shadowMap.renderList;
  56179. if (renderList) {
  56180. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, renderList);
  56181. }
  56182. }
  56183. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  56184. }
  56185. return this._transformMatrix;
  56186. };
  56187. ShadowGenerator.prototype.recreateShadowMap = function () {
  56188. var shadowMap = this._shadowMap;
  56189. if (!shadowMap) {
  56190. return;
  56191. }
  56192. // Track render list.
  56193. var renderList = shadowMap.renderList;
  56194. // Clean up existing data.
  56195. this._disposeRTTandPostProcesses();
  56196. // Reinitializes.
  56197. this._initializeGenerator();
  56198. // Reaffect the filter to ensure a correct fallback if necessary.
  56199. this.filter = this.filter;
  56200. // Reaffect the filter.
  56201. this._applyFilterValues();
  56202. // Reaffect Render List.
  56203. this._shadowMap.renderList = renderList;
  56204. };
  56205. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  56206. if (this._shadowMap2) {
  56207. this._shadowMap2.dispose();
  56208. this._shadowMap2 = null;
  56209. }
  56210. if (this._boxBlurPostprocess) {
  56211. this._boxBlurPostprocess.dispose();
  56212. this._boxBlurPostprocess = null;
  56213. }
  56214. if (this._kernelBlurXPostprocess) {
  56215. this._kernelBlurXPostprocess.dispose();
  56216. this._kernelBlurXPostprocess = null;
  56217. }
  56218. if (this._kernelBlurYPostprocess) {
  56219. this._kernelBlurYPostprocess.dispose();
  56220. this._kernelBlurYPostprocess = null;
  56221. }
  56222. this._blurPostProcesses = [];
  56223. };
  56224. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  56225. if (this._shadowMap) {
  56226. this._shadowMap.dispose();
  56227. this._shadowMap = null;
  56228. }
  56229. this._disposeBlurPostProcesses();
  56230. };
  56231. /**
  56232. * Disposes the ShadowGenerator.
  56233. * Returns nothing.
  56234. */
  56235. ShadowGenerator.prototype.dispose = function () {
  56236. this._disposeRTTandPostProcesses();
  56237. if (this._light) {
  56238. this._light._shadowGenerator = null;
  56239. this._light._markMeshesAsLightDirty();
  56240. }
  56241. };
  56242. /**
  56243. * Serializes the ShadowGenerator and returns a serializationObject.
  56244. */
  56245. ShadowGenerator.prototype.serialize = function () {
  56246. var serializationObject = {};
  56247. var shadowMap = this.getShadowMap();
  56248. if (!shadowMap) {
  56249. return serializationObject;
  56250. }
  56251. serializationObject.lightId = this._light.id;
  56252. serializationObject.mapSize = shadowMap.getRenderSize();
  56253. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  56254. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  56255. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  56256. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  56257. serializationObject.usePoissonSampling = this.usePoissonSampling;
  56258. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  56259. serializationObject.depthScale = this.depthScale;
  56260. serializationObject.darkness = this.getDarkness();
  56261. serializationObject.blurBoxOffset = this.blurBoxOffset;
  56262. serializationObject.blurKernel = this.blurKernel;
  56263. serializationObject.blurScale = this.blurScale;
  56264. serializationObject.useKernelBlur = this.useKernelBlur;
  56265. serializationObject.transparencyShadow = this._transparencyShadow;
  56266. serializationObject.renderList = [];
  56267. if (shadowMap.renderList) {
  56268. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  56269. var mesh = shadowMap.renderList[meshIndex];
  56270. serializationObject.renderList.push(mesh.id);
  56271. }
  56272. }
  56273. return serializationObject;
  56274. };
  56275. /**
  56276. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  56277. */
  56278. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  56279. //casting to point light, as light is missing the position attr and typescript complains.
  56280. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  56281. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  56282. var shadowMap = shadowGenerator.getShadowMap();
  56283. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  56284. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  56285. meshes.forEach(function (mesh) {
  56286. if (!shadowMap) {
  56287. return;
  56288. }
  56289. if (!shadowMap.renderList) {
  56290. shadowMap.renderList = [];
  56291. }
  56292. shadowMap.renderList.push(mesh);
  56293. });
  56294. }
  56295. if (parsedShadowGenerator.usePoissonSampling) {
  56296. shadowGenerator.usePoissonSampling = true;
  56297. }
  56298. else if (parsedShadowGenerator.useExponentialShadowMap) {
  56299. shadowGenerator.useExponentialShadowMap = true;
  56300. }
  56301. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  56302. shadowGenerator.useBlurExponentialShadowMap = true;
  56303. }
  56304. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  56305. shadowGenerator.useCloseExponentialShadowMap = true;
  56306. }
  56307. else if (parsedShadowGenerator.useBlurCloseExponentialShadowMap) {
  56308. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  56309. }
  56310. else if (parsedShadowGenerator.useVarianceShadowMap) {
  56311. shadowGenerator.useExponentialShadowMap = true;
  56312. }
  56313. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  56314. shadowGenerator.useBlurExponentialShadowMap = true;
  56315. }
  56316. if (parsedShadowGenerator.depthScale) {
  56317. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  56318. }
  56319. if (parsedShadowGenerator.blurScale) {
  56320. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  56321. }
  56322. if (parsedShadowGenerator.blurBoxOffset) {
  56323. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  56324. }
  56325. if (parsedShadowGenerator.useKernelBlur) {
  56326. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  56327. }
  56328. if (parsedShadowGenerator.blurKernel) {
  56329. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  56330. }
  56331. if (parsedShadowGenerator.bias !== undefined) {
  56332. shadowGenerator.bias = parsedShadowGenerator.bias;
  56333. }
  56334. if (parsedShadowGenerator.darkness) {
  56335. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  56336. }
  56337. if (parsedShadowGenerator.transparencyShadow) {
  56338. shadowGenerator.setTransparencyShadow(true);
  56339. }
  56340. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  56341. return shadowGenerator;
  56342. };
  56343. ShadowGenerator._FILTER_NONE = 0;
  56344. ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP = 1;
  56345. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  56346. ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  56347. ShadowGenerator._FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  56348. ShadowGenerator._FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  56349. return ShadowGenerator;
  56350. }());
  56351. BABYLON.ShadowGenerator = ShadowGenerator;
  56352. })(BABYLON || (BABYLON = {}));
  56353. //# sourceMappingURL=babylon.shadowGenerator.js.map
  56354. var BABYLON;
  56355. (function (BABYLON) {
  56356. var DefaultLoadingScreen = /** @class */ (function () {
  56357. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  56358. if (_loadingText === void 0) { _loadingText = ""; }
  56359. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  56360. var _this = this;
  56361. this._renderingCanvas = _renderingCanvas;
  56362. this._loadingText = _loadingText;
  56363. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  56364. // Resize
  56365. this._resizeLoadingUI = function () {
  56366. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  56367. var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position;
  56368. if (!_this._loadingDiv) {
  56369. return;
  56370. }
  56371. _this._loadingDiv.style.position = (canvasPositioning === "fixed") ? "fixed" : "absolute";
  56372. _this._loadingDiv.style.left = canvasRect.left + "px";
  56373. _this._loadingDiv.style.top = canvasRect.top + "px";
  56374. _this._loadingDiv.style.width = canvasRect.width + "px";
  56375. _this._loadingDiv.style.height = canvasRect.height + "px";
  56376. };
  56377. }
  56378. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  56379. if (this._loadingDiv) {
  56380. // Do not add a loading screen if there is already one
  56381. return;
  56382. }
  56383. this._loadingDiv = document.createElement("div");
  56384. this._loadingDiv.id = "babylonjsLoadingDiv";
  56385. this._loadingDiv.style.opacity = "0";
  56386. this._loadingDiv.style.transition = "opacity 1.5s ease";
  56387. this._loadingDiv.style.pointerEvents = "none";
  56388. // Loading text
  56389. this._loadingTextDiv = document.createElement("div");
  56390. this._loadingTextDiv.style.position = "absolute";
  56391. this._loadingTextDiv.style.left = "0";
  56392. this._loadingTextDiv.style.top = "50%";
  56393. this._loadingTextDiv.style.marginTop = "80px";
  56394. this._loadingTextDiv.style.width = "100%";
  56395. this._loadingTextDiv.style.height = "20px";
  56396. this._loadingTextDiv.style.fontFamily = "Arial";
  56397. this._loadingTextDiv.style.fontSize = "14px";
  56398. this._loadingTextDiv.style.color = "white";
  56399. this._loadingTextDiv.style.textAlign = "center";
  56400. this._loadingTextDiv.innerHTML = "Loading";
  56401. this._loadingDiv.appendChild(this._loadingTextDiv);
  56402. //set the predefined text
  56403. this._loadingTextDiv.innerHTML = this._loadingText;
  56404. // Generating keyframes
  56405. var style = document.createElement('style');
  56406. style.type = 'text/css';
  56407. 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 }";
  56408. style.innerHTML = keyFrames;
  56409. document.getElementsByTagName('head')[0].appendChild(style);
  56410. // Loading img
  56411. var imgBack = new Image();
  56412. 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";
  56413. imgBack.style.position = "absolute";
  56414. imgBack.style.left = "50%";
  56415. imgBack.style.top = "50%";
  56416. imgBack.style.marginLeft = "-60px";
  56417. imgBack.style.marginTop = "-60px";
  56418. imgBack.style.animation = "spin1 2s infinite ease-in-out";
  56419. imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
  56420. imgBack.style.transformOrigin = "50% 50%";
  56421. imgBack.style.webkitTransformOrigin = "50% 50%";
  56422. this._loadingDiv.appendChild(imgBack);
  56423. this._resizeLoadingUI();
  56424. window.addEventListener("resize", this._resizeLoadingUI);
  56425. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  56426. document.body.appendChild(this._loadingDiv);
  56427. this._loadingDiv.style.opacity = "1";
  56428. };
  56429. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  56430. var _this = this;
  56431. if (!this._loadingDiv) {
  56432. return;
  56433. }
  56434. var onTransitionEnd = function () {
  56435. if (!_this._loadingDiv) {
  56436. return;
  56437. }
  56438. document.body.removeChild(_this._loadingDiv);
  56439. window.removeEventListener("resize", _this._resizeLoadingUI);
  56440. _this._loadingDiv = null;
  56441. };
  56442. this._loadingDiv.style.opacity = "0";
  56443. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  56444. };
  56445. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  56446. set: function (text) {
  56447. this._loadingText = text;
  56448. if (this._loadingTextDiv) {
  56449. this._loadingTextDiv.innerHTML = this._loadingText;
  56450. }
  56451. },
  56452. enumerable: true,
  56453. configurable: true
  56454. });
  56455. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  56456. get: function () {
  56457. return this._loadingDivBackgroundColor;
  56458. },
  56459. set: function (color) {
  56460. this._loadingDivBackgroundColor = color;
  56461. if (!this._loadingDiv) {
  56462. return;
  56463. }
  56464. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  56465. },
  56466. enumerable: true,
  56467. configurable: true
  56468. });
  56469. return DefaultLoadingScreen;
  56470. }());
  56471. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  56472. })(BABYLON || (BABYLON = {}));
  56473. //# sourceMappingURL=babylon.loadingScreen.js.map
  56474. var BABYLON;
  56475. (function (BABYLON) {
  56476. var SceneLoaderProgressEvent = /** @class */ (function () {
  56477. function SceneLoaderProgressEvent(lengthComputable, loaded, total) {
  56478. this.lengthComputable = lengthComputable;
  56479. this.loaded = loaded;
  56480. this.total = total;
  56481. }
  56482. SceneLoaderProgressEvent.FromProgressEvent = function (event) {
  56483. return new SceneLoaderProgressEvent(event.lengthComputable, event.loaded, event.total);
  56484. };
  56485. return SceneLoaderProgressEvent;
  56486. }());
  56487. BABYLON.SceneLoaderProgressEvent = SceneLoaderProgressEvent;
  56488. var SceneLoader = /** @class */ (function () {
  56489. function SceneLoader() {
  56490. }
  56491. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  56492. get: function () {
  56493. return 0;
  56494. },
  56495. enumerable: true,
  56496. configurable: true
  56497. });
  56498. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  56499. get: function () {
  56500. return 1;
  56501. },
  56502. enumerable: true,
  56503. configurable: true
  56504. });
  56505. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  56506. get: function () {
  56507. return 2;
  56508. },
  56509. enumerable: true,
  56510. configurable: true
  56511. });
  56512. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  56513. get: function () {
  56514. return 3;
  56515. },
  56516. enumerable: true,
  56517. configurable: true
  56518. });
  56519. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  56520. get: function () {
  56521. return SceneLoader._ForceFullSceneLoadingForIncremental;
  56522. },
  56523. set: function (value) {
  56524. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  56525. },
  56526. enumerable: true,
  56527. configurable: true
  56528. });
  56529. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  56530. get: function () {
  56531. return SceneLoader._ShowLoadingScreen;
  56532. },
  56533. set: function (value) {
  56534. SceneLoader._ShowLoadingScreen = value;
  56535. },
  56536. enumerable: true,
  56537. configurable: true
  56538. });
  56539. Object.defineProperty(SceneLoader, "loggingLevel", {
  56540. get: function () {
  56541. return SceneLoader._loggingLevel;
  56542. },
  56543. set: function (value) {
  56544. SceneLoader._loggingLevel = value;
  56545. },
  56546. enumerable: true,
  56547. configurable: true
  56548. });
  56549. Object.defineProperty(SceneLoader, "CleanBoneMatrixWeights", {
  56550. get: function () {
  56551. return SceneLoader._CleanBoneMatrixWeights;
  56552. },
  56553. set: function (value) {
  56554. SceneLoader._CleanBoneMatrixWeights = value;
  56555. },
  56556. enumerable: true,
  56557. configurable: true
  56558. });
  56559. SceneLoader._getDefaultPlugin = function () {
  56560. return SceneLoader._registeredPlugins[".babylon"];
  56561. };
  56562. SceneLoader._getPluginForExtension = function (extension) {
  56563. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  56564. if (registeredPlugin) {
  56565. return registeredPlugin;
  56566. }
  56567. BABYLON.Tools.Warn("Unable to find a plugin to load " + extension + " files. Trying to use .babylon default plugin.");
  56568. return SceneLoader._getDefaultPlugin();
  56569. };
  56570. SceneLoader._getPluginForDirectLoad = function (data) {
  56571. for (var extension in SceneLoader._registeredPlugins) {
  56572. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  56573. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  56574. return SceneLoader._registeredPlugins[extension];
  56575. }
  56576. }
  56577. return SceneLoader._getDefaultPlugin();
  56578. };
  56579. SceneLoader._getPluginForFilename = function (sceneFilename) {
  56580. if (sceneFilename.name) {
  56581. sceneFilename = sceneFilename.name;
  56582. }
  56583. var queryStringPosition = sceneFilename.indexOf("?");
  56584. if (queryStringPosition !== -1) {
  56585. sceneFilename = sceneFilename.substring(0, queryStringPosition);
  56586. }
  56587. var dotPosition = sceneFilename.lastIndexOf(".");
  56588. var extension = sceneFilename.substring(dotPosition, sceneFilename.length).toLowerCase();
  56589. return SceneLoader._getPluginForExtension(extension);
  56590. };
  56591. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  56592. SceneLoader._getDirectLoad = function (sceneFilename) {
  56593. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  56594. return sceneFilename.substr(5);
  56595. }
  56596. return null;
  56597. };
  56598. SceneLoader._loadData = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, onDispose, pluginExtension) {
  56599. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  56600. var registeredPlugin = pluginExtension ? SceneLoader._getPluginForExtension(pluginExtension) : (directLoad ? SceneLoader._getPluginForDirectLoad(sceneFilename) : SceneLoader._getPluginForFilename(sceneFilename));
  56601. var plugin;
  56602. if (registeredPlugin.plugin.createPlugin) {
  56603. plugin = registeredPlugin.plugin.createPlugin();
  56604. }
  56605. else {
  56606. plugin = registeredPlugin.plugin;
  56607. }
  56608. var useArrayBuffer = registeredPlugin.isBinary;
  56609. var database;
  56610. SceneLoader.OnPluginActivatedObservable.notifyObservers(plugin);
  56611. var dataCallback = function (data, responseURL) {
  56612. if (scene.isDisposed) {
  56613. onError("Scene has been disposed");
  56614. return;
  56615. }
  56616. scene.database = database;
  56617. onSuccess(plugin, data, responseURL);
  56618. };
  56619. var request = null;
  56620. var pluginDisposed = false;
  56621. var onDisposeObservable = plugin.onDisposeObservable;
  56622. if (onDisposeObservable) {
  56623. onDisposeObservable.add(function () {
  56624. pluginDisposed = true;
  56625. if (request) {
  56626. request.abort();
  56627. request = null;
  56628. }
  56629. onDispose();
  56630. });
  56631. }
  56632. var manifestChecked = function () {
  56633. if (pluginDisposed) {
  56634. return;
  56635. }
  56636. var url = rootUrl + sceneFilename;
  56637. request = BABYLON.Tools.LoadFile(url, dataCallback, onProgress ? function (event) {
  56638. onProgress(SceneLoaderProgressEvent.FromProgressEvent(event));
  56639. } : undefined, database, useArrayBuffer, function (request, exception) {
  56640. onError("Failed to load scene." + (exception ? "" : " " + exception.message), exception);
  56641. });
  56642. };
  56643. if (directLoad) {
  56644. dataCallback(directLoad);
  56645. return plugin;
  56646. }
  56647. if (rootUrl.indexOf("file:") === -1) {
  56648. if (scene.getEngine().enableOfflineSupport) {
  56649. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  56650. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  56651. }
  56652. else {
  56653. manifestChecked();
  56654. }
  56655. }
  56656. else {
  56657. var fileOrString = sceneFilename;
  56658. if (fileOrString.name) {
  56659. request = BABYLON.Tools.ReadFile(fileOrString, dataCallback, onProgress, useArrayBuffer);
  56660. }
  56661. else if (BABYLON.FilesInput.FilesToLoad[sceneFilename]) {
  56662. request = BABYLON.Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[sceneFilename], dataCallback, onProgress, useArrayBuffer);
  56663. }
  56664. else {
  56665. onError("Unable to find file named " + sceneFilename);
  56666. }
  56667. }
  56668. return plugin;
  56669. };
  56670. // Public functions
  56671. SceneLoader.GetPluginForExtension = function (extension) {
  56672. return SceneLoader._getPluginForExtension(extension).plugin;
  56673. };
  56674. SceneLoader.IsPluginForExtensionAvailable = function (extension) {
  56675. return !!SceneLoader._registeredPlugins[extension];
  56676. };
  56677. SceneLoader.RegisterPlugin = function (plugin) {
  56678. if (typeof plugin.extensions === "string") {
  56679. var extension = plugin.extensions;
  56680. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  56681. plugin: plugin,
  56682. isBinary: false
  56683. };
  56684. }
  56685. else {
  56686. var extensions = plugin.extensions;
  56687. Object.keys(extensions).forEach(function (extension) {
  56688. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  56689. plugin: plugin,
  56690. isBinary: extensions[extension].isBinary
  56691. };
  56692. });
  56693. }
  56694. };
  56695. /**
  56696. * Import meshes into a scene
  56697. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  56698. * @param rootUrl a string that defines the root url for scene and resources
  56699. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  56700. * @param scene the instance of BABYLON.Scene to append to
  56701. * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds
  56702. * @param onProgress a callback with a progress event for each file being loaded
  56703. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  56704. */
  56705. SceneLoader.ImportMesh = function (meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  56706. if (onSuccess === void 0) { onSuccess = null; }
  56707. if (onProgress === void 0) { onProgress = null; }
  56708. if (onError === void 0) { onError = null; }
  56709. if (pluginExtension === void 0) { pluginExtension = null; }
  56710. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  56711. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  56712. return null;
  56713. }
  56714. var loadingToken = {};
  56715. scene._addPendingData(loadingToken);
  56716. var disposeHandler = function () {
  56717. scene._removePendingData(loadingToken);
  56718. };
  56719. var errorHandler = function (message, exception) {
  56720. var errorMessage = "Unable to import meshes from " + rootUrl + sceneFilename + ": " + message;
  56721. if (onError) {
  56722. onError(scene, errorMessage, exception);
  56723. }
  56724. else {
  56725. BABYLON.Tools.Error(errorMessage);
  56726. // should the exception be thrown?
  56727. }
  56728. disposeHandler();
  56729. };
  56730. var progressHandler = onProgress ? function (event) {
  56731. try {
  56732. onProgress(event);
  56733. }
  56734. catch (e) {
  56735. errorHandler("Error in onProgress callback", e);
  56736. }
  56737. } : undefined;
  56738. var successHandler = function (meshes, particleSystems, skeletons) {
  56739. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  56740. if (onSuccess) {
  56741. try {
  56742. onSuccess(meshes, particleSystems, skeletons);
  56743. }
  56744. catch (e) {
  56745. errorHandler("Error in onSuccess callback", e);
  56746. }
  56747. }
  56748. scene._removePendingData(loadingToken);
  56749. };
  56750. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  56751. if (plugin.rewriteRootURL) {
  56752. rootUrl = plugin.rewriteRootURL(rootUrl, responseURL);
  56753. }
  56754. if (plugin.importMesh) {
  56755. var syncedPlugin = plugin;
  56756. var meshes = new Array();
  56757. var particleSystems = new Array();
  56758. var skeletons = new Array();
  56759. if (!syncedPlugin.importMesh(meshNames, scene, data, rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
  56760. return;
  56761. }
  56762. scene.loadingPluginName = plugin.name;
  56763. successHandler(meshes, particleSystems, skeletons);
  56764. }
  56765. else {
  56766. var asyncedPlugin = plugin;
  56767. asyncedPlugin.importMeshAsync(meshNames, scene, data, rootUrl, function (meshes, particleSystems, skeletons) {
  56768. scene.loadingPluginName = plugin.name;
  56769. successHandler(meshes, particleSystems, skeletons);
  56770. }, progressHandler, errorHandler);
  56771. }
  56772. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  56773. };
  56774. /**
  56775. * Load a scene
  56776. * @param rootUrl a string that defines the root url for scene and resources
  56777. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  56778. * @param engine is the instance of BABYLON.Engine to use to create the scene
  56779. * @param onSuccess a callback with the scene when import succeeds
  56780. * @param onProgress a callback with a progress event for each file being loaded
  56781. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  56782. */
  56783. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onSuccess, onProgress, onError, pluginExtension) {
  56784. if (onSuccess === void 0) { onSuccess = null; }
  56785. if (onProgress === void 0) { onProgress = null; }
  56786. if (onError === void 0) { onError = null; }
  56787. if (pluginExtension === void 0) { pluginExtension = null; }
  56788. return SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onSuccess, onProgress, onError, pluginExtension);
  56789. };
  56790. /**
  56791. * Append a scene
  56792. * @param rootUrl a string that defines the root url for scene and resources
  56793. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  56794. * @param scene is the instance of BABYLON.Scene to append to
  56795. * @param onSuccess a callback with the scene when import succeeds
  56796. * @param onProgress a callback with a progress event for each file being loaded
  56797. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  56798. */
  56799. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  56800. if (onSuccess === void 0) { onSuccess = null; }
  56801. if (onProgress === void 0) { onProgress = null; }
  56802. if (onError === void 0) { onError = null; }
  56803. if (pluginExtension === void 0) { pluginExtension = null; }
  56804. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  56805. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  56806. return null;
  56807. }
  56808. if (SceneLoader.ShowLoadingScreen) {
  56809. scene.getEngine().displayLoadingUI();
  56810. }
  56811. var loadingToken = {};
  56812. scene._addPendingData(loadingToken);
  56813. var disposeHandler = function () {
  56814. scene._removePendingData(loadingToken);
  56815. scene.getEngine().hideLoadingUI();
  56816. };
  56817. var errorHandler = function (message, exception) {
  56818. var errorMessage = "Unable to load from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  56819. if (onError) {
  56820. onError(scene, errorMessage, exception);
  56821. }
  56822. else {
  56823. BABYLON.Tools.Error(errorMessage);
  56824. // should the exception be thrown?
  56825. }
  56826. disposeHandler();
  56827. };
  56828. var progressHandler = onProgress ? function (event) {
  56829. try {
  56830. onProgress(event);
  56831. }
  56832. catch (e) {
  56833. errorHandler("Error in onProgress callback", e);
  56834. }
  56835. } : undefined;
  56836. var successHandler = function () {
  56837. if (onSuccess) {
  56838. try {
  56839. onSuccess(scene);
  56840. }
  56841. catch (e) {
  56842. errorHandler("Error in onSuccess callback", e);
  56843. }
  56844. }
  56845. scene._removePendingData(loadingToken);
  56846. };
  56847. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  56848. if (plugin.load) {
  56849. var syncedPlugin = plugin;
  56850. if (!syncedPlugin.load(scene, data, rootUrl, errorHandler)) {
  56851. return;
  56852. }
  56853. scene.loadingPluginName = plugin.name;
  56854. successHandler();
  56855. }
  56856. else {
  56857. var asyncedPlugin = plugin;
  56858. asyncedPlugin.loadAsync(scene, data, rootUrl, function () {
  56859. scene.loadingPluginName = plugin.name;
  56860. successHandler();
  56861. }, progressHandler, errorHandler);
  56862. }
  56863. if (SceneLoader.ShowLoadingScreen) {
  56864. scene.executeWhenReady(function () {
  56865. scene.getEngine().hideLoadingUI();
  56866. });
  56867. }
  56868. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  56869. };
  56870. SceneLoader.LoadAssetContainer = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  56871. if (onSuccess === void 0) { onSuccess = null; }
  56872. if (onProgress === void 0) { onProgress = null; }
  56873. if (onError === void 0) { onError = null; }
  56874. if (pluginExtension === void 0) { pluginExtension = null; }
  56875. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  56876. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  56877. return null;
  56878. }
  56879. var loadingToken = {};
  56880. scene._addPendingData(loadingToken);
  56881. var disposeHandler = function () {
  56882. scene._removePendingData(loadingToken);
  56883. };
  56884. var errorHandler = function (message, exception) {
  56885. var errorMessage = "Unable to load assets from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  56886. if (onError) {
  56887. onError(scene, errorMessage, exception);
  56888. }
  56889. else {
  56890. BABYLON.Tools.Error(errorMessage);
  56891. // should the exception be thrown?
  56892. }
  56893. disposeHandler();
  56894. };
  56895. var progressHandler = onProgress ? function (event) {
  56896. try {
  56897. onProgress(event);
  56898. }
  56899. catch (e) {
  56900. errorHandler("Error in onProgress callback", e);
  56901. }
  56902. } : undefined;
  56903. var successHandler = function (assets) {
  56904. if (onSuccess) {
  56905. try {
  56906. onSuccess(assets);
  56907. }
  56908. catch (e) {
  56909. errorHandler("Error in onSuccess callback", e);
  56910. }
  56911. }
  56912. scene._removePendingData(loadingToken);
  56913. };
  56914. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  56915. if (plugin.loadAssets) {
  56916. var syncedPlugin = plugin;
  56917. var assetContainer = syncedPlugin.loadAssets(scene, data, rootUrl, errorHandler);
  56918. if (!assetContainer) {
  56919. return;
  56920. }
  56921. scene.loadingPluginName = plugin.name;
  56922. successHandler(assetContainer);
  56923. }
  56924. else if (plugin.loadAssetsAsync) {
  56925. var asyncedPlugin = plugin;
  56926. asyncedPlugin.loadAssetsAsync(scene, data, rootUrl, function (assetContainer) {
  56927. if (assetContainer) {
  56928. scene.loadingPluginName = plugin.name;
  56929. successHandler(assetContainer);
  56930. }
  56931. }, progressHandler, errorHandler);
  56932. }
  56933. else {
  56934. errorHandler("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssets or loadAssetsAsync method.");
  56935. }
  56936. if (SceneLoader.ShowLoadingScreen) {
  56937. scene.executeWhenReady(function () {
  56938. scene.getEngine().hideLoadingUI();
  56939. });
  56940. }
  56941. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  56942. };
  56943. // Flags
  56944. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  56945. SceneLoader._ShowLoadingScreen = true;
  56946. SceneLoader._CleanBoneMatrixWeights = false;
  56947. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  56948. // Members
  56949. SceneLoader.OnPluginActivatedObservable = new BABYLON.Observable();
  56950. SceneLoader._registeredPlugins = {};
  56951. return SceneLoader;
  56952. }());
  56953. BABYLON.SceneLoader = SceneLoader;
  56954. ;
  56955. })(BABYLON || (BABYLON = {}));
  56956. //# sourceMappingURL=babylon.sceneLoader.js.map
  56957. var BABYLON;
  56958. (function (BABYLON) {
  56959. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  56960. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  56961. var parsedMaterial = parsedData.materials[index];
  56962. if (parsedMaterial.id === id) {
  56963. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  56964. }
  56965. }
  56966. return null;
  56967. };
  56968. var isDescendantOf = function (mesh, names, hierarchyIds) {
  56969. for (var i in names) {
  56970. if (mesh.name === names[i]) {
  56971. hierarchyIds.push(mesh.id);
  56972. return true;
  56973. }
  56974. }
  56975. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  56976. hierarchyIds.push(mesh.id);
  56977. return true;
  56978. }
  56979. return false;
  56980. };
  56981. var logOperation = function (operation, producer) {
  56982. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  56983. };
  56984. var loadAssets = function (scene, data, rootUrl, onError, addToScene) {
  56985. if (addToScene === void 0) { addToScene = false; }
  56986. var container = new BABYLON.AssetContainer(scene);
  56987. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  56988. // when SceneLoader.debugLogging = true (default), or exception encountered.
  56989. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  56990. // and avoid problems with multiple concurrent .babylon loads.
  56991. var log = "importScene has failed JSON parse";
  56992. try {
  56993. var parsedData = JSON.parse(data);
  56994. log = "";
  56995. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  56996. var index;
  56997. var cache;
  56998. // Lights
  56999. if (parsedData.lights !== undefined && parsedData.lights !== null) {
  57000. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  57001. var parsedLight = parsedData.lights[index];
  57002. var light = BABYLON.Light.Parse(parsedLight, scene);
  57003. if (light) {
  57004. container.lights.push(light);
  57005. log += (index === 0 ? "\n\tLights:" : "");
  57006. log += "\n\t\t" + light.toString(fullDetails);
  57007. }
  57008. }
  57009. }
  57010. // Animations
  57011. if (parsedData.animations !== undefined && parsedData.animations !== null) {
  57012. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  57013. var parsedAnimation = parsedData.animations[index];
  57014. var animation = BABYLON.Animation.Parse(parsedAnimation);
  57015. scene.animations.push(animation);
  57016. container.animations.push(animation);
  57017. log += (index === 0 ? "\n\tAnimations:" : "");
  57018. log += "\n\t\t" + animation.toString(fullDetails);
  57019. }
  57020. }
  57021. // Materials
  57022. if (parsedData.materials !== undefined && parsedData.materials !== null) {
  57023. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  57024. var parsedMaterial = parsedData.materials[index];
  57025. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  57026. container.materials.push(mat);
  57027. log += (index === 0 ? "\n\tMaterials:" : "");
  57028. log += "\n\t\t" + mat.toString(fullDetails);
  57029. }
  57030. }
  57031. if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  57032. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  57033. var parsedMultiMaterial = parsedData.multiMaterials[index];
  57034. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  57035. container.multiMaterials.push(mmat);
  57036. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  57037. log += "\n\t\t" + mmat.toString(fullDetails);
  57038. }
  57039. }
  57040. // Morph targets
  57041. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  57042. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  57043. var managerData = _a[_i];
  57044. container.morphTargetManagers.push(BABYLON.MorphTargetManager.Parse(managerData, scene));
  57045. }
  57046. }
  57047. // Skeletons
  57048. if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  57049. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  57050. var parsedSkeleton = parsedData.skeletons[index];
  57051. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  57052. container.skeletons.push(skeleton);
  57053. log += (index === 0 ? "\n\tSkeletons:" : "");
  57054. log += "\n\t\t" + skeleton.toString(fullDetails);
  57055. }
  57056. }
  57057. // Geometries
  57058. var geometries = parsedData.geometries;
  57059. if (geometries !== undefined && geometries !== null) {
  57060. var addedGeometry = new Array();
  57061. // Boxes
  57062. var boxes = geometries.boxes;
  57063. if (boxes !== undefined && boxes !== null) {
  57064. for (index = 0, cache = boxes.length; index < cache; index++) {
  57065. var parsedBox = boxes[index];
  57066. addedGeometry.push(BABYLON.BoxGeometry.Parse(parsedBox, scene));
  57067. }
  57068. }
  57069. // Spheres
  57070. var spheres = geometries.spheres;
  57071. if (spheres !== undefined && spheres !== null) {
  57072. for (index = 0, cache = spheres.length; index < cache; index++) {
  57073. var parsedSphere = spheres[index];
  57074. addedGeometry.push(BABYLON.SphereGeometry.Parse(parsedSphere, scene));
  57075. }
  57076. }
  57077. // Cylinders
  57078. var cylinders = geometries.cylinders;
  57079. if (cylinders !== undefined && cylinders !== null) {
  57080. for (index = 0, cache = cylinders.length; index < cache; index++) {
  57081. var parsedCylinder = cylinders[index];
  57082. addedGeometry.push(BABYLON.CylinderGeometry.Parse(parsedCylinder, scene));
  57083. }
  57084. }
  57085. // Toruses
  57086. var toruses = geometries.toruses;
  57087. if (toruses !== undefined && toruses !== null) {
  57088. for (index = 0, cache = toruses.length; index < cache; index++) {
  57089. var parsedTorus = toruses[index];
  57090. addedGeometry.push(BABYLON.TorusGeometry.Parse(parsedTorus, scene));
  57091. }
  57092. }
  57093. // Grounds
  57094. var grounds = geometries.grounds;
  57095. if (grounds !== undefined && grounds !== null) {
  57096. for (index = 0, cache = grounds.length; index < cache; index++) {
  57097. var parsedGround = grounds[index];
  57098. addedGeometry.push(BABYLON.GroundGeometry.Parse(parsedGround, scene));
  57099. }
  57100. }
  57101. // Planes
  57102. var planes = geometries.planes;
  57103. if (planes !== undefined && planes !== null) {
  57104. for (index = 0, cache = planes.length; index < cache; index++) {
  57105. var parsedPlane = planes[index];
  57106. addedGeometry.push(BABYLON.PlaneGeometry.Parse(parsedPlane, scene));
  57107. }
  57108. }
  57109. // TorusKnots
  57110. var torusKnots = geometries.torusKnots;
  57111. if (torusKnots !== undefined && torusKnots !== null) {
  57112. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  57113. var parsedTorusKnot = torusKnots[index];
  57114. addedGeometry.push(BABYLON.TorusKnotGeometry.Parse(parsedTorusKnot, scene));
  57115. }
  57116. }
  57117. // VertexData
  57118. var vertexData = geometries.vertexData;
  57119. if (vertexData !== undefined && vertexData !== null) {
  57120. for (index = 0, cache = vertexData.length; index < cache; index++) {
  57121. var parsedVertexData = vertexData[index];
  57122. addedGeometry.push(BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl));
  57123. }
  57124. }
  57125. addedGeometry.forEach(function (g) {
  57126. if (g) {
  57127. container.geometries.push(g);
  57128. }
  57129. });
  57130. }
  57131. // Transform nodes
  57132. if (parsedData.transformNodes !== undefined && parsedData.transformNodes !== null) {
  57133. for (index = 0, cache = parsedData.transformNodes.length; index < cache; index++) {
  57134. var parsedTransformNode = parsedData.transformNodes[index];
  57135. var node = BABYLON.TransformNode.Parse(parsedTransformNode, scene, rootUrl);
  57136. container.transformNodes.push(node);
  57137. }
  57138. }
  57139. // Meshes
  57140. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  57141. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  57142. var parsedMesh = parsedData.meshes[index];
  57143. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  57144. container.meshes.push(mesh);
  57145. log += (index === 0 ? "\n\tMeshes:" : "");
  57146. log += "\n\t\t" + mesh.toString(fullDetails);
  57147. }
  57148. }
  57149. // Cameras
  57150. if (parsedData.cameras !== undefined && parsedData.cameras !== null) {
  57151. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  57152. var parsedCamera = parsedData.cameras[index];
  57153. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  57154. container.cameras.push(camera);
  57155. log += (index === 0 ? "\n\tCameras:" : "");
  57156. log += "\n\t\t" + camera.toString(fullDetails);
  57157. }
  57158. }
  57159. // Browsing all the graph to connect the dots
  57160. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  57161. var camera = scene.cameras[index];
  57162. if (camera._waitingParentId) {
  57163. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  57164. camera._waitingParentId = null;
  57165. }
  57166. }
  57167. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  57168. var light_1 = scene.lights[index];
  57169. if (light_1 && light_1._waitingParentId) {
  57170. light_1.parent = scene.getLastEntryByID(light_1._waitingParentId);
  57171. light_1._waitingParentId = null;
  57172. }
  57173. }
  57174. // Sounds
  57175. // TODO: add sound
  57176. var loadedSounds = [];
  57177. var loadedSound;
  57178. if (BABYLON.AudioEngine && parsedData.sounds !== undefined && parsedData.sounds !== null) {
  57179. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  57180. var parsedSound = parsedData.sounds[index];
  57181. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  57182. if (!parsedSound.url)
  57183. parsedSound.url = parsedSound.name;
  57184. if (!loadedSounds[parsedSound.url]) {
  57185. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  57186. loadedSounds[parsedSound.url] = loadedSound;
  57187. container.sounds.push(loadedSound);
  57188. }
  57189. else {
  57190. container.sounds.push(BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]));
  57191. }
  57192. }
  57193. else {
  57194. container.sounds.push(new BABYLON.Sound(parsedSound.name, null, scene));
  57195. }
  57196. }
  57197. }
  57198. loadedSounds = [];
  57199. // Connect parents & children and parse actions
  57200. for (index = 0, cache = scene.transformNodes.length; index < cache; index++) {
  57201. var transformNode = scene.transformNodes[index];
  57202. if (transformNode._waitingParentId) {
  57203. transformNode.parent = scene.getLastEntryByID(transformNode._waitingParentId);
  57204. transformNode._waitingParentId = null;
  57205. }
  57206. }
  57207. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  57208. var mesh = scene.meshes[index];
  57209. if (mesh._waitingParentId) {
  57210. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  57211. mesh._waitingParentId = null;
  57212. }
  57213. if (mesh._waitingActions) {
  57214. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  57215. mesh._waitingActions = null;
  57216. }
  57217. }
  57218. // freeze world matrix application
  57219. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  57220. var currentMesh = scene.meshes[index];
  57221. if (currentMesh._waitingFreezeWorldMatrix) {
  57222. currentMesh.freezeWorldMatrix();
  57223. currentMesh._waitingFreezeWorldMatrix = null;
  57224. }
  57225. else {
  57226. currentMesh.computeWorldMatrix(true);
  57227. }
  57228. }
  57229. // Particles Systems
  57230. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  57231. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  57232. var parsedParticleSystem = parsedData.particleSystems[index];
  57233. var ps = BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  57234. container.particleSystems.push(ps);
  57235. }
  57236. }
  57237. // Lens flares
  57238. if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {
  57239. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  57240. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  57241. var lf = BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  57242. container.lensFlareSystems.push(lf);
  57243. }
  57244. }
  57245. // Shadows
  57246. if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {
  57247. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  57248. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  57249. var sg = BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  57250. container.shadowGenerators.push(sg);
  57251. }
  57252. }
  57253. // Lights exclusions / inclusions
  57254. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  57255. var light_2 = scene.lights[index];
  57256. // Excluded check
  57257. if (light_2._excludedMeshesIds.length > 0) {
  57258. for (var excludedIndex = 0; excludedIndex < light_2._excludedMeshesIds.length; excludedIndex++) {
  57259. var excludedMesh = scene.getMeshByID(light_2._excludedMeshesIds[excludedIndex]);
  57260. if (excludedMesh) {
  57261. light_2.excludedMeshes.push(excludedMesh);
  57262. }
  57263. }
  57264. light_2._excludedMeshesIds = [];
  57265. }
  57266. // Included check
  57267. if (light_2._includedOnlyMeshesIds.length > 0) {
  57268. for (var includedOnlyIndex = 0; includedOnlyIndex < light_2._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  57269. var includedOnlyMesh = scene.getMeshByID(light_2._includedOnlyMeshesIds[includedOnlyIndex]);
  57270. if (includedOnlyMesh) {
  57271. light_2.includedOnlyMeshes.push(includedOnlyMesh);
  57272. }
  57273. }
  57274. light_2._includedOnlyMeshesIds = [];
  57275. }
  57276. }
  57277. // Actions (scene)
  57278. if (parsedData.actions !== undefined && parsedData.actions !== null) {
  57279. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  57280. }
  57281. if (!addToScene) {
  57282. container.removeAllFromScene();
  57283. }
  57284. return container;
  57285. }
  57286. catch (err) {
  57287. var msg = logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + log;
  57288. if (onError) {
  57289. onError(msg, err);
  57290. }
  57291. else {
  57292. BABYLON.Tools.Log(msg);
  57293. throw err;
  57294. }
  57295. }
  57296. finally {
  57297. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  57298. BABYLON.Tools.Log(logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  57299. }
  57300. }
  57301. return null;
  57302. };
  57303. BABYLON.SceneLoader.RegisterPlugin({
  57304. name: "babylon.js",
  57305. extensions: ".babylon",
  57306. canDirectLoad: function (data) {
  57307. if (data.indexOf("babylon") !== -1) {
  57308. return true;
  57309. }
  57310. return false;
  57311. },
  57312. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons, onError) {
  57313. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  57314. // when SceneLoader.debugLogging = true (default), or exception encountered.
  57315. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  57316. // and avoid problems with multiple concurrent .babylon loads.
  57317. var log = "importMesh has failed JSON parse";
  57318. try {
  57319. var parsedData = JSON.parse(data);
  57320. log = "";
  57321. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  57322. if (!meshesNames) {
  57323. meshesNames = null;
  57324. }
  57325. else if (!Array.isArray(meshesNames)) {
  57326. meshesNames = [meshesNames];
  57327. }
  57328. var hierarchyIds = new Array();
  57329. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  57330. var loadedSkeletonsIds = [];
  57331. var loadedMaterialsIds = [];
  57332. var index;
  57333. var cache;
  57334. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  57335. var parsedMesh = parsedData.meshes[index];
  57336. if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  57337. if (meshesNames !== null) {
  57338. // Remove found mesh name from list.
  57339. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  57340. }
  57341. //Geometry?
  57342. if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) {
  57343. //does the file contain geometries?
  57344. if (parsedData.geometries !== undefined && parsedData.geometries !== null) {
  57345. //find the correct geometry and add it to the scene
  57346. var found = false;
  57347. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  57348. if (found === true || !parsedData.geometries[geometryType] || !(Array.isArray(parsedData.geometries[geometryType]))) {
  57349. return;
  57350. }
  57351. else {
  57352. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  57353. if (parsedGeometryData.id === parsedMesh.geometryId) {
  57354. switch (geometryType) {
  57355. case "boxes":
  57356. BABYLON.BoxGeometry.Parse(parsedGeometryData, scene);
  57357. break;
  57358. case "spheres":
  57359. BABYLON.SphereGeometry.Parse(parsedGeometryData, scene);
  57360. break;
  57361. case "cylinders":
  57362. BABYLON.CylinderGeometry.Parse(parsedGeometryData, scene);
  57363. break;
  57364. case "toruses":
  57365. BABYLON.TorusGeometry.Parse(parsedGeometryData, scene);
  57366. break;
  57367. case "grounds":
  57368. BABYLON.GroundGeometry.Parse(parsedGeometryData, scene);
  57369. break;
  57370. case "planes":
  57371. BABYLON.PlaneGeometry.Parse(parsedGeometryData, scene);
  57372. break;
  57373. case "torusKnots":
  57374. BABYLON.TorusKnotGeometry.Parse(parsedGeometryData, scene);
  57375. break;
  57376. case "vertexData":
  57377. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  57378. break;
  57379. }
  57380. found = true;
  57381. }
  57382. });
  57383. }
  57384. });
  57385. if (found === false) {
  57386. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  57387. }
  57388. }
  57389. }
  57390. // Material ?
  57391. if (parsedMesh.materialId) {
  57392. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  57393. if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  57394. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  57395. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  57396. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  57397. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  57398. var subMatId = parsedMultiMaterial.materials[matIndex];
  57399. loadedMaterialsIds.push(subMatId);
  57400. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  57401. log += "\n\tMaterial " + mat.toString(fullDetails);
  57402. }
  57403. loadedMaterialsIds.push(parsedMultiMaterial.id);
  57404. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  57405. materialFound = true;
  57406. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  57407. break;
  57408. }
  57409. }
  57410. }
  57411. if (materialFound === false) {
  57412. loadedMaterialsIds.push(parsedMesh.materialId);
  57413. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  57414. if (!mat) {
  57415. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  57416. }
  57417. else {
  57418. log += "\n\tMaterial " + mat.toString(fullDetails);
  57419. }
  57420. }
  57421. }
  57422. // Skeleton ?
  57423. if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  57424. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  57425. if (skeletonAlreadyLoaded === false) {
  57426. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  57427. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  57428. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  57429. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  57430. skeletons.push(skeleton);
  57431. loadedSkeletonsIds.push(parsedSkeleton.id);
  57432. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  57433. }
  57434. }
  57435. }
  57436. }
  57437. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  57438. meshes.push(mesh);
  57439. log += "\n\tMesh " + mesh.toString(fullDetails);
  57440. }
  57441. }
  57442. // Connecting parents
  57443. var currentMesh;
  57444. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  57445. currentMesh = scene.meshes[index];
  57446. if (currentMesh._waitingParentId) {
  57447. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  57448. currentMesh._waitingParentId = null;
  57449. }
  57450. }
  57451. // freeze and compute world matrix application
  57452. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  57453. currentMesh = scene.meshes[index];
  57454. if (currentMesh._waitingFreezeWorldMatrix) {
  57455. currentMesh.freezeWorldMatrix();
  57456. currentMesh._waitingFreezeWorldMatrix = null;
  57457. }
  57458. else {
  57459. currentMesh.computeWorldMatrix(true);
  57460. }
  57461. }
  57462. }
  57463. // Particles
  57464. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  57465. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  57466. var parsedParticleSystem = parsedData.particleSystems[index];
  57467. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  57468. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  57469. }
  57470. }
  57471. }
  57472. return true;
  57473. }
  57474. catch (err) {
  57475. var msg = logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log;
  57476. if (onError) {
  57477. onError(msg, err);
  57478. }
  57479. else {
  57480. BABYLON.Tools.Log(msg);
  57481. throw err;
  57482. }
  57483. }
  57484. finally {
  57485. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  57486. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  57487. }
  57488. }
  57489. return false;
  57490. },
  57491. load: function (scene, data, rootUrl, onError) {
  57492. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  57493. // when SceneLoader.debugLogging = true (default), or exception encountered.
  57494. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  57495. // and avoid problems with multiple concurrent .babylon loads.
  57496. var log = "importScene has failed JSON parse";
  57497. try {
  57498. var parsedData = JSON.parse(data);
  57499. log = "";
  57500. // Scene
  57501. if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {
  57502. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  57503. }
  57504. if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {
  57505. scene.autoClear = parsedData.autoClear;
  57506. }
  57507. if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {
  57508. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  57509. }
  57510. if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {
  57511. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  57512. }
  57513. if (parsedData.gravity !== undefined && parsedData.gravity !== null) {
  57514. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  57515. }
  57516. // Fog
  57517. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  57518. scene.fogMode = parsedData.fogMode;
  57519. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  57520. scene.fogStart = parsedData.fogStart;
  57521. scene.fogEnd = parsedData.fogEnd;
  57522. scene.fogDensity = parsedData.fogDensity;
  57523. log += "\tFog mode for scene: ";
  57524. switch (scene.fogMode) {
  57525. // getters not compiling, so using hardcoded
  57526. case 1:
  57527. log += "exp\n";
  57528. break;
  57529. case 2:
  57530. log += "exp2\n";
  57531. break;
  57532. case 3:
  57533. log += "linear\n";
  57534. break;
  57535. }
  57536. }
  57537. //Physics
  57538. if (parsedData.physicsEnabled) {
  57539. var physicsPlugin;
  57540. if (parsedData.physicsEngine === "cannon") {
  57541. physicsPlugin = new BABYLON.CannonJSPlugin();
  57542. }
  57543. else if (parsedData.physicsEngine === "oimo") {
  57544. physicsPlugin = new BABYLON.OimoJSPlugin();
  57545. }
  57546. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  57547. //else - default engine, which is currently oimo
  57548. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  57549. scene.enablePhysics(physicsGravity, physicsPlugin);
  57550. }
  57551. // Metadata
  57552. if (parsedData.metadata !== undefined && parsedData.metadata !== null) {
  57553. scene.metadata = parsedData.metadata;
  57554. }
  57555. //collisions, if defined. otherwise, default is true
  57556. if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {
  57557. scene.collisionsEnabled = parsedData.collisionsEnabled;
  57558. }
  57559. scene.workerCollisions = !!parsedData.workerCollisions;
  57560. var container = loadAssets(scene, data, rootUrl, onerror, true);
  57561. if (!container) {
  57562. return false;
  57563. }
  57564. if (parsedData.autoAnimate) {
  57565. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  57566. }
  57567. if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {
  57568. scene.setActiveCameraByID(parsedData.activeCameraID);
  57569. }
  57570. // Environment texture
  57571. if (parsedData.environmentTexture !== undefined && parsedData.environmentTexture !== null) {
  57572. scene.environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(rootUrl + parsedData.environmentTexture, scene);
  57573. if (parsedData.createDefaultSkybox === true) {
  57574. var skyboxScale = (scene.activeCamera !== undefined && scene.activeCamera !== null) ? (scene.activeCamera.maxZ - scene.activeCamera.minZ) / 2 : 1000;
  57575. var skyboxBlurLevel = parsedData.skyboxBlurLevel || 0;
  57576. scene.createDefaultSkybox(undefined, true, skyboxScale, skyboxBlurLevel);
  57577. }
  57578. }
  57579. // Finish
  57580. return true;
  57581. }
  57582. catch (err) {
  57583. var msg = logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log;
  57584. if (onError) {
  57585. onError(msg, err);
  57586. }
  57587. else {
  57588. BABYLON.Tools.Log(msg);
  57589. throw err;
  57590. }
  57591. }
  57592. finally {
  57593. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  57594. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  57595. }
  57596. }
  57597. return false;
  57598. },
  57599. loadAssets: function (scene, data, rootUrl, onError) {
  57600. var container = loadAssets(scene, data, rootUrl, onerror);
  57601. return container;
  57602. }
  57603. });
  57604. })(BABYLON || (BABYLON = {}));
  57605. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  57606. var BABYLON;
  57607. (function (BABYLON) {
  57608. var FilesInput = /** @class */ (function () {
  57609. function FilesInput(engine, scene, sceneLoadedCallback, progressCallback, additionalRenderLoopLogicCallback, textureLoadingCallback, startingProcessingFilesCallback, onReloadCallback, errorCallback) {
  57610. this.onProcessFileCallback = function () { return true; };
  57611. this._engine = engine;
  57612. this._currentScene = scene;
  57613. this._sceneLoadedCallback = sceneLoadedCallback;
  57614. this._progressCallback = progressCallback;
  57615. this._additionalRenderLoopLogicCallback = additionalRenderLoopLogicCallback;
  57616. this._textureLoadingCallback = textureLoadingCallback;
  57617. this._startingProcessingFilesCallback = startingProcessingFilesCallback;
  57618. this._onReloadCallback = onReloadCallback;
  57619. this._errorCallback = errorCallback;
  57620. }
  57621. FilesInput.prototype.monitorElementForDragNDrop = function (elementToMonitor) {
  57622. var _this = this;
  57623. if (elementToMonitor) {
  57624. this._elementToMonitor = elementToMonitor;
  57625. this._dragEnterHandler = function (e) { _this.drag(e); };
  57626. this._dragOverHandler = function (e) { _this.drag(e); };
  57627. this._dropHandler = function (e) { _this.drop(e); };
  57628. this._elementToMonitor.addEventListener("dragenter", this._dragEnterHandler, false);
  57629. this._elementToMonitor.addEventListener("dragover", this._dragOverHandler, false);
  57630. this._elementToMonitor.addEventListener("drop", this._dropHandler, false);
  57631. }
  57632. };
  57633. FilesInput.prototype.dispose = function () {
  57634. if (!this._elementToMonitor) {
  57635. return;
  57636. }
  57637. this._elementToMonitor.removeEventListener("dragenter", this._dragEnterHandler);
  57638. this._elementToMonitor.removeEventListener("dragover", this._dragOverHandler);
  57639. this._elementToMonitor.removeEventListener("drop", this._dropHandler);
  57640. };
  57641. FilesInput.prototype.renderFunction = function () {
  57642. if (this._additionalRenderLoopLogicCallback) {
  57643. this._additionalRenderLoopLogicCallback();
  57644. }
  57645. if (this._currentScene) {
  57646. if (this._textureLoadingCallback) {
  57647. var remaining = this._currentScene.getWaitingItemsCount();
  57648. if (remaining > 0) {
  57649. this._textureLoadingCallback(remaining);
  57650. }
  57651. }
  57652. this._currentScene.render();
  57653. }
  57654. };
  57655. FilesInput.prototype.drag = function (e) {
  57656. e.stopPropagation();
  57657. e.preventDefault();
  57658. };
  57659. FilesInput.prototype.drop = function (eventDrop) {
  57660. eventDrop.stopPropagation();
  57661. eventDrop.preventDefault();
  57662. this.loadFiles(eventDrop);
  57663. };
  57664. FilesInput.prototype._traverseFolder = function (folder, files, remaining, callback) {
  57665. var _this = this;
  57666. var reader = folder.createReader();
  57667. var relativePath = folder.fullPath.replace(/^\//, "").replace(/(.+?)\/?$/, "$1/");
  57668. reader.readEntries(function (entries) {
  57669. remaining.count += entries.length;
  57670. for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {
  57671. var entry = entries_1[_i];
  57672. if (entry.isFile) {
  57673. entry.file(function (file) {
  57674. file.correctName = relativePath + file.name;
  57675. files.push(file);
  57676. if (--remaining.count === 0) {
  57677. callback();
  57678. }
  57679. });
  57680. }
  57681. else if (entry.isDirectory) {
  57682. _this._traverseFolder(entry, files, remaining, callback);
  57683. }
  57684. }
  57685. if (--remaining.count) {
  57686. callback();
  57687. }
  57688. });
  57689. };
  57690. FilesInput.prototype._processFiles = function (files) {
  57691. for (var i = 0; i < files.length; i++) {
  57692. var name = files[i].correctName.toLowerCase();
  57693. var extension = name.split('.').pop();
  57694. if (!this.onProcessFileCallback(files[i], name, extension)) {
  57695. continue;
  57696. }
  57697. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  57698. && name.indexOf(".binary.babylon") === -1 && name.indexOf(".incremental.babylon") === -1) {
  57699. this._sceneFileToLoad = files[i];
  57700. }
  57701. else {
  57702. FilesInput.FilesToLoad[name] = files[i];
  57703. }
  57704. }
  57705. };
  57706. FilesInput.prototype.loadFiles = function (event) {
  57707. var _this = this;
  57708. if (this._startingProcessingFilesCallback)
  57709. this._startingProcessingFilesCallback();
  57710. // Handling data transfer via drag'n'drop
  57711. if (event && event.dataTransfer && event.dataTransfer.files) {
  57712. this._filesToLoad = event.dataTransfer.files;
  57713. }
  57714. // Handling files from input files
  57715. if (event && event.target && event.target.files) {
  57716. this._filesToLoad = event.target.files;
  57717. }
  57718. if (this._filesToLoad && this._filesToLoad.length > 0) {
  57719. var files_1 = new Array();
  57720. var folders = [];
  57721. var items = event.dataTransfer ? event.dataTransfer.items : null;
  57722. for (var i = 0; i < this._filesToLoad.length; i++) {
  57723. var fileToLoad = this._filesToLoad[i];
  57724. var name_1 = fileToLoad.name.toLowerCase();
  57725. var entry = void 0;
  57726. fileToLoad.correctName = name_1;
  57727. if (items) {
  57728. var item = items[i];
  57729. if (item.getAsEntry) {
  57730. entry = item.getAsEntry();
  57731. }
  57732. else if (item.webkitGetAsEntry) {
  57733. entry = item.webkitGetAsEntry();
  57734. }
  57735. }
  57736. if (!entry) {
  57737. files_1.push(fileToLoad);
  57738. }
  57739. else {
  57740. if (entry.isDirectory) {
  57741. folders.push(entry);
  57742. }
  57743. else {
  57744. files_1.push(fileToLoad);
  57745. }
  57746. }
  57747. }
  57748. if (folders.length === 0) {
  57749. this._processFiles(files_1);
  57750. this._processReload();
  57751. }
  57752. else {
  57753. var remaining = { count: folders.length };
  57754. for (var _i = 0, folders_1 = folders; _i < folders_1.length; _i++) {
  57755. var folder = folders_1[_i];
  57756. this._traverseFolder(folder, files_1, remaining, function () {
  57757. _this._processFiles(files_1);
  57758. if (remaining.count === 0) {
  57759. _this._processReload();
  57760. }
  57761. });
  57762. }
  57763. }
  57764. }
  57765. };
  57766. FilesInput.prototype._processReload = function () {
  57767. if (this._onReloadCallback) {
  57768. this._onReloadCallback(this._sceneFileToLoad);
  57769. }
  57770. else {
  57771. this.reload();
  57772. }
  57773. };
  57774. FilesInput.prototype.reload = function () {
  57775. var _this = this;
  57776. // If a scene file has been provided
  57777. if (this._sceneFileToLoad) {
  57778. if (this._currentScene) {
  57779. if (BABYLON.Tools.errorsCount > 0) {
  57780. BABYLON.Tools.ClearLogCache();
  57781. }
  57782. this._engine.stopRenderLoop();
  57783. this._currentScene.dispose();
  57784. }
  57785. BABYLON.SceneLoader.Load("file:", this._sceneFileToLoad, this._engine, function (newScene) {
  57786. _this._currentScene = newScene;
  57787. if (_this._sceneLoadedCallback) {
  57788. _this._sceneLoadedCallback(_this._sceneFileToLoad, _this._currentScene);
  57789. }
  57790. // Wait for textures and shaders to be ready
  57791. _this._currentScene.executeWhenReady(function () {
  57792. _this._engine.runRenderLoop(function () {
  57793. _this.renderFunction();
  57794. });
  57795. });
  57796. }, function (progress) {
  57797. if (_this._progressCallback) {
  57798. _this._progressCallback(progress);
  57799. }
  57800. }, function (scene, message) {
  57801. _this._currentScene = scene;
  57802. if (_this._errorCallback) {
  57803. _this._errorCallback(_this._sceneFileToLoad, _this._currentScene, message);
  57804. }
  57805. });
  57806. }
  57807. else {
  57808. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  57809. }
  57810. };
  57811. FilesInput.FilesToLoad = {};
  57812. return FilesInput;
  57813. }());
  57814. BABYLON.FilesInput = FilesInput;
  57815. })(BABYLON || (BABYLON = {}));
  57816. //# sourceMappingURL=babylon.filesInput.js.map
  57817. var BABYLON;
  57818. (function (BABYLON) {
  57819. /**
  57820. * This class implement a typical dictionary using a string as key and the generic type T as value.
  57821. * The underlying implementation relies on an associative array to ensure the best performances.
  57822. * The value can be anything including 'null' but except 'undefined'
  57823. */
  57824. var StringDictionary = /** @class */ (function () {
  57825. function StringDictionary() {
  57826. this._count = 0;
  57827. this._data = {};
  57828. }
  57829. /**
  57830. * This will clear this dictionary and copy the content from the 'source' one.
  57831. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  57832. * @param source the dictionary to take the content from and copy to this dictionary
  57833. */
  57834. StringDictionary.prototype.copyFrom = function (source) {
  57835. var _this = this;
  57836. this.clear();
  57837. source.forEach(function (t, v) { return _this.add(t, v); });
  57838. };
  57839. /**
  57840. * Get a value based from its key
  57841. * @param key the given key to get the matching value from
  57842. * @return the value if found, otherwise undefined is returned
  57843. */
  57844. StringDictionary.prototype.get = function (key) {
  57845. var val = this._data[key];
  57846. if (val !== undefined) {
  57847. return val;
  57848. }
  57849. return undefined;
  57850. };
  57851. /**
  57852. * Get a value from its key or add it if it doesn't exist.
  57853. * This method will ensure you that a given key/data will be present in the dictionary.
  57854. * @param key the given key to get the matching value from
  57855. * @param factory the factory that will create the value if the key is not present in the dictionary.
  57856. * The factory will only be invoked if there's no data for the given key.
  57857. * @return the value corresponding to the key.
  57858. */
  57859. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  57860. var val = this.get(key);
  57861. if (val !== undefined) {
  57862. return val;
  57863. }
  57864. val = factory(key);
  57865. if (val) {
  57866. this.add(key, val);
  57867. }
  57868. return val;
  57869. };
  57870. /**
  57871. * Get a value from its key if present in the dictionary otherwise add it
  57872. * @param key the key to get the value from
  57873. * @param val if there's no such key/value pair in the dictionary add it with this value
  57874. * @return the value corresponding to the key
  57875. */
  57876. StringDictionary.prototype.getOrAdd = function (key, val) {
  57877. var curVal = this.get(key);
  57878. if (curVal !== undefined) {
  57879. return curVal;
  57880. }
  57881. this.add(key, val);
  57882. return val;
  57883. };
  57884. /**
  57885. * Check if there's a given key in the dictionary
  57886. * @param key the key to check for
  57887. * @return true if the key is present, false otherwise
  57888. */
  57889. StringDictionary.prototype.contains = function (key) {
  57890. return this._data[key] !== undefined;
  57891. };
  57892. /**
  57893. * Add a new key and its corresponding value
  57894. * @param key the key to add
  57895. * @param value the value corresponding to the key
  57896. * @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
  57897. */
  57898. StringDictionary.prototype.add = function (key, value) {
  57899. if (this._data[key] !== undefined) {
  57900. return false;
  57901. }
  57902. this._data[key] = value;
  57903. ++this._count;
  57904. return true;
  57905. };
  57906. StringDictionary.prototype.set = function (key, value) {
  57907. if (this._data[key] === undefined) {
  57908. return false;
  57909. }
  57910. this._data[key] = value;
  57911. return true;
  57912. };
  57913. /**
  57914. * Get the element of the given key and remove it from the dictionary
  57915. * @param key
  57916. */
  57917. StringDictionary.prototype.getAndRemove = function (key) {
  57918. var val = this.get(key);
  57919. if (val !== undefined) {
  57920. delete this._data[key];
  57921. --this._count;
  57922. return val;
  57923. }
  57924. return null;
  57925. };
  57926. /**
  57927. * Remove a key/value from the dictionary.
  57928. * @param key the key to remove
  57929. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  57930. */
  57931. StringDictionary.prototype.remove = function (key) {
  57932. if (this.contains(key)) {
  57933. delete this._data[key];
  57934. --this._count;
  57935. return true;
  57936. }
  57937. return false;
  57938. };
  57939. /**
  57940. * Clear the whole content of the dictionary
  57941. */
  57942. StringDictionary.prototype.clear = function () {
  57943. this._data = {};
  57944. this._count = 0;
  57945. };
  57946. Object.defineProperty(StringDictionary.prototype, "count", {
  57947. get: function () {
  57948. return this._count;
  57949. },
  57950. enumerable: true,
  57951. configurable: true
  57952. });
  57953. /**
  57954. * Execute a callback on each key/val of the dictionary.
  57955. * Note that you can remove any element in this dictionary in the callback implementation
  57956. * @param callback the callback to execute on a given key/value pair
  57957. */
  57958. StringDictionary.prototype.forEach = function (callback) {
  57959. for (var cur in this._data) {
  57960. var val = this._data[cur];
  57961. callback(cur, val);
  57962. }
  57963. };
  57964. /**
  57965. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  57966. * If the callback returns null or undefined the method will iterate to the next key/value pair
  57967. * Note that you can remove any element in this dictionary in the callback implementation
  57968. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  57969. */
  57970. StringDictionary.prototype.first = function (callback) {
  57971. for (var cur in this._data) {
  57972. var val = this._data[cur];
  57973. var res = callback(cur, val);
  57974. if (res) {
  57975. return res;
  57976. }
  57977. }
  57978. return null;
  57979. };
  57980. return StringDictionary;
  57981. }());
  57982. BABYLON.StringDictionary = StringDictionary;
  57983. })(BABYLON || (BABYLON = {}));
  57984. //# sourceMappingURL=babylon.stringDictionary.js.map
  57985. var BABYLON;
  57986. (function (BABYLON) {
  57987. var Tags = /** @class */ (function () {
  57988. function Tags() {
  57989. }
  57990. Tags.EnableFor = function (obj) {
  57991. obj._tags = obj._tags || {};
  57992. obj.hasTags = function () {
  57993. return Tags.HasTags(obj);
  57994. };
  57995. obj.addTags = function (tagsString) {
  57996. return Tags.AddTagsTo(obj, tagsString);
  57997. };
  57998. obj.removeTags = function (tagsString) {
  57999. return Tags.RemoveTagsFrom(obj, tagsString);
  58000. };
  58001. obj.matchesTagsQuery = function (tagsQuery) {
  58002. return Tags.MatchesQuery(obj, tagsQuery);
  58003. };
  58004. };
  58005. Tags.DisableFor = function (obj) {
  58006. delete obj._tags;
  58007. delete obj.hasTags;
  58008. delete obj.addTags;
  58009. delete obj.removeTags;
  58010. delete obj.matchesTagsQuery;
  58011. };
  58012. Tags.HasTags = function (obj) {
  58013. if (!obj._tags) {
  58014. return false;
  58015. }
  58016. return !BABYLON.Tools.IsEmpty(obj._tags);
  58017. };
  58018. Tags.GetTags = function (obj, asString) {
  58019. if (asString === void 0) { asString = true; }
  58020. if (!obj._tags) {
  58021. return null;
  58022. }
  58023. if (asString) {
  58024. var tagsArray = [];
  58025. for (var tag in obj._tags) {
  58026. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  58027. tagsArray.push(tag);
  58028. }
  58029. }
  58030. return tagsArray.join(" ");
  58031. }
  58032. else {
  58033. return obj._tags;
  58034. }
  58035. };
  58036. // the tags 'true' and 'false' are reserved and cannot be used as tags
  58037. // a tag cannot start with '||', '&&', and '!'
  58038. // it cannot contain whitespaces
  58039. Tags.AddTagsTo = function (obj, tagsString) {
  58040. if (!tagsString) {
  58041. return;
  58042. }
  58043. if (typeof tagsString !== "string") {
  58044. return;
  58045. }
  58046. var tags = tagsString.split(" ");
  58047. tags.forEach(function (tag, index, array) {
  58048. Tags._AddTagTo(obj, tag);
  58049. });
  58050. };
  58051. Tags._AddTagTo = function (obj, tag) {
  58052. tag = tag.trim();
  58053. if (tag === "" || tag === "true" || tag === "false") {
  58054. return;
  58055. }
  58056. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  58057. return;
  58058. }
  58059. Tags.EnableFor(obj);
  58060. obj._tags[tag] = true;
  58061. };
  58062. Tags.RemoveTagsFrom = function (obj, tagsString) {
  58063. if (!Tags.HasTags(obj)) {
  58064. return;
  58065. }
  58066. var tags = tagsString.split(" ");
  58067. for (var t in tags) {
  58068. Tags._RemoveTagFrom(obj, tags[t]);
  58069. }
  58070. };
  58071. Tags._RemoveTagFrom = function (obj, tag) {
  58072. delete obj._tags[tag];
  58073. };
  58074. Tags.MatchesQuery = function (obj, tagsQuery) {
  58075. if (tagsQuery === undefined) {
  58076. return true;
  58077. }
  58078. if (tagsQuery === "") {
  58079. return Tags.HasTags(obj);
  58080. }
  58081. return BABYLON.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  58082. };
  58083. return Tags;
  58084. }());
  58085. BABYLON.Tags = Tags;
  58086. })(BABYLON || (BABYLON = {}));
  58087. //# sourceMappingURL=babylon.tags.js.map
  58088. var BABYLON;
  58089. (function (BABYLON) {
  58090. var AndOrNotEvaluator = /** @class */ (function () {
  58091. function AndOrNotEvaluator() {
  58092. }
  58093. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  58094. if (!query.match(/\([^\(\)]*\)/g)) {
  58095. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  58096. }
  58097. else {
  58098. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  58099. // remove parenthesis
  58100. r = r.slice(1, r.length - 1);
  58101. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  58102. });
  58103. }
  58104. if (query === "true") {
  58105. return true;
  58106. }
  58107. if (query === "false") {
  58108. return false;
  58109. }
  58110. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  58111. };
  58112. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  58113. evaluateCallback = evaluateCallback || (function (r) {
  58114. return r === "true" ? true : false;
  58115. });
  58116. var result;
  58117. var or = parenthesisContent.split("||");
  58118. for (var i in or) {
  58119. if (or.hasOwnProperty(i)) {
  58120. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  58121. var and = ori.split("&&");
  58122. if (and.length > 1) {
  58123. for (var j = 0; j < and.length; ++j) {
  58124. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  58125. if (andj !== "true" && andj !== "false") {
  58126. if (andj[0] === "!") {
  58127. result = !evaluateCallback(andj.substring(1));
  58128. }
  58129. else {
  58130. result = evaluateCallback(andj);
  58131. }
  58132. }
  58133. else {
  58134. result = andj === "true" ? true : false;
  58135. }
  58136. if (!result) {
  58137. ori = "false";
  58138. break;
  58139. }
  58140. }
  58141. }
  58142. if (result || ori === "true") {
  58143. result = true;
  58144. break;
  58145. }
  58146. // result equals false (or undefined)
  58147. if (ori !== "true" && ori !== "false") {
  58148. if (ori[0] === "!") {
  58149. result = !evaluateCallback(ori.substring(1));
  58150. }
  58151. else {
  58152. result = evaluateCallback(ori);
  58153. }
  58154. }
  58155. else {
  58156. result = ori === "true" ? true : false;
  58157. }
  58158. }
  58159. }
  58160. // the whole parenthesis scope is replaced by 'true' or 'false'
  58161. return result ? "true" : "false";
  58162. };
  58163. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  58164. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  58165. // remove whitespaces
  58166. r = r.replace(/[\s]/g, function () { return ""; });
  58167. return r.length % 2 ? "!" : "";
  58168. });
  58169. booleanString = booleanString.trim();
  58170. if (booleanString === "!true") {
  58171. booleanString = "false";
  58172. }
  58173. else if (booleanString === "!false") {
  58174. booleanString = "true";
  58175. }
  58176. return booleanString;
  58177. };
  58178. return AndOrNotEvaluator;
  58179. }());
  58180. BABYLON.AndOrNotEvaluator = AndOrNotEvaluator;
  58181. })(BABYLON || (BABYLON = {}));
  58182. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  58183. var BABYLON;
  58184. (function (BABYLON) {
  58185. var Database = /** @class */ (function () {
  58186. function Database(urlToScene, callbackManifestChecked) {
  58187. // Handling various flavors of prefixed version of IndexedDB
  58188. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  58189. this.callbackManifestChecked = callbackManifestChecked;
  58190. this.currentSceneUrl = Database.ReturnFullUrlLocation(urlToScene);
  58191. this.db = null;
  58192. this._enableSceneOffline = false;
  58193. this._enableTexturesOffline = false;
  58194. this.manifestVersionFound = 0;
  58195. this.mustUpdateRessources = false;
  58196. this.hasReachedQuota = false;
  58197. if (!Database.IDBStorageEnabled) {
  58198. this.callbackManifestChecked(true);
  58199. }
  58200. else {
  58201. this.checkManifestFile();
  58202. }
  58203. }
  58204. Object.defineProperty(Database.prototype, "enableSceneOffline", {
  58205. get: function () {
  58206. return this._enableSceneOffline;
  58207. },
  58208. enumerable: true,
  58209. configurable: true
  58210. });
  58211. Object.defineProperty(Database.prototype, "enableTexturesOffline", {
  58212. get: function () {
  58213. return this._enableTexturesOffline;
  58214. },
  58215. enumerable: true,
  58216. configurable: true
  58217. });
  58218. Database.prototype.checkManifestFile = function () {
  58219. var _this = this;
  58220. var noManifestFile = function () {
  58221. _this._enableSceneOffline = false;
  58222. _this._enableTexturesOffline = false;
  58223. _this.callbackManifestChecked(false);
  58224. };
  58225. var timeStampUsed = false;
  58226. var manifestURL = this.currentSceneUrl + ".manifest";
  58227. var xhr = new XMLHttpRequest();
  58228. if (navigator.onLine) {
  58229. // Adding a timestamp to by-pass browsers' cache
  58230. timeStampUsed = true;
  58231. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  58232. }
  58233. xhr.open("GET", manifestURL, true);
  58234. xhr.addEventListener("load", function () {
  58235. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  58236. try {
  58237. var manifestFile = JSON.parse(xhr.response);
  58238. _this._enableSceneOffline = manifestFile.enableSceneOffline;
  58239. _this._enableTexturesOffline = manifestFile.enableTexturesOffline;
  58240. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  58241. _this.manifestVersionFound = manifestFile.version;
  58242. }
  58243. if (_this.callbackManifestChecked) {
  58244. _this.callbackManifestChecked(true);
  58245. }
  58246. }
  58247. catch (ex) {
  58248. noManifestFile();
  58249. }
  58250. }
  58251. else {
  58252. noManifestFile();
  58253. }
  58254. }, false);
  58255. xhr.addEventListener("error", function (event) {
  58256. if (timeStampUsed) {
  58257. timeStampUsed = false;
  58258. // Let's retry without the timeStamp
  58259. // It could fail when coupled with HTML5 Offline API
  58260. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  58261. xhr.open("GET", retryManifestURL, true);
  58262. xhr.send();
  58263. }
  58264. else {
  58265. noManifestFile();
  58266. }
  58267. }, false);
  58268. try {
  58269. xhr.send();
  58270. }
  58271. catch (ex) {
  58272. BABYLON.Tools.Error("Error on XHR send request.");
  58273. this.callbackManifestChecked(false);
  58274. }
  58275. };
  58276. Database.prototype.openAsync = function (successCallback, errorCallback) {
  58277. var _this = this;
  58278. var handleError = function () {
  58279. _this.isSupported = false;
  58280. if (errorCallback)
  58281. errorCallback();
  58282. };
  58283. if (!this.idbFactory || !(this._enableSceneOffline || this._enableTexturesOffline)) {
  58284. // Your browser doesn't support IndexedDB
  58285. this.isSupported = false;
  58286. if (errorCallback)
  58287. errorCallback();
  58288. }
  58289. else {
  58290. // If the DB hasn't been opened or created yet
  58291. if (!this.db) {
  58292. this.hasReachedQuota = false;
  58293. this.isSupported = true;
  58294. var request = this.idbFactory.open("babylonjs", 1);
  58295. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  58296. request.onerror = function (event) {
  58297. handleError();
  58298. };
  58299. // executes when a version change transaction cannot complete due to other active transactions
  58300. request.onblocked = function (event) {
  58301. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  58302. handleError();
  58303. };
  58304. // DB has been opened successfully
  58305. request.onsuccess = function (event) {
  58306. _this.db = request.result;
  58307. successCallback();
  58308. };
  58309. // Initialization of the DB. Creating Scenes & Textures stores
  58310. request.onupgradeneeded = function (event) {
  58311. _this.db = (event.target).result;
  58312. if (_this.db) {
  58313. try {
  58314. _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  58315. _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  58316. _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  58317. }
  58318. catch (ex) {
  58319. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  58320. handleError();
  58321. }
  58322. }
  58323. };
  58324. }
  58325. else {
  58326. if (successCallback)
  58327. successCallback();
  58328. }
  58329. }
  58330. };
  58331. Database.prototype.loadImageFromDB = function (url, image) {
  58332. var _this = this;
  58333. var completeURL = Database.ReturnFullUrlLocation(url);
  58334. var saveAndLoadImage = function () {
  58335. if (!_this.hasReachedQuota && _this.db !== null) {
  58336. // the texture is not yet in the DB, let's try to save it
  58337. _this._saveImageIntoDBAsync(completeURL, image);
  58338. }
  58339. else {
  58340. image.src = url;
  58341. }
  58342. };
  58343. if (!this.mustUpdateRessources) {
  58344. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  58345. }
  58346. else {
  58347. saveAndLoadImage();
  58348. }
  58349. };
  58350. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  58351. if (this.isSupported && this.db !== null) {
  58352. var texture;
  58353. var transaction = this.db.transaction(["textures"]);
  58354. transaction.onabort = function (event) {
  58355. image.src = url;
  58356. };
  58357. transaction.oncomplete = function (event) {
  58358. var blobTextureURL;
  58359. if (texture) {
  58360. var URL = window.URL || window.webkitURL;
  58361. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  58362. image.onerror = function () {
  58363. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  58364. image.src = url;
  58365. };
  58366. image.src = blobTextureURL;
  58367. }
  58368. else {
  58369. notInDBCallback();
  58370. }
  58371. };
  58372. var getRequest = transaction.objectStore("textures").get(url);
  58373. getRequest.onsuccess = function (event) {
  58374. texture = (event.target).result;
  58375. };
  58376. getRequest.onerror = function (event) {
  58377. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  58378. image.src = url;
  58379. };
  58380. }
  58381. else {
  58382. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  58383. image.src = url;
  58384. }
  58385. };
  58386. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  58387. var _this = this;
  58388. if (this.isSupported) {
  58389. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  58390. var generateBlobUrl = function () {
  58391. var blobTextureURL;
  58392. if (blob) {
  58393. var URL = window.URL || window.webkitURL;
  58394. try {
  58395. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  58396. }
  58397. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  58398. catch (ex) {
  58399. blobTextureURL = URL.createObjectURL(blob);
  58400. }
  58401. }
  58402. if (blobTextureURL) {
  58403. image.src = blobTextureURL;
  58404. }
  58405. };
  58406. if (Database.IsUASupportingBlobStorage) {
  58407. var xhr = new XMLHttpRequest(), blob;
  58408. xhr.open("GET", url, true);
  58409. xhr.responseType = "blob";
  58410. xhr.addEventListener("load", function () {
  58411. if (xhr.status === 200 && _this.db) {
  58412. // Blob as response (XHR2)
  58413. blob = xhr.response;
  58414. var transaction = _this.db.transaction(["textures"], "readwrite");
  58415. // the transaction could abort because of a QuotaExceededError error
  58416. transaction.onabort = function (event) {
  58417. try {
  58418. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  58419. var srcElement = (event.srcElement || event.target);
  58420. var error = srcElement.error;
  58421. if (error && error.name === "QuotaExceededError") {
  58422. _this.hasReachedQuota = true;
  58423. }
  58424. }
  58425. catch (ex) { }
  58426. generateBlobUrl();
  58427. };
  58428. transaction.oncomplete = function (event) {
  58429. generateBlobUrl();
  58430. };
  58431. var newTexture = { textureUrl: url, data: blob };
  58432. try {
  58433. // Put the blob into the dabase
  58434. var addRequest = transaction.objectStore("textures").put(newTexture);
  58435. addRequest.onsuccess = function (event) {
  58436. };
  58437. addRequest.onerror = function (event) {
  58438. generateBlobUrl();
  58439. };
  58440. }
  58441. catch (ex) {
  58442. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  58443. if (ex.code === 25) {
  58444. Database.IsUASupportingBlobStorage = false;
  58445. }
  58446. image.src = url;
  58447. }
  58448. }
  58449. else {
  58450. image.src = url;
  58451. }
  58452. }, false);
  58453. xhr.addEventListener("error", function (event) {
  58454. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  58455. image.src = url;
  58456. }, false);
  58457. xhr.send();
  58458. }
  58459. else {
  58460. image.src = url;
  58461. }
  58462. }
  58463. else {
  58464. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  58465. image.src = url;
  58466. }
  58467. };
  58468. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  58469. var _this = this;
  58470. var updateVersion = function () {
  58471. // the version is not yet in the DB or we need to update it
  58472. _this._saveVersionIntoDBAsync(url, versionLoaded);
  58473. };
  58474. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  58475. };
  58476. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  58477. var _this = this;
  58478. if (this.isSupported && this.db) {
  58479. var version;
  58480. try {
  58481. var transaction = this.db.transaction(["versions"]);
  58482. transaction.oncomplete = function (event) {
  58483. if (version) {
  58484. // If the version in the JSON file is > than the version in DB
  58485. if (_this.manifestVersionFound > version.data) {
  58486. _this.mustUpdateRessources = true;
  58487. updateInDBCallback();
  58488. }
  58489. else {
  58490. callback(version.data);
  58491. }
  58492. }
  58493. else {
  58494. _this.mustUpdateRessources = true;
  58495. updateInDBCallback();
  58496. }
  58497. };
  58498. transaction.onabort = function (event) {
  58499. callback(-1);
  58500. };
  58501. var getRequest = transaction.objectStore("versions").get(url);
  58502. getRequest.onsuccess = function (event) {
  58503. version = (event.target).result;
  58504. };
  58505. getRequest.onerror = function (event) {
  58506. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  58507. callback(-1);
  58508. };
  58509. }
  58510. catch (ex) {
  58511. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  58512. callback(-1);
  58513. }
  58514. }
  58515. else {
  58516. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  58517. callback(-1);
  58518. }
  58519. };
  58520. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  58521. var _this = this;
  58522. if (this.isSupported && !this.hasReachedQuota && this.db) {
  58523. try {
  58524. // Open a transaction to the database
  58525. var transaction = this.db.transaction(["versions"], "readwrite");
  58526. // the transaction could abort because of a QuotaExceededError error
  58527. transaction.onabort = function (event) {
  58528. try {
  58529. var error = event.srcElement['error'];
  58530. if (error && error.name === "QuotaExceededError") {
  58531. _this.hasReachedQuota = true;
  58532. }
  58533. }
  58534. catch (ex) { }
  58535. callback(-1);
  58536. };
  58537. transaction.oncomplete = function (event) {
  58538. callback(_this.manifestVersionFound);
  58539. };
  58540. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  58541. // Put the scene into the database
  58542. var addRequest = transaction.objectStore("versions").put(newVersion);
  58543. addRequest.onsuccess = function (event) {
  58544. };
  58545. addRequest.onerror = function (event) {
  58546. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  58547. };
  58548. }
  58549. catch (ex) {
  58550. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  58551. callback(-1);
  58552. }
  58553. }
  58554. else {
  58555. callback(-1);
  58556. }
  58557. };
  58558. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  58559. var _this = this;
  58560. var completeUrl = Database.ReturnFullUrlLocation(url);
  58561. var saveAndLoadFile = function () {
  58562. // the scene is not yet in the DB, let's try to save it
  58563. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  58564. };
  58565. this._checkVersionFromDB(completeUrl, function (version) {
  58566. if (version !== -1) {
  58567. if (!_this.mustUpdateRessources) {
  58568. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  58569. }
  58570. else {
  58571. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  58572. }
  58573. }
  58574. else {
  58575. if (errorCallback) {
  58576. errorCallback();
  58577. }
  58578. }
  58579. });
  58580. };
  58581. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  58582. if (this.isSupported && this.db) {
  58583. var targetStore;
  58584. if (url.indexOf(".babylon") !== -1) {
  58585. targetStore = "scenes";
  58586. }
  58587. else {
  58588. targetStore = "textures";
  58589. }
  58590. var file;
  58591. var transaction = this.db.transaction([targetStore]);
  58592. transaction.oncomplete = function (event) {
  58593. if (file) {
  58594. callback(file.data);
  58595. }
  58596. else {
  58597. notInDBCallback();
  58598. }
  58599. };
  58600. transaction.onabort = function (event) {
  58601. notInDBCallback();
  58602. };
  58603. var getRequest = transaction.objectStore(targetStore).get(url);
  58604. getRequest.onsuccess = function (event) {
  58605. file = (event.target).result;
  58606. };
  58607. getRequest.onerror = function (event) {
  58608. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  58609. notInDBCallback();
  58610. };
  58611. }
  58612. else {
  58613. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  58614. callback();
  58615. }
  58616. };
  58617. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  58618. var _this = this;
  58619. if (this.isSupported) {
  58620. var targetStore;
  58621. if (url.indexOf(".babylon") !== -1) {
  58622. targetStore = "scenes";
  58623. }
  58624. else {
  58625. targetStore = "textures";
  58626. }
  58627. // Create XHR
  58628. var xhr = new XMLHttpRequest();
  58629. var fileData;
  58630. xhr.open("GET", url, true);
  58631. if (useArrayBuffer) {
  58632. xhr.responseType = "arraybuffer";
  58633. }
  58634. if (progressCallback) {
  58635. xhr.onprogress = progressCallback;
  58636. }
  58637. xhr.addEventListener("load", function () {
  58638. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  58639. // Blob as response (XHR2)
  58640. //fileData = xhr.responseText;
  58641. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  58642. if (!_this.hasReachedQuota && _this.db) {
  58643. // Open a transaction to the database
  58644. var transaction = _this.db.transaction([targetStore], "readwrite");
  58645. // the transaction could abort because of a QuotaExceededError error
  58646. transaction.onabort = function (event) {
  58647. try {
  58648. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  58649. var error = event.srcElement['error'];
  58650. if (error && error.name === "QuotaExceededError") {
  58651. _this.hasReachedQuota = true;
  58652. }
  58653. }
  58654. catch (ex) { }
  58655. callback(fileData);
  58656. };
  58657. transaction.oncomplete = function (event) {
  58658. callback(fileData);
  58659. };
  58660. var newFile;
  58661. if (targetStore === "scenes") {
  58662. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  58663. }
  58664. else {
  58665. newFile = { textureUrl: url, data: fileData };
  58666. }
  58667. try {
  58668. // Put the scene into the database
  58669. var addRequest = transaction.objectStore(targetStore).put(newFile);
  58670. addRequest.onsuccess = function (event) {
  58671. };
  58672. addRequest.onerror = function (event) {
  58673. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  58674. };
  58675. }
  58676. catch (ex) {
  58677. callback(fileData);
  58678. }
  58679. }
  58680. else {
  58681. callback(fileData);
  58682. }
  58683. }
  58684. else {
  58685. callback();
  58686. }
  58687. }, false);
  58688. xhr.addEventListener("error", function (event) {
  58689. BABYLON.Tools.Error("error on XHR request.");
  58690. callback();
  58691. }, false);
  58692. xhr.send();
  58693. }
  58694. else {
  58695. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  58696. callback();
  58697. }
  58698. };
  58699. Database.IsUASupportingBlobStorage = true;
  58700. Database.IDBStorageEnabled = true;
  58701. Database.parseURL = function (url) {
  58702. var a = document.createElement('a');
  58703. a.href = url;
  58704. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  58705. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  58706. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  58707. return absLocation;
  58708. };
  58709. Database.ReturnFullUrlLocation = function (url) {
  58710. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  58711. return (Database.parseURL(window.location.href) + url);
  58712. }
  58713. else {
  58714. return url;
  58715. }
  58716. };
  58717. return Database;
  58718. }());
  58719. BABYLON.Database = Database;
  58720. })(BABYLON || (BABYLON = {}));
  58721. //# sourceMappingURL=babylon.database.js.map
  58722. var BABYLON;
  58723. (function (BABYLON) {
  58724. var FresnelParameters = /** @class */ (function () {
  58725. function FresnelParameters() {
  58726. this._isEnabled = true;
  58727. this.leftColor = BABYLON.Color3.White();
  58728. this.rightColor = BABYLON.Color3.Black();
  58729. this.bias = 0;
  58730. this.power = 1;
  58731. }
  58732. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  58733. get: function () {
  58734. return this._isEnabled;
  58735. },
  58736. set: function (value) {
  58737. if (this._isEnabled === value) {
  58738. return;
  58739. }
  58740. this._isEnabled = value;
  58741. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  58742. },
  58743. enumerable: true,
  58744. configurable: true
  58745. });
  58746. FresnelParameters.prototype.clone = function () {
  58747. var newFresnelParameters = new FresnelParameters();
  58748. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  58749. return newFresnelParameters;
  58750. };
  58751. FresnelParameters.prototype.serialize = function () {
  58752. var serializationObject = {};
  58753. serializationObject.isEnabled = this.isEnabled;
  58754. serializationObject.leftColor = this.leftColor;
  58755. serializationObject.rightColor = this.rightColor;
  58756. serializationObject.bias = this.bias;
  58757. serializationObject.power = this.power;
  58758. return serializationObject;
  58759. };
  58760. FresnelParameters.Parse = function (parsedFresnelParameters) {
  58761. var fresnelParameters = new FresnelParameters();
  58762. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  58763. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  58764. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  58765. fresnelParameters.bias = parsedFresnelParameters.bias;
  58766. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  58767. return fresnelParameters;
  58768. };
  58769. return FresnelParameters;
  58770. }());
  58771. BABYLON.FresnelParameters = FresnelParameters;
  58772. })(BABYLON || (BABYLON = {}));
  58773. //# sourceMappingURL=babylon.fresnelParameters.js.map
  58774. var BABYLON;
  58775. (function (BABYLON) {
  58776. var MultiMaterial = /** @class */ (function (_super) {
  58777. __extends(MultiMaterial, _super);
  58778. function MultiMaterial(name, scene) {
  58779. var _this = _super.call(this, name, scene, true) || this;
  58780. scene.multiMaterials.push(_this);
  58781. _this.subMaterials = new Array();
  58782. _this.storeEffectOnSubMeshes = true; // multimaterial is considered like a push material
  58783. return _this;
  58784. }
  58785. Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
  58786. get: function () {
  58787. return this._subMaterials;
  58788. },
  58789. set: function (value) {
  58790. this._subMaterials = value;
  58791. this._hookArray(value);
  58792. },
  58793. enumerable: true,
  58794. configurable: true
  58795. });
  58796. MultiMaterial.prototype._hookArray = function (array) {
  58797. var _this = this;
  58798. var oldPush = array.push;
  58799. array.push = function () {
  58800. var items = [];
  58801. for (var _i = 0; _i < arguments.length; _i++) {
  58802. items[_i] = arguments[_i];
  58803. }
  58804. var result = oldPush.apply(array, items);
  58805. _this._markAllSubMeshesAsTexturesDirty();
  58806. return result;
  58807. };
  58808. var oldSplice = array.splice;
  58809. array.splice = function (index, deleteCount) {
  58810. var deleted = oldSplice.apply(array, [index, deleteCount]);
  58811. _this._markAllSubMeshesAsTexturesDirty();
  58812. return deleted;
  58813. };
  58814. };
  58815. // Properties
  58816. MultiMaterial.prototype.getSubMaterial = function (index) {
  58817. if (index < 0 || index >= this.subMaterials.length) {
  58818. return this.getScene().defaultMaterial;
  58819. }
  58820. return this.subMaterials[index];
  58821. };
  58822. MultiMaterial.prototype.getActiveTextures = function () {
  58823. return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) {
  58824. if (subMaterial) {
  58825. return subMaterial.getActiveTextures();
  58826. }
  58827. else {
  58828. return [];
  58829. }
  58830. }));
  58831. var _a;
  58832. };
  58833. // Methods
  58834. MultiMaterial.prototype.getClassName = function () {
  58835. return "MultiMaterial";
  58836. };
  58837. MultiMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  58838. for (var index = 0; index < this.subMaterials.length; index++) {
  58839. var subMaterial = this.subMaterials[index];
  58840. if (subMaterial) {
  58841. if (subMaterial.storeEffectOnSubMeshes) {
  58842. if (!subMaterial.isReadyForSubMesh(mesh, subMesh, useInstances)) {
  58843. return false;
  58844. }
  58845. continue;
  58846. }
  58847. if (!subMaterial.isReady(mesh)) {
  58848. return false;
  58849. }
  58850. }
  58851. }
  58852. return true;
  58853. };
  58854. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  58855. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  58856. for (var index = 0; index < this.subMaterials.length; index++) {
  58857. var subMaterial = null;
  58858. var current = this.subMaterials[index];
  58859. if (cloneChildren && current) {
  58860. subMaterial = current.clone(name + "-" + current.name);
  58861. }
  58862. else {
  58863. subMaterial = this.subMaterials[index];
  58864. }
  58865. newMultiMaterial.subMaterials.push(subMaterial);
  58866. }
  58867. return newMultiMaterial;
  58868. };
  58869. MultiMaterial.prototype.serialize = function () {
  58870. var serializationObject = {};
  58871. serializationObject.name = this.name;
  58872. serializationObject.id = this.id;
  58873. if (BABYLON.Tags) {
  58874. serializationObject.tags = BABYLON.Tags.GetTags(this);
  58875. }
  58876. serializationObject.materials = [];
  58877. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  58878. var subMat = this.subMaterials[matIndex];
  58879. if (subMat) {
  58880. serializationObject.materials.push(subMat.id);
  58881. }
  58882. else {
  58883. serializationObject.materials.push(null);
  58884. }
  58885. }
  58886. return serializationObject;
  58887. };
  58888. MultiMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  58889. var scene = this.getScene();
  58890. if (!scene) {
  58891. return;
  58892. }
  58893. var index = scene.multiMaterials.indexOf(this);
  58894. if (index >= 0) {
  58895. scene.multiMaterials.splice(index, 1);
  58896. }
  58897. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  58898. };
  58899. return MultiMaterial;
  58900. }(BABYLON.Material));
  58901. BABYLON.MultiMaterial = MultiMaterial;
  58902. })(BABYLON || (BABYLON = {}));
  58903. //# sourceMappingURL=babylon.multiMaterial.js.map
  58904. var BABYLON;
  58905. (function (BABYLON) {
  58906. var FreeCameraTouchInput = /** @class */ (function () {
  58907. function FreeCameraTouchInput() {
  58908. this._offsetX = null;
  58909. this._offsetY = null;
  58910. this._pointerPressed = new Array();
  58911. this.touchAngularSensibility = 200000.0;
  58912. this.touchMoveSensibility = 250.0;
  58913. }
  58914. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  58915. var _this = this;
  58916. var previousPosition = null;
  58917. if (this._pointerInput === undefined) {
  58918. this._onLostFocus = function (evt) {
  58919. _this._offsetX = null;
  58920. _this._offsetY = null;
  58921. };
  58922. this._pointerInput = function (p, s) {
  58923. var evt = p.event;
  58924. if (evt.pointerType === "mouse") {
  58925. return;
  58926. }
  58927. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  58928. if (!noPreventDefault) {
  58929. evt.preventDefault();
  58930. }
  58931. _this._pointerPressed.push(evt.pointerId);
  58932. if (_this._pointerPressed.length !== 1) {
  58933. return;
  58934. }
  58935. previousPosition = {
  58936. x: evt.clientX,
  58937. y: evt.clientY
  58938. };
  58939. }
  58940. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  58941. if (!noPreventDefault) {
  58942. evt.preventDefault();
  58943. }
  58944. var index = _this._pointerPressed.indexOf(evt.pointerId);
  58945. if (index === -1) {
  58946. return;
  58947. }
  58948. _this._pointerPressed.splice(index, 1);
  58949. if (index != 0) {
  58950. return;
  58951. }
  58952. previousPosition = null;
  58953. _this._offsetX = null;
  58954. _this._offsetY = null;
  58955. }
  58956. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  58957. if (!noPreventDefault) {
  58958. evt.preventDefault();
  58959. }
  58960. if (!previousPosition) {
  58961. return;
  58962. }
  58963. var index = _this._pointerPressed.indexOf(evt.pointerId);
  58964. if (index != 0) {
  58965. return;
  58966. }
  58967. _this._offsetX = evt.clientX - previousPosition.x;
  58968. _this._offsetY = -(evt.clientY - previousPosition.y);
  58969. }
  58970. };
  58971. }
  58972. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  58973. if (this._onLostFocus) {
  58974. element.addEventListener("blur", this._onLostFocus);
  58975. }
  58976. };
  58977. FreeCameraTouchInput.prototype.detachControl = function (element) {
  58978. if (this._pointerInput && element) {
  58979. if (this._observer) {
  58980. this.camera.getScene().onPointerObservable.remove(this._observer);
  58981. this._observer = null;
  58982. }
  58983. if (this._onLostFocus) {
  58984. element.removeEventListener("blur", this._onLostFocus);
  58985. this._onLostFocus = null;
  58986. }
  58987. this._pointerPressed = [];
  58988. this._offsetX = null;
  58989. this._offsetY = null;
  58990. }
  58991. };
  58992. FreeCameraTouchInput.prototype.checkInputs = function () {
  58993. if (this._offsetX && this._offsetY) {
  58994. var camera = this.camera;
  58995. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  58996. if (this._pointerPressed.length > 1) {
  58997. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  58998. }
  58999. else {
  59000. var speed = camera._computeLocalCameraSpeed();
  59001. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  59002. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  59003. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  59004. }
  59005. }
  59006. };
  59007. FreeCameraTouchInput.prototype.getClassName = function () {
  59008. return "FreeCameraTouchInput";
  59009. };
  59010. FreeCameraTouchInput.prototype.getSimpleName = function () {
  59011. return "touch";
  59012. };
  59013. __decorate([
  59014. BABYLON.serialize()
  59015. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  59016. __decorate([
  59017. BABYLON.serialize()
  59018. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  59019. return FreeCameraTouchInput;
  59020. }());
  59021. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  59022. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  59023. })(BABYLON || (BABYLON = {}));
  59024. //# sourceMappingURL=babylon.freeCameraTouchInput.js.map
  59025. var BABYLON;
  59026. (function (BABYLON) {
  59027. // We're mainly based on the logic defined into the FreeCamera code
  59028. var TouchCamera = /** @class */ (function (_super) {
  59029. __extends(TouchCamera, _super);
  59030. //-- end properties for backward compatibility for inputs
  59031. function TouchCamera(name, position, scene) {
  59032. var _this = _super.call(this, name, position, scene) || this;
  59033. _this.inputs.addTouch();
  59034. _this._setupInputs();
  59035. return _this;
  59036. }
  59037. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  59038. //-- Begin properties for backward compatibility for inputs
  59039. get: function () {
  59040. var touch = this.inputs.attached["touch"];
  59041. if (touch)
  59042. return touch.touchAngularSensibility;
  59043. return 0;
  59044. },
  59045. set: function (value) {
  59046. var touch = this.inputs.attached["touch"];
  59047. if (touch)
  59048. touch.touchAngularSensibility = value;
  59049. },
  59050. enumerable: true,
  59051. configurable: true
  59052. });
  59053. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  59054. get: function () {
  59055. var touch = this.inputs.attached["touch"];
  59056. if (touch)
  59057. return touch.touchMoveSensibility;
  59058. return 0;
  59059. },
  59060. set: function (value) {
  59061. var touch = this.inputs.attached["touch"];
  59062. if (touch)
  59063. touch.touchMoveSensibility = value;
  59064. },
  59065. enumerable: true,
  59066. configurable: true
  59067. });
  59068. TouchCamera.prototype.getClassName = function () {
  59069. return "TouchCamera";
  59070. };
  59071. TouchCamera.prototype._setupInputs = function () {
  59072. var mouse = this.inputs.attached["mouse"];
  59073. if (mouse) {
  59074. mouse.touchEnabled = false;
  59075. }
  59076. };
  59077. return TouchCamera;
  59078. }(BABYLON.FreeCamera));
  59079. BABYLON.TouchCamera = TouchCamera;
  59080. })(BABYLON || (BABYLON = {}));
  59081. //# sourceMappingURL=babylon.touchCamera.js.map
  59082. var BABYLON;
  59083. (function (BABYLON) {
  59084. var ProceduralTexture = /** @class */ (function (_super) {
  59085. __extends(ProceduralTexture, _super);
  59086. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  59087. if (fallbackTexture === void 0) { fallbackTexture = null; }
  59088. if (generateMipMaps === void 0) { generateMipMaps = true; }
  59089. if (isCube === void 0) { isCube = false; }
  59090. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  59091. _this.isCube = isCube;
  59092. _this.isEnabled = true;
  59093. _this._currentRefreshId = -1;
  59094. _this._refreshRate = 1;
  59095. _this._vertexBuffers = {};
  59096. _this._uniforms = new Array();
  59097. _this._samplers = new Array();
  59098. _this._textures = {};
  59099. _this._floats = {};
  59100. _this._floatsArrays = {};
  59101. _this._colors3 = {};
  59102. _this._colors4 = {};
  59103. _this._vectors2 = {};
  59104. _this._vectors3 = {};
  59105. _this._matrices = {};
  59106. _this._fallbackTextureUsed = false;
  59107. scene._proceduralTextures.push(_this);
  59108. _this._engine = scene.getEngine();
  59109. _this.name = name;
  59110. _this.isRenderTarget = true;
  59111. _this._size = size;
  59112. _this._generateMipMaps = generateMipMaps;
  59113. _this.setFragment(fragment);
  59114. _this._fallbackTexture = fallbackTexture;
  59115. if (isCube) {
  59116. _this._texture = _this._engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  59117. _this.setFloat("face", 0);
  59118. }
  59119. else {
  59120. _this._texture = _this._engine.createRenderTargetTexture(size, generateMipMaps);
  59121. }
  59122. // VBO
  59123. var vertices = [];
  59124. vertices.push(1, 1);
  59125. vertices.push(-1, 1);
  59126. vertices.push(-1, -1);
  59127. vertices.push(1, -1);
  59128. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(_this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  59129. _this._createIndexBuffer();
  59130. return _this;
  59131. }
  59132. ProceduralTexture.prototype._createIndexBuffer = function () {
  59133. var engine = this._engine;
  59134. // Indices
  59135. var indices = [];
  59136. indices.push(0);
  59137. indices.push(1);
  59138. indices.push(2);
  59139. indices.push(0);
  59140. indices.push(2);
  59141. indices.push(3);
  59142. this._indexBuffer = engine.createIndexBuffer(indices);
  59143. };
  59144. ProceduralTexture.prototype._rebuild = function () {
  59145. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  59146. if (vb) {
  59147. vb._rebuild();
  59148. }
  59149. this._createIndexBuffer();
  59150. if (this.refreshRate === BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  59151. this.refreshRate = BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  59152. }
  59153. };
  59154. ProceduralTexture.prototype.reset = function () {
  59155. if (this._effect === undefined) {
  59156. return;
  59157. }
  59158. var engine = this._engine;
  59159. engine._releaseEffect(this._effect);
  59160. };
  59161. ProceduralTexture.prototype.isReady = function () {
  59162. var _this = this;
  59163. var engine = this._engine;
  59164. var shaders;
  59165. if (!this._fragment) {
  59166. return false;
  59167. }
  59168. if (this._fallbackTextureUsed) {
  59169. return true;
  59170. }
  59171. if (this._fragment.fragmentElement !== undefined) {
  59172. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  59173. }
  59174. else {
  59175. shaders = { vertex: "procedural", fragment: this._fragment };
  59176. }
  59177. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", undefined, undefined, function () {
  59178. _this.releaseInternalTexture();
  59179. if (_this._fallbackTexture) {
  59180. _this._texture = _this._fallbackTexture._texture;
  59181. if (_this._texture) {
  59182. _this._texture.incrementReferences();
  59183. }
  59184. }
  59185. _this._fallbackTextureUsed = true;
  59186. });
  59187. return this._effect.isReady();
  59188. };
  59189. ProceduralTexture.prototype.resetRefreshCounter = function () {
  59190. this._currentRefreshId = -1;
  59191. };
  59192. ProceduralTexture.prototype.setFragment = function (fragment) {
  59193. this._fragment = fragment;
  59194. };
  59195. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  59196. get: function () {
  59197. return this._refreshRate;
  59198. },
  59199. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  59200. set: function (value) {
  59201. this._refreshRate = value;
  59202. this.resetRefreshCounter();
  59203. },
  59204. enumerable: true,
  59205. configurable: true
  59206. });
  59207. ProceduralTexture.prototype._shouldRender = function () {
  59208. if (!this.isEnabled || !this.isReady() || !this._texture) {
  59209. return false;
  59210. }
  59211. if (this._fallbackTextureUsed) {
  59212. return false;
  59213. }
  59214. if (this._currentRefreshId === -1) {
  59215. this._currentRefreshId = 1;
  59216. return true;
  59217. }
  59218. if (this.refreshRate === this._currentRefreshId) {
  59219. this._currentRefreshId = 1;
  59220. return true;
  59221. }
  59222. this._currentRefreshId++;
  59223. return false;
  59224. };
  59225. ProceduralTexture.prototype.getRenderSize = function () {
  59226. return this._size;
  59227. };
  59228. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  59229. if (this._fallbackTextureUsed) {
  59230. return;
  59231. }
  59232. this.releaseInternalTexture();
  59233. this._texture = this._engine.createRenderTargetTexture(size, generateMipMaps);
  59234. };
  59235. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  59236. if (this._uniforms.indexOf(uniformName) === -1) {
  59237. this._uniforms.push(uniformName);
  59238. }
  59239. };
  59240. ProceduralTexture.prototype.setTexture = function (name, texture) {
  59241. if (this._samplers.indexOf(name) === -1) {
  59242. this._samplers.push(name);
  59243. }
  59244. this._textures[name] = texture;
  59245. return this;
  59246. };
  59247. ProceduralTexture.prototype.setFloat = function (name, value) {
  59248. this._checkUniform(name);
  59249. this._floats[name] = value;
  59250. return this;
  59251. };
  59252. ProceduralTexture.prototype.setFloats = function (name, value) {
  59253. this._checkUniform(name);
  59254. this._floatsArrays[name] = value;
  59255. return this;
  59256. };
  59257. ProceduralTexture.prototype.setColor3 = function (name, value) {
  59258. this._checkUniform(name);
  59259. this._colors3[name] = value;
  59260. return this;
  59261. };
  59262. ProceduralTexture.prototype.setColor4 = function (name, value) {
  59263. this._checkUniform(name);
  59264. this._colors4[name] = value;
  59265. return this;
  59266. };
  59267. ProceduralTexture.prototype.setVector2 = function (name, value) {
  59268. this._checkUniform(name);
  59269. this._vectors2[name] = value;
  59270. return this;
  59271. };
  59272. ProceduralTexture.prototype.setVector3 = function (name, value) {
  59273. this._checkUniform(name);
  59274. this._vectors3[name] = value;
  59275. return this;
  59276. };
  59277. ProceduralTexture.prototype.setMatrix = function (name, value) {
  59278. this._checkUniform(name);
  59279. this._matrices[name] = value;
  59280. return this;
  59281. };
  59282. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  59283. var scene = this.getScene();
  59284. if (!scene) {
  59285. return;
  59286. }
  59287. var engine = this._engine;
  59288. // Render
  59289. engine.enableEffect(this._effect);
  59290. engine.setState(false);
  59291. // Texture
  59292. for (var name in this._textures) {
  59293. this._effect.setTexture(name, this._textures[name]);
  59294. }
  59295. // Float
  59296. for (name in this._floats) {
  59297. this._effect.setFloat(name, this._floats[name]);
  59298. }
  59299. // Floats
  59300. for (name in this._floatsArrays) {
  59301. this._effect.setArray(name, this._floatsArrays[name]);
  59302. }
  59303. // Color3
  59304. for (name in this._colors3) {
  59305. this._effect.setColor3(name, this._colors3[name]);
  59306. }
  59307. // Color4
  59308. for (name in this._colors4) {
  59309. var color = this._colors4[name];
  59310. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  59311. }
  59312. // Vector2
  59313. for (name in this._vectors2) {
  59314. this._effect.setVector2(name, this._vectors2[name]);
  59315. }
  59316. // Vector3
  59317. for (name in this._vectors3) {
  59318. this._effect.setVector3(name, this._vectors3[name]);
  59319. }
  59320. // Matrix
  59321. for (name in this._matrices) {
  59322. this._effect.setMatrix(name, this._matrices[name]);
  59323. }
  59324. if (!this._texture) {
  59325. return;
  59326. }
  59327. if (this.isCube) {
  59328. for (var face = 0; face < 6; face++) {
  59329. engine.bindFramebuffer(this._texture, face, undefined, undefined, true);
  59330. // VBOs
  59331. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  59332. this._effect.setFloat("face", face);
  59333. // Clear
  59334. engine.clear(scene.clearColor, true, true, true);
  59335. // Draw order
  59336. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  59337. // Mipmaps
  59338. if (face === 5) {
  59339. engine.generateMipMapsForCubemap(this._texture);
  59340. }
  59341. }
  59342. }
  59343. else {
  59344. engine.bindFramebuffer(this._texture, 0, undefined, undefined, true);
  59345. // VBOs
  59346. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  59347. // Clear
  59348. engine.clear(scene.clearColor, true, true, true);
  59349. // Draw order
  59350. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  59351. }
  59352. // Unbind
  59353. engine.unBindFramebuffer(this._texture, this.isCube);
  59354. if (this.onGenerated) {
  59355. this.onGenerated();
  59356. }
  59357. };
  59358. ProceduralTexture.prototype.clone = function () {
  59359. var textureSize = this.getSize();
  59360. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  59361. // Base texture
  59362. newTexture.hasAlpha = this.hasAlpha;
  59363. newTexture.level = this.level;
  59364. // RenderTarget Texture
  59365. newTexture.coordinatesMode = this.coordinatesMode;
  59366. return newTexture;
  59367. };
  59368. ProceduralTexture.prototype.dispose = function () {
  59369. var scene = this.getScene();
  59370. if (!scene) {
  59371. return;
  59372. }
  59373. var index = scene._proceduralTextures.indexOf(this);
  59374. if (index >= 0) {
  59375. scene._proceduralTextures.splice(index, 1);
  59376. }
  59377. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  59378. if (vertexBuffer) {
  59379. vertexBuffer.dispose();
  59380. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  59381. }
  59382. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  59383. this._indexBuffer = null;
  59384. }
  59385. _super.prototype.dispose.call(this);
  59386. };
  59387. return ProceduralTexture;
  59388. }(BABYLON.Texture));
  59389. BABYLON.ProceduralTexture = ProceduralTexture;
  59390. })(BABYLON || (BABYLON = {}));
  59391. //# sourceMappingURL=babylon.proceduralTexture.js.map
  59392. var BABYLON;
  59393. (function (BABYLON) {
  59394. var CustomProceduralTexture = /** @class */ (function (_super) {
  59395. __extends(CustomProceduralTexture, _super);
  59396. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  59397. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  59398. _this._animate = true;
  59399. _this._time = 0;
  59400. _this._texturePath = texturePath;
  59401. //Try to load json
  59402. _this.loadJson(texturePath);
  59403. _this.refreshRate = 1;
  59404. return _this;
  59405. }
  59406. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  59407. var _this = this;
  59408. var noConfigFile = function () {
  59409. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  59410. try {
  59411. _this.setFragment(_this._texturePath);
  59412. }
  59413. catch (ex) {
  59414. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  59415. }
  59416. };
  59417. var configFileUrl = jsonUrl + "/config.json";
  59418. var xhr = new XMLHttpRequest();
  59419. xhr.open("GET", configFileUrl, true);
  59420. xhr.addEventListener("load", function () {
  59421. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  59422. try {
  59423. _this._config = JSON.parse(xhr.response);
  59424. _this.updateShaderUniforms();
  59425. _this.updateTextures();
  59426. _this.setFragment(_this._texturePath + "/custom");
  59427. _this._animate = _this._config.animate;
  59428. _this.refreshRate = _this._config.refreshrate;
  59429. }
  59430. catch (ex) {
  59431. noConfigFile();
  59432. }
  59433. }
  59434. else {
  59435. noConfigFile();
  59436. }
  59437. }, false);
  59438. xhr.addEventListener("error", function () {
  59439. noConfigFile();
  59440. }, false);
  59441. try {
  59442. xhr.send();
  59443. }
  59444. catch (ex) {
  59445. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  59446. }
  59447. };
  59448. CustomProceduralTexture.prototype.isReady = function () {
  59449. if (!_super.prototype.isReady.call(this)) {
  59450. return false;
  59451. }
  59452. for (var name in this._textures) {
  59453. var texture = this._textures[name];
  59454. if (!texture.isReady()) {
  59455. return false;
  59456. }
  59457. }
  59458. return true;
  59459. };
  59460. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  59461. var scene = this.getScene();
  59462. if (this._animate && scene) {
  59463. this._time += scene.getAnimationRatio() * 0.03;
  59464. this.updateShaderUniforms();
  59465. }
  59466. _super.prototype.render.call(this, useCameraPostProcess);
  59467. };
  59468. CustomProceduralTexture.prototype.updateTextures = function () {
  59469. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  59470. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  59471. }
  59472. };
  59473. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  59474. if (this._config) {
  59475. for (var j = 0; j < this._config.uniforms.length; j++) {
  59476. var uniform = this._config.uniforms[j];
  59477. switch (uniform.type) {
  59478. case "float":
  59479. this.setFloat(uniform.name, uniform.value);
  59480. break;
  59481. case "color3":
  59482. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  59483. break;
  59484. case "color4":
  59485. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  59486. break;
  59487. case "vector2":
  59488. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  59489. break;
  59490. case "vector3":
  59491. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  59492. break;
  59493. }
  59494. }
  59495. }
  59496. this.setFloat("time", this._time);
  59497. };
  59498. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  59499. get: function () {
  59500. return this._animate;
  59501. },
  59502. set: function (value) {
  59503. this._animate = value;
  59504. },
  59505. enumerable: true,
  59506. configurable: true
  59507. });
  59508. return CustomProceduralTexture;
  59509. }(BABYLON.ProceduralTexture));
  59510. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  59511. })(BABYLON || (BABYLON = {}));
  59512. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  59513. var BABYLON;
  59514. (function (BABYLON) {
  59515. var FreeCameraGamepadInput = /** @class */ (function () {
  59516. function FreeCameraGamepadInput() {
  59517. this.gamepadAngularSensibility = 200;
  59518. this.gamepadMoveSensibility = 40;
  59519. // private members
  59520. this._cameraTransform = BABYLON.Matrix.Identity();
  59521. this._deltaTransform = BABYLON.Vector3.Zero();
  59522. this._vector3 = BABYLON.Vector3.Zero();
  59523. this._vector2 = BABYLON.Vector2.Zero();
  59524. }
  59525. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  59526. var _this = this;
  59527. var manager = this.camera.getScene().gamepadManager;
  59528. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  59529. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  59530. // prioritize XBOX gamepads.
  59531. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  59532. _this.gamepad = gamepad;
  59533. }
  59534. }
  59535. });
  59536. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  59537. if (_this.gamepad === gamepad) {
  59538. _this.gamepad = null;
  59539. }
  59540. });
  59541. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  59542. };
  59543. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  59544. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  59545. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  59546. this.gamepad = null;
  59547. };
  59548. FreeCameraGamepadInput.prototype.checkInputs = function () {
  59549. if (this.gamepad && this.gamepad.leftStick) {
  59550. var camera = this.camera;
  59551. var LSValues = this.gamepad.leftStick;
  59552. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  59553. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  59554. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  59555. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  59556. var RSValues = this.gamepad.rightStick;
  59557. if (RSValues) {
  59558. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  59559. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  59560. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  59561. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  59562. }
  59563. else {
  59564. RSValues = { x: 0, y: 0 };
  59565. }
  59566. if (!camera.rotationQuaternion) {
  59567. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  59568. }
  59569. else {
  59570. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  59571. }
  59572. var speed = camera._computeLocalCameraSpeed() * 50.0;
  59573. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  59574. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  59575. camera.cameraDirection.addInPlace(this._deltaTransform);
  59576. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  59577. camera.cameraRotation.addInPlace(this._vector2);
  59578. }
  59579. };
  59580. FreeCameraGamepadInput.prototype.getClassName = function () {
  59581. return "FreeCameraGamepadInput";
  59582. };
  59583. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  59584. return "gamepad";
  59585. };
  59586. __decorate([
  59587. BABYLON.serialize()
  59588. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  59589. __decorate([
  59590. BABYLON.serialize()
  59591. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  59592. return FreeCameraGamepadInput;
  59593. }());
  59594. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  59595. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  59596. })(BABYLON || (BABYLON = {}));
  59597. //# sourceMappingURL=babylon.freeCameraGamepadInput.js.map
  59598. var BABYLON;
  59599. (function (BABYLON) {
  59600. var ArcRotateCameraGamepadInput = /** @class */ (function () {
  59601. function ArcRotateCameraGamepadInput() {
  59602. this.gamepadRotationSensibility = 80;
  59603. this.gamepadMoveSensibility = 40;
  59604. }
  59605. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  59606. var _this = this;
  59607. var manager = this.camera.getScene().gamepadManager;
  59608. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  59609. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  59610. // prioritize XBOX gamepads.
  59611. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  59612. _this.gamepad = gamepad;
  59613. }
  59614. }
  59615. });
  59616. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  59617. if (_this.gamepad === gamepad) {
  59618. _this.gamepad = null;
  59619. }
  59620. });
  59621. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  59622. };
  59623. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  59624. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  59625. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  59626. this.gamepad = null;
  59627. };
  59628. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  59629. if (this.gamepad) {
  59630. var camera = this.camera;
  59631. var RSValues = this.gamepad.rightStick;
  59632. if (RSValues) {
  59633. if (RSValues.x != 0) {
  59634. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  59635. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  59636. camera.inertialAlphaOffset += normalizedRX;
  59637. }
  59638. }
  59639. if (RSValues.y != 0) {
  59640. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  59641. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  59642. camera.inertialBetaOffset += normalizedRY;
  59643. }
  59644. }
  59645. }
  59646. var LSValues = this.gamepad.leftStick;
  59647. if (LSValues && LSValues.y != 0) {
  59648. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  59649. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  59650. this.camera.inertialRadiusOffset -= normalizedLY;
  59651. }
  59652. }
  59653. }
  59654. };
  59655. ArcRotateCameraGamepadInput.prototype.getClassName = function () {
  59656. return "ArcRotateCameraGamepadInput";
  59657. };
  59658. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  59659. return "gamepad";
  59660. };
  59661. __decorate([
  59662. BABYLON.serialize()
  59663. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  59664. __decorate([
  59665. BABYLON.serialize()
  59666. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  59667. return ArcRotateCameraGamepadInput;
  59668. }());
  59669. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  59670. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  59671. })(BABYLON || (BABYLON = {}));
  59672. //# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map
  59673. var BABYLON;
  59674. (function (BABYLON) {
  59675. var GamepadManager = /** @class */ (function () {
  59676. function GamepadManager(_scene) {
  59677. var _this = this;
  59678. this._scene = _scene;
  59679. this._babylonGamepads = [];
  59680. this._oneGamepadConnected = false;
  59681. this._isMonitoring = false;
  59682. this.onGamepadDisconnectedObservable = new BABYLON.Observable();
  59683. if (!BABYLON.Tools.IsWindowObjectExist()) {
  59684. this._gamepadEventSupported = false;
  59685. }
  59686. else {
  59687. this._gamepadEventSupported = 'GamepadEvent' in window;
  59688. this._gamepadSupport = (navigator.getGamepads ||
  59689. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  59690. }
  59691. this.onGamepadConnectedObservable = new BABYLON.Observable(function (observer) {
  59692. // This will be used to raise the onGamepadConnected for all gamepads ALREADY connected
  59693. for (var i in _this._babylonGamepads) {
  59694. var gamepad = _this._babylonGamepads[i];
  59695. if (gamepad && gamepad._isConnected) {
  59696. _this.onGamepadConnectedObservable.notifyObserver(observer, gamepad);
  59697. }
  59698. }
  59699. });
  59700. this._onGamepadConnectedEvent = function (evt) {
  59701. var gamepad = evt.gamepad;
  59702. if (gamepad.index in _this._babylonGamepads) {
  59703. if (_this._babylonGamepads[gamepad.index].isConnected) {
  59704. return;
  59705. }
  59706. }
  59707. var newGamepad;
  59708. if (_this._babylonGamepads[gamepad.index]) {
  59709. newGamepad = _this._babylonGamepads[gamepad.index];
  59710. newGamepad.browserGamepad = gamepad;
  59711. newGamepad._isConnected = true;
  59712. }
  59713. else {
  59714. newGamepad = _this._addNewGamepad(gamepad);
  59715. }
  59716. _this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  59717. _this._startMonitoringGamepads();
  59718. };
  59719. this._onGamepadDisconnectedEvent = function (evt) {
  59720. var gamepad = evt.gamepad;
  59721. // Remove the gamepad from the list of gamepads to monitor.
  59722. for (var i in _this._babylonGamepads) {
  59723. if (_this._babylonGamepads[i].index === gamepad.index) {
  59724. var disconnectedGamepad = _this._babylonGamepads[i];
  59725. disconnectedGamepad._isConnected = false;
  59726. _this.onGamepadDisconnectedObservable.notifyObservers(disconnectedGamepad);
  59727. break;
  59728. }
  59729. }
  59730. };
  59731. if (this._gamepadSupport) {
  59732. //first add already-connected gamepads
  59733. this._updateGamepadObjects();
  59734. if (this._babylonGamepads.length) {
  59735. this._startMonitoringGamepads();
  59736. }
  59737. // Checking if the gamepad connected event is supported (like in Firefox)
  59738. if (this._gamepadEventSupported) {
  59739. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  59740. window.addEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent, false);
  59741. }
  59742. else {
  59743. this._startMonitoringGamepads();
  59744. }
  59745. }
  59746. }
  59747. Object.defineProperty(GamepadManager.prototype, "gamepads", {
  59748. get: function () {
  59749. return this._babylonGamepads;
  59750. },
  59751. enumerable: true,
  59752. configurable: true
  59753. });
  59754. GamepadManager.prototype.getGamepadByType = function (type) {
  59755. if (type === void 0) { type = BABYLON.Gamepad.XBOX; }
  59756. for (var _i = 0, _a = this._babylonGamepads; _i < _a.length; _i++) {
  59757. var gamepad = _a[_i];
  59758. if (gamepad && gamepad.type === type) {
  59759. return gamepad;
  59760. }
  59761. }
  59762. return null;
  59763. };
  59764. GamepadManager.prototype.dispose = function () {
  59765. if (this._gamepadEventSupported) {
  59766. if (this._onGamepadConnectedEvent) {
  59767. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent);
  59768. }
  59769. if (this._onGamepadDisconnectedEvent) {
  59770. window.removeEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent);
  59771. }
  59772. this._onGamepadConnectedEvent = null;
  59773. this._onGamepadDisconnectedEvent = null;
  59774. }
  59775. this._babylonGamepads.forEach(function (gamepad) {
  59776. gamepad.dispose();
  59777. });
  59778. this.onGamepadConnectedObservable.clear();
  59779. this.onGamepadDisconnectedObservable.clear();
  59780. this._oneGamepadConnected = false;
  59781. this._stopMonitoringGamepads();
  59782. this._babylonGamepads = [];
  59783. };
  59784. GamepadManager.prototype._addNewGamepad = function (gamepad) {
  59785. if (!this._oneGamepadConnected) {
  59786. this._oneGamepadConnected = true;
  59787. }
  59788. var newGamepad;
  59789. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  59790. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  59791. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  59792. }
  59793. else if (gamepad.pose) {
  59794. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  59795. }
  59796. else {
  59797. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  59798. }
  59799. this._babylonGamepads[newGamepad.index] = newGamepad;
  59800. return newGamepad;
  59801. };
  59802. GamepadManager.prototype._startMonitoringGamepads = function () {
  59803. if (!this._isMonitoring) {
  59804. this._isMonitoring = true;
  59805. //back-comp
  59806. if (!this._scene) {
  59807. this._checkGamepadsStatus();
  59808. }
  59809. }
  59810. };
  59811. GamepadManager.prototype._stopMonitoringGamepads = function () {
  59812. this._isMonitoring = false;
  59813. };
  59814. GamepadManager.prototype._checkGamepadsStatus = function () {
  59815. var _this = this;
  59816. // Hack to be compatible Chrome
  59817. this._updateGamepadObjects();
  59818. for (var i in this._babylonGamepads) {
  59819. var gamepad = this._babylonGamepads[i];
  59820. if (!gamepad || !gamepad.isConnected) {
  59821. continue;
  59822. }
  59823. gamepad.update();
  59824. }
  59825. if (this._isMonitoring && !this._scene) {
  59826. BABYLON.Tools.QueueNewFrame(function () { _this._checkGamepadsStatus(); });
  59827. }
  59828. };
  59829. // This function is called only on Chrome, which does not properly support
  59830. // connection/disconnection events and forces you to recopy again the gamepad object
  59831. GamepadManager.prototype._updateGamepadObjects = function () {
  59832. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  59833. for (var i = 0; i < gamepads.length; i++) {
  59834. if (gamepads[i]) {
  59835. if (!this._babylonGamepads[gamepads[i].index]) {
  59836. var newGamepad = this._addNewGamepad(gamepads[i]);
  59837. this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  59838. }
  59839. else {
  59840. // Forced to copy again this object for Chrome for unknown reason
  59841. this._babylonGamepads[i].browserGamepad = gamepads[i];
  59842. if (!this._babylonGamepads[i].isConnected) {
  59843. this._babylonGamepads[i]._isConnected = true;
  59844. this.onGamepadConnectedObservable.notifyObservers(this._babylonGamepads[i]);
  59845. }
  59846. }
  59847. }
  59848. }
  59849. };
  59850. return GamepadManager;
  59851. }());
  59852. BABYLON.GamepadManager = GamepadManager;
  59853. })(BABYLON || (BABYLON = {}));
  59854. //# sourceMappingURL=babylon.gamepadManager.js.map
  59855. var BABYLON;
  59856. (function (BABYLON) {
  59857. var StickValues = /** @class */ (function () {
  59858. function StickValues(x, y) {
  59859. this.x = x;
  59860. this.y = y;
  59861. }
  59862. return StickValues;
  59863. }());
  59864. BABYLON.StickValues = StickValues;
  59865. var Gamepad = /** @class */ (function () {
  59866. function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  59867. if (leftStickX === void 0) { leftStickX = 0; }
  59868. if (leftStickY === void 0) { leftStickY = 1; }
  59869. if (rightStickX === void 0) { rightStickX = 2; }
  59870. if (rightStickY === void 0) { rightStickY = 3; }
  59871. this.id = id;
  59872. this.index = index;
  59873. this.browserGamepad = browserGamepad;
  59874. this._isConnected = true;
  59875. this._invertLeftStickY = false;
  59876. this.type = Gamepad.GAMEPAD;
  59877. this._leftStickAxisX = leftStickX;
  59878. this._leftStickAxisY = leftStickY;
  59879. this._rightStickAxisX = rightStickX;
  59880. this._rightStickAxisY = rightStickY;
  59881. if (this.browserGamepad.axes.length >= 2) {
  59882. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  59883. }
  59884. if (this.browserGamepad.axes.length >= 4) {
  59885. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  59886. }
  59887. }
  59888. Object.defineProperty(Gamepad.prototype, "isConnected", {
  59889. get: function () {
  59890. return this._isConnected;
  59891. },
  59892. enumerable: true,
  59893. configurable: true
  59894. });
  59895. Gamepad.prototype.onleftstickchanged = function (callback) {
  59896. this._onleftstickchanged = callback;
  59897. };
  59898. Gamepad.prototype.onrightstickchanged = function (callback) {
  59899. this._onrightstickchanged = callback;
  59900. };
  59901. Object.defineProperty(Gamepad.prototype, "leftStick", {
  59902. get: function () {
  59903. return this._leftStick;
  59904. },
  59905. set: function (newValues) {
  59906. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  59907. this._onleftstickchanged(newValues);
  59908. }
  59909. this._leftStick = newValues;
  59910. },
  59911. enumerable: true,
  59912. configurable: true
  59913. });
  59914. Object.defineProperty(Gamepad.prototype, "rightStick", {
  59915. get: function () {
  59916. return this._rightStick;
  59917. },
  59918. set: function (newValues) {
  59919. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  59920. this._onrightstickchanged(newValues);
  59921. }
  59922. this._rightStick = newValues;
  59923. },
  59924. enumerable: true,
  59925. configurable: true
  59926. });
  59927. Gamepad.prototype.update = function () {
  59928. if (this._leftStick) {
  59929. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  59930. if (this._invertLeftStickY) {
  59931. this.leftStick.y *= -1;
  59932. }
  59933. }
  59934. if (this._rightStick) {
  59935. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  59936. }
  59937. };
  59938. Gamepad.prototype.dispose = function () {
  59939. };
  59940. Gamepad.GAMEPAD = 0;
  59941. Gamepad.GENERIC = 1;
  59942. Gamepad.XBOX = 2;
  59943. Gamepad.POSE_ENABLED = 3;
  59944. return Gamepad;
  59945. }());
  59946. BABYLON.Gamepad = Gamepad;
  59947. var GenericPad = /** @class */ (function (_super) {
  59948. __extends(GenericPad, _super);
  59949. function GenericPad(id, index, browserGamepad) {
  59950. var _this = _super.call(this, id, index, browserGamepad) || this;
  59951. _this.onButtonDownObservable = new BABYLON.Observable();
  59952. _this.onButtonUpObservable = new BABYLON.Observable();
  59953. _this.type = Gamepad.GENERIC;
  59954. _this._buttons = new Array(browserGamepad.buttons.length);
  59955. return _this;
  59956. }
  59957. GenericPad.prototype.onbuttondown = function (callback) {
  59958. this._onbuttondown = callback;
  59959. };
  59960. GenericPad.prototype.onbuttonup = function (callback) {
  59961. this._onbuttonup = callback;
  59962. };
  59963. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  59964. if (newValue !== currentValue) {
  59965. if (newValue === 1) {
  59966. if (this._onbuttondown) {
  59967. this._onbuttondown(buttonIndex);
  59968. }
  59969. this.onButtonDownObservable.notifyObservers(buttonIndex);
  59970. }
  59971. if (newValue === 0) {
  59972. if (this._onbuttonup) {
  59973. this._onbuttonup(buttonIndex);
  59974. }
  59975. this.onButtonUpObservable.notifyObservers(buttonIndex);
  59976. }
  59977. }
  59978. return newValue;
  59979. };
  59980. GenericPad.prototype.update = function () {
  59981. _super.prototype.update.call(this);
  59982. for (var index = 0; index < this._buttons.length; index++) {
  59983. this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index);
  59984. }
  59985. };
  59986. GenericPad.prototype.dispose = function () {
  59987. _super.prototype.dispose.call(this);
  59988. this.onButtonDownObservable.clear();
  59989. this.onButtonUpObservable.clear();
  59990. };
  59991. return GenericPad;
  59992. }(Gamepad));
  59993. BABYLON.GenericPad = GenericPad;
  59994. })(BABYLON || (BABYLON = {}));
  59995. //# sourceMappingURL=babylon.gamepad.js.map
  59996. var BABYLON;
  59997. (function (BABYLON) {
  59998. var Xbox360Button;
  59999. (function (Xbox360Button) {
  60000. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  60001. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  60002. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  60003. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  60004. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  60005. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  60006. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  60007. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  60008. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  60009. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  60010. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  60011. var Xbox360Dpad;
  60012. (function (Xbox360Dpad) {
  60013. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  60014. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  60015. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  60016. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  60017. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  60018. var Xbox360Pad = /** @class */ (function (_super) {
  60019. __extends(Xbox360Pad, _super);
  60020. function Xbox360Pad(id, index, gamepad, xboxOne) {
  60021. if (xboxOne === void 0) { xboxOne = false; }
  60022. var _this = _super.call(this, id, index, gamepad, 0, 1, 2, 3) || this;
  60023. _this._leftTrigger = 0;
  60024. _this._rightTrigger = 0;
  60025. _this.onButtonDownObservable = new BABYLON.Observable();
  60026. _this.onButtonUpObservable = new BABYLON.Observable();
  60027. _this.onPadDownObservable = new BABYLON.Observable();
  60028. _this.onPadUpObservable = new BABYLON.Observable();
  60029. _this._buttonA = 0;
  60030. _this._buttonB = 0;
  60031. _this._buttonX = 0;
  60032. _this._buttonY = 0;
  60033. _this._buttonBack = 0;
  60034. _this._buttonStart = 0;
  60035. _this._buttonLB = 0;
  60036. _this._buttonRB = 0;
  60037. _this._buttonLeftStick = 0;
  60038. _this._buttonRightStick = 0;
  60039. _this._dPadUp = 0;
  60040. _this._dPadDown = 0;
  60041. _this._dPadLeft = 0;
  60042. _this._dPadRight = 0;
  60043. _this._isXboxOnePad = false;
  60044. _this.type = BABYLON.Gamepad.XBOX;
  60045. _this._isXboxOnePad = xboxOne;
  60046. return _this;
  60047. }
  60048. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  60049. this._onlefttriggerchanged = callback;
  60050. };
  60051. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  60052. this._onrighttriggerchanged = callback;
  60053. };
  60054. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  60055. get: function () {
  60056. return this._leftTrigger;
  60057. },
  60058. set: function (newValue) {
  60059. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  60060. this._onlefttriggerchanged(newValue);
  60061. }
  60062. this._leftTrigger = newValue;
  60063. },
  60064. enumerable: true,
  60065. configurable: true
  60066. });
  60067. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  60068. get: function () {
  60069. return this._rightTrigger;
  60070. },
  60071. set: function (newValue) {
  60072. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  60073. this._onrighttriggerchanged(newValue);
  60074. }
  60075. this._rightTrigger = newValue;
  60076. },
  60077. enumerable: true,
  60078. configurable: true
  60079. });
  60080. Xbox360Pad.prototype.onbuttondown = function (callback) {
  60081. this._onbuttondown = callback;
  60082. };
  60083. Xbox360Pad.prototype.onbuttonup = function (callback) {
  60084. this._onbuttonup = callback;
  60085. };
  60086. Xbox360Pad.prototype.ondpaddown = function (callback) {
  60087. this._ondpaddown = callback;
  60088. };
  60089. Xbox360Pad.prototype.ondpadup = function (callback) {
  60090. this._ondpadup = callback;
  60091. };
  60092. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  60093. if (newValue !== currentValue) {
  60094. if (newValue === 1) {
  60095. if (this._onbuttondown) {
  60096. this._onbuttondown(buttonType);
  60097. }
  60098. this.onButtonDownObservable.notifyObservers(buttonType);
  60099. }
  60100. if (newValue === 0) {
  60101. if (this._onbuttonup) {
  60102. this._onbuttonup(buttonType);
  60103. }
  60104. this.onButtonUpObservable.notifyObservers(buttonType);
  60105. }
  60106. }
  60107. return newValue;
  60108. };
  60109. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  60110. if (newValue !== currentValue) {
  60111. if (newValue === 1) {
  60112. if (this._ondpaddown) {
  60113. this._ondpaddown(buttonType);
  60114. }
  60115. this.onPadDownObservable.notifyObservers(buttonType);
  60116. }
  60117. if (newValue === 0) {
  60118. if (this._ondpadup) {
  60119. this._ondpadup(buttonType);
  60120. }
  60121. this.onPadUpObservable.notifyObservers(buttonType);
  60122. }
  60123. }
  60124. return newValue;
  60125. };
  60126. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  60127. get: function () {
  60128. return this._buttonA;
  60129. },
  60130. set: function (value) {
  60131. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  60132. },
  60133. enumerable: true,
  60134. configurable: true
  60135. });
  60136. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  60137. get: function () {
  60138. return this._buttonB;
  60139. },
  60140. set: function (value) {
  60141. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  60142. },
  60143. enumerable: true,
  60144. configurable: true
  60145. });
  60146. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  60147. get: function () {
  60148. return this._buttonX;
  60149. },
  60150. set: function (value) {
  60151. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  60152. },
  60153. enumerable: true,
  60154. configurable: true
  60155. });
  60156. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  60157. get: function () {
  60158. return this._buttonY;
  60159. },
  60160. set: function (value) {
  60161. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  60162. },
  60163. enumerable: true,
  60164. configurable: true
  60165. });
  60166. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  60167. get: function () {
  60168. return this._buttonStart;
  60169. },
  60170. set: function (value) {
  60171. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  60172. },
  60173. enumerable: true,
  60174. configurable: true
  60175. });
  60176. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  60177. get: function () {
  60178. return this._buttonBack;
  60179. },
  60180. set: function (value) {
  60181. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  60182. },
  60183. enumerable: true,
  60184. configurable: true
  60185. });
  60186. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  60187. get: function () {
  60188. return this._buttonLB;
  60189. },
  60190. set: function (value) {
  60191. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  60192. },
  60193. enumerable: true,
  60194. configurable: true
  60195. });
  60196. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  60197. get: function () {
  60198. return this._buttonRB;
  60199. },
  60200. set: function (value) {
  60201. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  60202. },
  60203. enumerable: true,
  60204. configurable: true
  60205. });
  60206. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  60207. get: function () {
  60208. return this._buttonLeftStick;
  60209. },
  60210. set: function (value) {
  60211. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  60212. },
  60213. enumerable: true,
  60214. configurable: true
  60215. });
  60216. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  60217. get: function () {
  60218. return this._buttonRightStick;
  60219. },
  60220. set: function (value) {
  60221. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  60222. },
  60223. enumerable: true,
  60224. configurable: true
  60225. });
  60226. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  60227. get: function () {
  60228. return this._dPadUp;
  60229. },
  60230. set: function (value) {
  60231. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  60232. },
  60233. enumerable: true,
  60234. configurable: true
  60235. });
  60236. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  60237. get: function () {
  60238. return this._dPadDown;
  60239. },
  60240. set: function (value) {
  60241. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  60242. },
  60243. enumerable: true,
  60244. configurable: true
  60245. });
  60246. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  60247. get: function () {
  60248. return this._dPadLeft;
  60249. },
  60250. set: function (value) {
  60251. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  60252. },
  60253. enumerable: true,
  60254. configurable: true
  60255. });
  60256. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  60257. get: function () {
  60258. return this._dPadRight;
  60259. },
  60260. set: function (value) {
  60261. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  60262. },
  60263. enumerable: true,
  60264. configurable: true
  60265. });
  60266. Xbox360Pad.prototype.update = function () {
  60267. _super.prototype.update.call(this);
  60268. if (this._isXboxOnePad) {
  60269. this.buttonA = this.browserGamepad.buttons[0].value;
  60270. this.buttonB = this.browserGamepad.buttons[1].value;
  60271. this.buttonX = this.browserGamepad.buttons[2].value;
  60272. this.buttonY = this.browserGamepad.buttons[3].value;
  60273. this.buttonLB = this.browserGamepad.buttons[4].value;
  60274. this.buttonRB = this.browserGamepad.buttons[5].value;
  60275. this.leftTrigger = this.browserGamepad.axes[2];
  60276. this.rightTrigger = this.browserGamepad.axes[5];
  60277. this.buttonBack = this.browserGamepad.buttons[9].value;
  60278. this.buttonStart = this.browserGamepad.buttons[8].value;
  60279. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  60280. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  60281. this.dPadUp = this.browserGamepad.buttons[11].value;
  60282. this.dPadDown = this.browserGamepad.buttons[12].value;
  60283. this.dPadLeft = this.browserGamepad.buttons[13].value;
  60284. this.dPadRight = this.browserGamepad.buttons[14].value;
  60285. }
  60286. else {
  60287. this.buttonA = this.browserGamepad.buttons[0].value;
  60288. this.buttonB = this.browserGamepad.buttons[1].value;
  60289. this.buttonX = this.browserGamepad.buttons[2].value;
  60290. this.buttonY = this.browserGamepad.buttons[3].value;
  60291. this.buttonLB = this.browserGamepad.buttons[4].value;
  60292. this.buttonRB = this.browserGamepad.buttons[5].value;
  60293. this.leftTrigger = this.browserGamepad.buttons[6].value;
  60294. this.rightTrigger = this.browserGamepad.buttons[7].value;
  60295. this.buttonBack = this.browserGamepad.buttons[8].value;
  60296. this.buttonStart = this.browserGamepad.buttons[9].value;
  60297. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  60298. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  60299. this.dPadUp = this.browserGamepad.buttons[12].value;
  60300. this.dPadDown = this.browserGamepad.buttons[13].value;
  60301. this.dPadLeft = this.browserGamepad.buttons[14].value;
  60302. this.dPadRight = this.browserGamepad.buttons[15].value;
  60303. }
  60304. };
  60305. Xbox360Pad.prototype.dispose = function () {
  60306. _super.prototype.dispose.call(this);
  60307. this.onButtonDownObservable.clear();
  60308. this.onButtonUpObservable.clear();
  60309. this.onPadDownObservable.clear();
  60310. this.onPadUpObservable.clear();
  60311. };
  60312. return Xbox360Pad;
  60313. }(BABYLON.Gamepad));
  60314. BABYLON.Xbox360Pad = Xbox360Pad;
  60315. })(BABYLON || (BABYLON = {}));
  60316. //# sourceMappingURL=babylon.xboxGamepad.js.map
  60317. var BABYLON;
  60318. (function (BABYLON) {
  60319. var PoseEnabledControllerType;
  60320. (function (PoseEnabledControllerType) {
  60321. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  60322. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  60323. PoseEnabledControllerType[PoseEnabledControllerType["WINDOWS"] = 2] = "WINDOWS";
  60324. PoseEnabledControllerType[PoseEnabledControllerType["GEAR_VR"] = 3] = "GEAR_VR";
  60325. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 4] = "GENERIC";
  60326. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  60327. var PoseEnabledControllerHelper = /** @class */ (function () {
  60328. function PoseEnabledControllerHelper() {
  60329. }
  60330. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  60331. // Oculus Touch
  60332. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  60333. return new BABYLON.OculusTouchController(vrGamepad);
  60334. }
  60335. else if (vrGamepad.id.indexOf(BABYLON.WindowsMotionController.GAMEPAD_ID_PREFIX) === 0) {
  60336. return new BABYLON.WindowsMotionController(vrGamepad);
  60337. }
  60338. else if (vrGamepad.id.toLowerCase().indexOf('openvr') !== -1) {
  60339. return new BABYLON.ViveController(vrGamepad);
  60340. }
  60341. else if (vrGamepad.id.indexOf(BABYLON.GearVRController.GAMEPAD_ID_PREFIX) === 0) {
  60342. return new BABYLON.GearVRController(vrGamepad);
  60343. }
  60344. else {
  60345. return new BABYLON.GenericController(vrGamepad);
  60346. }
  60347. };
  60348. return PoseEnabledControllerHelper;
  60349. }());
  60350. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  60351. var PoseEnabledController = /** @class */ (function (_super) {
  60352. __extends(PoseEnabledController, _super);
  60353. function PoseEnabledController(browserGamepad) {
  60354. var _this = _super.call(this, browserGamepad.id, browserGamepad.index, browserGamepad) || this;
  60355. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  60356. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  60357. _this._deviceRoomRotationQuaternion = new BABYLON.Quaternion();
  60358. // Represents device position and rotation in babylon space
  60359. _this.devicePosition = BABYLON.Vector3.Zero();
  60360. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  60361. _this.deviceScaleFactor = 1;
  60362. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  60363. _this._deviceToWorld = BABYLON.Matrix.Identity();
  60364. _this._workingMatrix = BABYLON.Matrix.Identity();
  60365. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  60366. _this.controllerType = PoseEnabledControllerType.GENERIC;
  60367. _this.position = BABYLON.Vector3.Zero();
  60368. _this.rotationQuaternion = new BABYLON.Quaternion();
  60369. _this._calculatedPosition = BABYLON.Vector3.Zero();
  60370. _this._calculatedRotation = new BABYLON.Quaternion();
  60371. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  60372. return _this;
  60373. }
  60374. PoseEnabledController.prototype.update = function () {
  60375. _super.prototype.update.call(this);
  60376. var pose = this.browserGamepad.pose;
  60377. this.updateFromDevice(pose);
  60378. BABYLON.Vector3.TransformCoordinatesToRef(this._calculatedPosition, this._deviceToWorld, this.devicePosition);
  60379. this._deviceToWorld.getRotationMatrixToRef(this._workingMatrix);
  60380. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  60381. this.deviceRotationQuaternion.multiplyInPlace(this._calculatedRotation);
  60382. if (this._mesh) {
  60383. this._mesh.position.copyFrom(this.devicePosition);
  60384. if (this._mesh.rotationQuaternion) {
  60385. this._mesh.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  60386. }
  60387. }
  60388. };
  60389. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  60390. if (poseData) {
  60391. this.rawPose = poseData;
  60392. if (poseData.position) {
  60393. this._deviceRoomPosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  60394. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  60395. this._deviceRoomPosition.z *= -1;
  60396. }
  60397. this._deviceRoomPosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  60398. this._calculatedPosition.addInPlace(this.position);
  60399. }
  60400. var pose = this.rawPose;
  60401. if (poseData.orientation && pose.orientation) {
  60402. this._deviceRoomRotationQuaternion.copyFromFloats(pose.orientation[0], pose.orientation[1], -pose.orientation[2], -pose.orientation[3]);
  60403. if (this._mesh) {
  60404. if (this._mesh.getScene().useRightHandedSystem) {
  60405. this._deviceRoomRotationQuaternion.z *= -1;
  60406. this._deviceRoomRotationQuaternion.w *= -1;
  60407. }
  60408. else {
  60409. this._deviceRoomRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this._deviceRoomRotationQuaternion);
  60410. }
  60411. }
  60412. // if the camera is set, rotate to the camera's rotation
  60413. this._deviceRoomRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  60414. }
  60415. }
  60416. };
  60417. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  60418. if (this._mesh) {
  60419. this._mesh.parent = null;
  60420. }
  60421. this._mesh = mesh;
  60422. if (this._poseControlledCamera) {
  60423. this._mesh.parent = this._poseControlledCamera;
  60424. }
  60425. if (!this._mesh.rotationQuaternion) {
  60426. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  60427. }
  60428. };
  60429. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  60430. this._poseControlledCamera = camera;
  60431. if (this._mesh) {
  60432. this._mesh.parent = this._poseControlledCamera;
  60433. }
  60434. };
  60435. PoseEnabledController.prototype.dispose = function () {
  60436. if (this._mesh) {
  60437. this._mesh.dispose();
  60438. }
  60439. this._mesh = null;
  60440. _super.prototype.dispose.call(this);
  60441. };
  60442. Object.defineProperty(PoseEnabledController.prototype, "mesh", {
  60443. get: function () {
  60444. return this._mesh;
  60445. },
  60446. enumerable: true,
  60447. configurable: true
  60448. });
  60449. PoseEnabledController.prototype.getForwardRay = function (length) {
  60450. if (length === void 0) { length = 100; }
  60451. if (!this.mesh) {
  60452. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, 1), length);
  60453. }
  60454. var m = this.mesh.getWorldMatrix();
  60455. var origin = m.getTranslation();
  60456. var forward = new BABYLON.Vector3(0, 0, -1);
  60457. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  60458. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  60459. return new BABYLON.Ray(origin, direction, length);
  60460. };
  60461. return PoseEnabledController;
  60462. }(BABYLON.Gamepad));
  60463. BABYLON.PoseEnabledController = PoseEnabledController;
  60464. })(BABYLON || (BABYLON = {}));
  60465. //# sourceMappingURL=babylon.poseEnabledController.js.map
  60466. var BABYLON;
  60467. (function (BABYLON) {
  60468. var WebVRController = /** @class */ (function (_super) {
  60469. __extends(WebVRController, _super);
  60470. function WebVRController(vrGamepad) {
  60471. var _this = _super.call(this, vrGamepad) || this;
  60472. // Observables
  60473. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  60474. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  60475. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  60476. _this.onPadStateChangedObservable = new BABYLON.Observable();
  60477. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  60478. _this.pad = { x: 0, y: 0 };
  60479. // avoid GC, store state in a tmp object
  60480. _this._changes = {
  60481. pressChanged: false,
  60482. touchChanged: false,
  60483. valueChanged: false,
  60484. changed: false
  60485. };
  60486. _this._buttons = new Array(vrGamepad.buttons.length);
  60487. _this.hand = vrGamepad.hand;
  60488. return _this;
  60489. }
  60490. WebVRController.prototype.onButtonStateChange = function (callback) {
  60491. this._onButtonStateChange = callback;
  60492. };
  60493. Object.defineProperty(WebVRController.prototype, "defaultModel", {
  60494. get: function () {
  60495. return this._defaultModel;
  60496. },
  60497. enumerable: true,
  60498. configurable: true
  60499. });
  60500. WebVRController.prototype.update = function () {
  60501. _super.prototype.update.call(this);
  60502. for (var index = 0; index < this._buttons.length; index++) {
  60503. this._setButtonValue(this.browserGamepad.buttons[index], this._buttons[index], index);
  60504. }
  60505. ;
  60506. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  60507. this.pad.x = this.leftStick.x;
  60508. this.pad.y = this.leftStick.y;
  60509. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  60510. }
  60511. };
  60512. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  60513. if (!newState) {
  60514. newState = {
  60515. pressed: false,
  60516. touched: false,
  60517. value: 0
  60518. };
  60519. }
  60520. if (!currentState) {
  60521. this._buttons[buttonIndex] = {
  60522. pressed: newState.pressed,
  60523. touched: newState.touched,
  60524. value: newState.value
  60525. };
  60526. return;
  60527. }
  60528. this._checkChanges(newState, currentState);
  60529. if (this._changes.changed) {
  60530. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  60531. this.handleButtonChange(buttonIndex, newState, this._changes);
  60532. }
  60533. this._buttons[buttonIndex].pressed = newState.pressed;
  60534. this._buttons[buttonIndex].touched = newState.touched;
  60535. // oculus triggers are never 0, thou not touched.
  60536. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  60537. };
  60538. WebVRController.prototype._checkChanges = function (newState, currentState) {
  60539. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  60540. this._changes.touchChanged = newState.touched !== currentState.touched;
  60541. this._changes.valueChanged = newState.value !== currentState.value;
  60542. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  60543. return this._changes;
  60544. };
  60545. WebVRController.prototype.dispose = function () {
  60546. _super.prototype.dispose.call(this);
  60547. this.onTriggerStateChangedObservable.clear();
  60548. this.onMainButtonStateChangedObservable.clear();
  60549. this.onSecondaryButtonStateChangedObservable.clear();
  60550. this.onPadStateChangedObservable.clear();
  60551. this.onPadValuesChangedObservable.clear();
  60552. };
  60553. return WebVRController;
  60554. }(BABYLON.PoseEnabledController));
  60555. BABYLON.WebVRController = WebVRController;
  60556. })(BABYLON || (BABYLON = {}));
  60557. //# sourceMappingURL=babylon.webVRController.js.map
  60558. var BABYLON;
  60559. (function (BABYLON) {
  60560. var OculusTouchController = /** @class */ (function (_super) {
  60561. __extends(OculusTouchController, _super);
  60562. function OculusTouchController(vrGamepad) {
  60563. var _this = _super.call(this, vrGamepad) || this;
  60564. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  60565. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  60566. _this.controllerType = BABYLON.PoseEnabledControllerType.OCULUS;
  60567. return _this;
  60568. }
  60569. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  60570. var _this = this;
  60571. var meshName;
  60572. // Hand
  60573. if (this.hand === 'left') {
  60574. meshName = OculusTouchController.MODEL_LEFT_FILENAME;
  60575. }
  60576. else {
  60577. meshName = OculusTouchController.MODEL_RIGHT_FILENAME;
  60578. }
  60579. BABYLON.SceneLoader.ImportMesh("", OculusTouchController.MODEL_BASE_URL, meshName, scene, function (newMeshes) {
  60580. /*
  60581. Parent Mesh name: oculus_touch_left
  60582. - body
  60583. - trigger
  60584. - thumbstick
  60585. - grip
  60586. - button_y
  60587. - button_x
  60588. - button_enter
  60589. */
  60590. _this._defaultModel = newMeshes[1];
  60591. _this.attachToMesh(_this._defaultModel);
  60592. if (meshLoaded) {
  60593. meshLoaded(_this._defaultModel);
  60594. }
  60595. });
  60596. };
  60597. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  60598. // helper getters for left and right hand.
  60599. get: function () {
  60600. if (this.hand === 'right') {
  60601. return this.onMainButtonStateChangedObservable;
  60602. }
  60603. else {
  60604. throw new Error('No A button on left hand');
  60605. }
  60606. },
  60607. enumerable: true,
  60608. configurable: true
  60609. });
  60610. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  60611. get: function () {
  60612. if (this.hand === 'right') {
  60613. return this.onSecondaryButtonStateChangedObservable;
  60614. }
  60615. else {
  60616. throw new Error('No B button on left hand');
  60617. }
  60618. },
  60619. enumerable: true,
  60620. configurable: true
  60621. });
  60622. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  60623. get: function () {
  60624. if (this.hand === 'left') {
  60625. return this.onMainButtonStateChangedObservable;
  60626. }
  60627. else {
  60628. throw new Error('No X button on right hand');
  60629. }
  60630. },
  60631. enumerable: true,
  60632. configurable: true
  60633. });
  60634. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  60635. get: function () {
  60636. if (this.hand === 'left') {
  60637. return this.onSecondaryButtonStateChangedObservable;
  60638. }
  60639. else {
  60640. throw new Error('No Y button on right hand');
  60641. }
  60642. },
  60643. enumerable: true,
  60644. configurable: true
  60645. });
  60646. /*
  60647. 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  60648. 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  60649. 2) secondary trigger (same)
  60650. 3) A (right) X (left), touch, pressed = value
  60651. 4) B / Y
  60652. 5) thumb rest
  60653. */
  60654. OculusTouchController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  60655. var notifyObject = state; //{ state: state, changes: changes };
  60656. var triggerDirection = this.hand === 'right' ? -1 : 1;
  60657. switch (buttonIdx) {
  60658. case 0:
  60659. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  60660. return;
  60661. case 1:// index trigger
  60662. if (this._defaultModel) {
  60663. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  60664. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  60665. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  60666. }
  60667. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  60668. return;
  60669. case 2:// secondary trigger
  60670. if (this._defaultModel) {
  60671. (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035;
  60672. }
  60673. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  60674. return;
  60675. case 3:
  60676. if (this._defaultModel) {
  60677. if (notifyObject.pressed) {
  60678. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  60679. }
  60680. else {
  60681. (this._defaultModel.getChildren()[1]).position.y = 0;
  60682. }
  60683. }
  60684. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  60685. return;
  60686. case 4:
  60687. if (this._defaultModel) {
  60688. if (notifyObject.pressed) {
  60689. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  60690. }
  60691. else {
  60692. (this._defaultModel.getChildren()[2]).position.y = 0;
  60693. }
  60694. }
  60695. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  60696. return;
  60697. case 5:
  60698. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  60699. return;
  60700. }
  60701. };
  60702. OculusTouchController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/oculus/';
  60703. OculusTouchController.MODEL_LEFT_FILENAME = 'left.babylon';
  60704. OculusTouchController.MODEL_RIGHT_FILENAME = 'right.babylon';
  60705. return OculusTouchController;
  60706. }(BABYLON.WebVRController));
  60707. BABYLON.OculusTouchController = OculusTouchController;
  60708. })(BABYLON || (BABYLON = {}));
  60709. //# sourceMappingURL=babylon.oculusTouchController.js.map
  60710. var BABYLON;
  60711. (function (BABYLON) {
  60712. var ViveController = /** @class */ (function (_super) {
  60713. __extends(ViveController, _super);
  60714. function ViveController(vrGamepad) {
  60715. var _this = _super.call(this, vrGamepad) || this;
  60716. _this.controllerType = BABYLON.PoseEnabledControllerType.VIVE;
  60717. _this._invertLeftStickY = true;
  60718. return _this;
  60719. }
  60720. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  60721. var _this = this;
  60722. BABYLON.SceneLoader.ImportMesh("", ViveController.MODEL_BASE_URL, ViveController.MODEL_FILENAME, scene, function (newMeshes) {
  60723. /*
  60724. Parent Mesh name: ViveWand
  60725. - body
  60726. - r_gripper
  60727. - l_gripper
  60728. - menu_button
  60729. - system_button
  60730. - trackpad
  60731. - trigger
  60732. - LED
  60733. */
  60734. _this._defaultModel = newMeshes[1];
  60735. _this.attachToMesh(_this._defaultModel);
  60736. if (meshLoaded) {
  60737. meshLoaded(_this._defaultModel);
  60738. }
  60739. });
  60740. };
  60741. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  60742. get: function () {
  60743. return this.onMainButtonStateChangedObservable;
  60744. },
  60745. enumerable: true,
  60746. configurable: true
  60747. });
  60748. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  60749. get: function () {
  60750. return this.onMainButtonStateChangedObservable;
  60751. },
  60752. enumerable: true,
  60753. configurable: true
  60754. });
  60755. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  60756. get: function () {
  60757. return this.onSecondaryButtonStateChangedObservable;
  60758. },
  60759. enumerable: true,
  60760. configurable: true
  60761. });
  60762. /**
  60763. * Vive mapping:
  60764. * 0: touchpad
  60765. * 1: trigger
  60766. * 2: left AND right buttons
  60767. * 3: menu button
  60768. */
  60769. ViveController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  60770. var notifyObject = state; //{ state: state, changes: changes };
  60771. switch (buttonIdx) {
  60772. case 0:
  60773. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  60774. return;
  60775. case 1:// index trigger
  60776. if (this._defaultModel) {
  60777. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  60778. }
  60779. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  60780. return;
  60781. case 2:// left AND right button
  60782. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  60783. return;
  60784. case 3:
  60785. if (this._defaultModel) {
  60786. if (notifyObject.pressed) {
  60787. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  60788. }
  60789. else {
  60790. (this._defaultModel.getChildren()[2]).position.y = 0;
  60791. }
  60792. }
  60793. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  60794. return;
  60795. }
  60796. };
  60797. ViveController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/vive/';
  60798. ViveController.MODEL_FILENAME = 'wand.babylon';
  60799. return ViveController;
  60800. }(BABYLON.WebVRController));
  60801. BABYLON.ViveController = ViveController;
  60802. })(BABYLON || (BABYLON = {}));
  60803. //# sourceMappingURL=babylon.viveController.js.map
  60804. var BABYLON;
  60805. (function (BABYLON) {
  60806. var GenericController = /** @class */ (function (_super) {
  60807. __extends(GenericController, _super);
  60808. function GenericController(vrGamepad) {
  60809. return _super.call(this, vrGamepad) || this;
  60810. }
  60811. GenericController.prototype.initControllerMesh = function (scene, meshLoaded) {
  60812. var _this = this;
  60813. BABYLON.SceneLoader.ImportMesh("", GenericController.MODEL_BASE_URL, GenericController.MODEL_FILENAME, scene, function (newMeshes) {
  60814. _this._defaultModel = newMeshes[1];
  60815. _this.attachToMesh(_this._defaultModel);
  60816. if (meshLoaded) {
  60817. meshLoaded(_this._defaultModel);
  60818. }
  60819. });
  60820. };
  60821. GenericController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  60822. console.log("Button id: " + buttonIdx + "state: ");
  60823. console.dir(state);
  60824. };
  60825. GenericController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  60826. GenericController.MODEL_FILENAME = 'generic.babylon';
  60827. return GenericController;
  60828. }(BABYLON.WebVRController));
  60829. BABYLON.GenericController = GenericController;
  60830. })(BABYLON || (BABYLON = {}));
  60831. //# sourceMappingURL=babylon.genericController.js.map
  60832. var BABYLON;
  60833. (function (BABYLON) {
  60834. var LoadedMeshInfo = /** @class */ (function () {
  60835. function LoadedMeshInfo() {
  60836. this.buttonMeshes = {};
  60837. this.axisMeshes = {};
  60838. }
  60839. return LoadedMeshInfo;
  60840. }());
  60841. var WindowsMotionController = /** @class */ (function (_super) {
  60842. __extends(WindowsMotionController, _super);
  60843. function WindowsMotionController(vrGamepad) {
  60844. var _this = _super.call(this, vrGamepad) || this;
  60845. _this._mapping = {
  60846. // Semantic button names
  60847. buttons: ['thumbstick', 'trigger', 'grip', 'menu', 'trackpad'],
  60848. // A mapping of the button name to glTF model node name
  60849. // that should be transformed by button value.
  60850. buttonMeshNames: {
  60851. 'trigger': 'SELECT',
  60852. 'menu': 'MENU',
  60853. 'grip': 'GRASP',
  60854. 'thumbstick': 'THUMBSTICK_PRESS',
  60855. 'trackpad': 'TOUCHPAD_PRESS'
  60856. },
  60857. // This mapping is used to translate from the Motion Controller to Babylon semantics
  60858. buttonObservableNames: {
  60859. 'trigger': 'onTriggerStateChangedObservable',
  60860. 'menu': 'onSecondaryButtonStateChangedObservable',
  60861. 'grip': 'onMainButtonStateChangedObservable',
  60862. 'thumbstick': 'onPadStateChangedObservable',
  60863. 'trackpad': 'onTrackpadChangedObservable'
  60864. },
  60865. // A mapping of the axis name to glTF model node name
  60866. // that should be transformed by axis value.
  60867. // This array mirrors the browserGamepad.axes array, such that
  60868. // the mesh corresponding to axis 0 is in this array index 0.
  60869. axisMeshNames: [
  60870. 'THUMBSTICK_X',
  60871. 'THUMBSTICK_Y',
  60872. 'TOUCHPAD_TOUCH_X',
  60873. 'TOUCHPAD_TOUCH_Y'
  60874. ],
  60875. pointingPoseMeshName: 'POINTING_POSE'
  60876. };
  60877. _this.onTrackpadChangedObservable = new BABYLON.Observable();
  60878. _this.onTrackpadValuesChangedObservable = new BABYLON.Observable();
  60879. _this.trackpad = { x: 0, y: 0 };
  60880. _this.controllerType = BABYLON.PoseEnabledControllerType.WINDOWS;
  60881. _this._loadedMeshInfo = null;
  60882. return _this;
  60883. }
  60884. Object.defineProperty(WindowsMotionController.prototype, "onTriggerButtonStateChangedObservable", {
  60885. get: function () {
  60886. return this.onTriggerStateChangedObservable;
  60887. },
  60888. enumerable: true,
  60889. configurable: true
  60890. });
  60891. Object.defineProperty(WindowsMotionController.prototype, "onMenuButtonStateChangedObservable", {
  60892. get: function () {
  60893. return this.onSecondaryButtonStateChangedObservable;
  60894. },
  60895. enumerable: true,
  60896. configurable: true
  60897. });
  60898. Object.defineProperty(WindowsMotionController.prototype, "onGripButtonStateChangedObservable", {
  60899. get: function () {
  60900. return this.onMainButtonStateChangedObservable;
  60901. },
  60902. enumerable: true,
  60903. configurable: true
  60904. });
  60905. Object.defineProperty(WindowsMotionController.prototype, "onThumbstickButtonStateChangedObservable", {
  60906. get: function () {
  60907. return this.onPadStateChangedObservable;
  60908. },
  60909. enumerable: true,
  60910. configurable: true
  60911. });
  60912. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadButtonStateChangedObservable", {
  60913. get: function () {
  60914. return this.onTrackpadChangedObservable;
  60915. },
  60916. enumerable: true,
  60917. configurable: true
  60918. });
  60919. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadValuesChangedObservable", {
  60920. get: function () {
  60921. return this.onTrackpadValuesChangedObservable;
  60922. },
  60923. enumerable: true,
  60924. configurable: true
  60925. });
  60926. /**
  60927. * Called once per frame by the engine.
  60928. */
  60929. WindowsMotionController.prototype.update = function () {
  60930. _super.prototype.update.call(this);
  60931. // Only need to animate axes if there is a loaded mesh
  60932. if (this._loadedMeshInfo) {
  60933. if (this.browserGamepad.axes) {
  60934. if (this.browserGamepad.axes[2] != this.trackpad.x || this.browserGamepad.axes[3] != this.trackpad.y) {
  60935. this.trackpad.x = this.browserGamepad["axes"][2];
  60936. this.trackpad.y = this.browserGamepad["axes"][3];
  60937. this.onTrackpadValuesChangedObservable.notifyObservers(this.trackpad);
  60938. }
  60939. for (var axis = 0; axis < this._mapping.axisMeshNames.length; axis++) {
  60940. this.lerpAxisTransform(axis, this.browserGamepad.axes[axis]);
  60941. }
  60942. }
  60943. }
  60944. };
  60945. /**
  60946. * Called once for each button that changed state since the last frame
  60947. * @param buttonIdx Which button index changed
  60948. * @param state New state of the button
  60949. * @param changes Which properties on the state changed since last frame
  60950. */
  60951. WindowsMotionController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  60952. var buttonName = this._mapping.buttons[buttonIdx];
  60953. if (!buttonName) {
  60954. return;
  60955. }
  60956. // Only emit events for buttons that we know how to map from index to name
  60957. var observable = this[(this._mapping.buttonObservableNames)[buttonName]];
  60958. if (observable) {
  60959. observable.notifyObservers(state);
  60960. }
  60961. this.lerpButtonTransform(buttonName, state.value);
  60962. };
  60963. WindowsMotionController.prototype.lerpButtonTransform = function (buttonName, buttonValue) {
  60964. // If there is no loaded mesh, there is nothing to transform.
  60965. if (!this._loadedMeshInfo) {
  60966. return;
  60967. }
  60968. var meshInfo = this._loadedMeshInfo.buttonMeshes[buttonName];
  60969. if (!meshInfo.unpressed.rotationQuaternion || !meshInfo.pressed.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  60970. return;
  60971. }
  60972. BABYLON.Quaternion.SlerpToRef(meshInfo.unpressed.rotationQuaternion, meshInfo.pressed.rotationQuaternion, buttonValue, meshInfo.value.rotationQuaternion);
  60973. BABYLON.Vector3.LerpToRef(meshInfo.unpressed.position, meshInfo.pressed.position, buttonValue, meshInfo.value.position);
  60974. };
  60975. WindowsMotionController.prototype.lerpAxisTransform = function (axis, axisValue) {
  60976. if (!this._loadedMeshInfo) {
  60977. return;
  60978. }
  60979. var meshInfo = this._loadedMeshInfo.axisMeshes[axis];
  60980. if (!meshInfo) {
  60981. return;
  60982. }
  60983. if (!meshInfo.min.rotationQuaternion || !meshInfo.max.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  60984. return;
  60985. }
  60986. // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1)
  60987. var lerpValue = axisValue * 0.5 + 0.5;
  60988. BABYLON.Quaternion.SlerpToRef(meshInfo.min.rotationQuaternion, meshInfo.max.rotationQuaternion, lerpValue, meshInfo.value.rotationQuaternion);
  60989. BABYLON.Vector3.LerpToRef(meshInfo.min.position, meshInfo.max.position, lerpValue, meshInfo.value.position);
  60990. };
  60991. /**
  60992. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  60993. * @param scene scene in which to add meshes
  60994. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  60995. */
  60996. WindowsMotionController.prototype.initControllerMesh = function (scene, meshLoaded, forceDefault) {
  60997. var _this = this;
  60998. if (forceDefault === void 0) { forceDefault = false; }
  60999. var path;
  61000. var filename;
  61001. // Checking if GLB loader is present
  61002. if (BABYLON.SceneLoader.IsPluginForExtensionAvailable(".glb")) {
  61003. // Determine the device specific folder based on the ID suffix
  61004. var device = 'default';
  61005. if (this.id && !forceDefault) {
  61006. var match = this.id.match(WindowsMotionController.GAMEPAD_ID_PATTERN);
  61007. device = ((match && match[0]) || device);
  61008. }
  61009. // Hand
  61010. if (this.hand === 'left') {
  61011. filename = WindowsMotionController.MODEL_LEFT_FILENAME;
  61012. }
  61013. else {
  61014. filename = WindowsMotionController.MODEL_RIGHT_FILENAME;
  61015. }
  61016. path = WindowsMotionController.MODEL_BASE_URL + device + '/';
  61017. }
  61018. else {
  61019. BABYLON.Tools.Warn("You need to reference GLTF loader to load Windows Motion Controllers model. Falling back to generic models");
  61020. path = BABYLON.GenericController.MODEL_BASE_URL;
  61021. filename = BABYLON.GenericController.MODEL_FILENAME;
  61022. }
  61023. BABYLON.SceneLoader.ImportMesh("", path, filename, scene, function (meshes) {
  61024. // glTF files successfully loaded from the remote server, now process them to ensure they are in the right format.
  61025. _this._loadedMeshInfo = _this.processModel(scene, meshes);
  61026. if (!_this._loadedMeshInfo) {
  61027. return;
  61028. }
  61029. _this._defaultModel = _this._loadedMeshInfo.rootNode;
  61030. _this.attachToMesh(_this._defaultModel);
  61031. if (meshLoaded) {
  61032. meshLoaded(_this._defaultModel);
  61033. }
  61034. }, null, function (scene, message) {
  61035. BABYLON.Tools.Log(message);
  61036. BABYLON.Tools.Warn('Failed to retrieve controller model from the remote server: ' + path + filename);
  61037. if (!forceDefault) {
  61038. _this.initControllerMesh(scene, meshLoaded, true);
  61039. }
  61040. });
  61041. };
  61042. /**
  61043. * Takes a list of meshes (as loaded from the glTF file) and finds the root node, as well as nodes that
  61044. * can be transformed by button presses and axes values, based on this._mapping.
  61045. *
  61046. * @param scene scene in which the meshes exist
  61047. * @param meshes list of meshes that make up the controller model to process
  61048. * @return structured view of the given meshes, with mapping of buttons and axes to meshes that can be transformed.
  61049. */
  61050. WindowsMotionController.prototype.processModel = function (scene, meshes) {
  61051. var loadedMeshInfo = null;
  61052. // Create a new mesh to contain the glTF hierarchy
  61053. var parentMesh = new BABYLON.Mesh(this.id + " " + this.hand, scene);
  61054. // Find the root node in the loaded glTF scene, and attach it as a child of 'parentMesh'
  61055. var childMesh = null;
  61056. for (var i = 0; i < meshes.length; i++) {
  61057. var mesh = meshes[i];
  61058. if (!mesh.parent) {
  61059. // Exclude controller meshes from picking results
  61060. mesh.isPickable = false;
  61061. // Handle root node, attach to the new parentMesh
  61062. childMesh = mesh;
  61063. break;
  61064. }
  61065. }
  61066. if (childMesh) {
  61067. childMesh.setParent(parentMesh);
  61068. // Create our mesh info. Note that this method will always return non-null.
  61069. loadedMeshInfo = this.createMeshInfo(parentMesh);
  61070. }
  61071. else {
  61072. BABYLON.Tools.Warn('Could not find root node in model file.');
  61073. }
  61074. return loadedMeshInfo;
  61075. };
  61076. WindowsMotionController.prototype.createMeshInfo = function (rootNode) {
  61077. var loadedMeshInfo = new LoadedMeshInfo();
  61078. var i;
  61079. loadedMeshInfo.rootNode = rootNode;
  61080. // Reset the caches
  61081. loadedMeshInfo.buttonMeshes = {};
  61082. loadedMeshInfo.axisMeshes = {};
  61083. // Button Meshes
  61084. for (i = 0; i < this._mapping.buttons.length; i++) {
  61085. var buttonMeshName = this._mapping.buttonMeshNames[this._mapping.buttons[i]];
  61086. if (!buttonMeshName) {
  61087. BABYLON.Tools.Log('Skipping unknown button at index: ' + i + ' with mapped name: ' + this._mapping.buttons[i]);
  61088. continue;
  61089. }
  61090. var buttonMesh = getChildByName(rootNode, buttonMeshName);
  61091. if (!buttonMesh) {
  61092. BABYLON.Tools.Warn('Missing button mesh with name: ' + buttonMeshName);
  61093. continue;
  61094. }
  61095. var buttonMeshInfo = {
  61096. index: i,
  61097. value: getImmediateChildByName(buttonMesh, 'VALUE'),
  61098. pressed: getImmediateChildByName(buttonMesh, 'PRESSED'),
  61099. unpressed: getImmediateChildByName(buttonMesh, 'UNPRESSED')
  61100. };
  61101. if (buttonMeshInfo.value && buttonMeshInfo.pressed && buttonMeshInfo.unpressed) {
  61102. loadedMeshInfo.buttonMeshes[this._mapping.buttons[i]] = buttonMeshInfo;
  61103. }
  61104. else {
  61105. // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.
  61106. BABYLON.Tools.Warn('Missing button submesh under mesh with name: ' + buttonMeshName +
  61107. '(VALUE: ' + !!buttonMeshInfo.value +
  61108. ', PRESSED: ' + !!buttonMeshInfo.pressed +
  61109. ', UNPRESSED:' + !!buttonMeshInfo.unpressed +
  61110. ')');
  61111. }
  61112. }
  61113. // Axis Meshes
  61114. for (i = 0; i < this._mapping.axisMeshNames.length; i++) {
  61115. var axisMeshName = this._mapping.axisMeshNames[i];
  61116. if (!axisMeshName) {
  61117. BABYLON.Tools.Log('Skipping unknown axis at index: ' + i);
  61118. continue;
  61119. }
  61120. var axisMesh = getChildByName(rootNode, axisMeshName);
  61121. if (!axisMesh) {
  61122. BABYLON.Tools.Warn('Missing axis mesh with name: ' + axisMeshName);
  61123. continue;
  61124. }
  61125. var axisMeshInfo = {
  61126. index: i,
  61127. value: getImmediateChildByName(axisMesh, 'VALUE'),
  61128. min: getImmediateChildByName(axisMesh, 'MIN'),
  61129. max: getImmediateChildByName(axisMesh, 'MAX')
  61130. };
  61131. if (axisMeshInfo.value && axisMeshInfo.min && axisMeshInfo.max) {
  61132. loadedMeshInfo.axisMeshes[i] = axisMeshInfo;
  61133. }
  61134. else {
  61135. // If we didn't find the mesh, it simply means thit axis won't have transforms applied as mapped axis values change.
  61136. BABYLON.Tools.Warn('Missing axis submesh under mesh with name: ' + axisMeshName +
  61137. '(VALUE: ' + !!axisMeshInfo.value +
  61138. ', MIN: ' + !!axisMeshInfo.min +
  61139. ', MAX:' + !!axisMeshInfo.max +
  61140. ')');
  61141. }
  61142. }
  61143. // Pointing Ray
  61144. loadedMeshInfo.pointingPoseNode = getChildByName(rootNode, this._mapping.pointingPoseMeshName);
  61145. if (!loadedMeshInfo.pointingPoseNode) {
  61146. BABYLON.Tools.Warn('Missing pointing pose mesh with name: ' + this._mapping.pointingPoseMeshName);
  61147. }
  61148. return loadedMeshInfo;
  61149. // Look through all children recursively. This will return null if no mesh exists with the given name.
  61150. function getChildByName(node, name) {
  61151. return node.getChildMeshes(false, function (n) { return n.name === name; })[0];
  61152. }
  61153. // Look through only immediate children. This will return null if no mesh exists with the given name.
  61154. function getImmediateChildByName(node, name) {
  61155. return node.getChildMeshes(true, function (n) { return n.name == name; })[0];
  61156. }
  61157. };
  61158. WindowsMotionController.prototype.getForwardRay = function (length) {
  61159. if (length === void 0) { length = 100; }
  61160. if (!(this._loadedMeshInfo && this._loadedMeshInfo.pointingPoseNode)) {
  61161. return _super.prototype.getForwardRay.call(this, length);
  61162. }
  61163. var m = this._loadedMeshInfo.pointingPoseNode.getWorldMatrix();
  61164. var origin = m.getTranslation();
  61165. var forward = new BABYLON.Vector3(0, 0, -1);
  61166. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  61167. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  61168. return new BABYLON.Ray(origin, direction, length);
  61169. };
  61170. WindowsMotionController.prototype.dispose = function () {
  61171. _super.prototype.dispose.call(this);
  61172. this.onTrackpadChangedObservable.clear();
  61173. };
  61174. WindowsMotionController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/microsoft/';
  61175. WindowsMotionController.MODEL_LEFT_FILENAME = 'left.glb';
  61176. WindowsMotionController.MODEL_RIGHT_FILENAME = 'right.glb';
  61177. WindowsMotionController.GAMEPAD_ID_PREFIX = 'Spatial Controller (Spatial Interaction Source) ';
  61178. WindowsMotionController.GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;
  61179. return WindowsMotionController;
  61180. }(BABYLON.WebVRController));
  61181. BABYLON.WindowsMotionController = WindowsMotionController;
  61182. })(BABYLON || (BABYLON = {}));
  61183. //# sourceMappingURL=babylon.windowsMotionController.js.map
  61184. var BABYLON;
  61185. (function (BABYLON) {
  61186. var GearVRController = /** @class */ (function (_super) {
  61187. __extends(GearVRController, _super);
  61188. function GearVRController(vrGamepad) {
  61189. var _this = _super.call(this, vrGamepad) || this;
  61190. _this._buttonIndexToObservableNameMap = [
  61191. 'onTrackpadChangedObservable',
  61192. 'onTriggerStateChangedObservable' // Trigger
  61193. ];
  61194. _this.controllerType = BABYLON.PoseEnabledControllerType.GEAR_VR;
  61195. return _this;
  61196. }
  61197. GearVRController.prototype.initControllerMesh = function (scene, meshLoaded) {
  61198. var _this = this;
  61199. BABYLON.SceneLoader.ImportMesh("", GearVRController.MODEL_BASE_URL, GearVRController.MODEL_FILENAME, scene, function (newMeshes) {
  61200. _this._defaultModel = newMeshes[1];
  61201. _this.attachToMesh(_this._defaultModel);
  61202. if (meshLoaded) {
  61203. meshLoaded(_this._defaultModel);
  61204. }
  61205. });
  61206. };
  61207. GearVRController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  61208. if (buttonIdx < this._buttonIndexToObservableNameMap.length) {
  61209. var observableName = this._buttonIndexToObservableNameMap[buttonIdx];
  61210. // Only emit events for buttons that we know how to map from index to observable
  61211. var observable = this[observableName];
  61212. if (observable) {
  61213. observable.notifyObservers(state);
  61214. }
  61215. }
  61216. };
  61217. GearVRController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  61218. GearVRController.MODEL_FILENAME = 'generic.babylon';
  61219. GearVRController.GAMEPAD_ID_PREFIX = 'Gear VR'; // id is 'Gear VR Controller'
  61220. return GearVRController;
  61221. }(BABYLON.WebVRController));
  61222. BABYLON.GearVRController = GearVRController;
  61223. })(BABYLON || (BABYLON = {}));
  61224. //# sourceMappingURL=babylon.gearVRController.js.map
  61225. var BABYLON;
  61226. (function (BABYLON) {
  61227. var FollowCamera = /** @class */ (function (_super) {
  61228. __extends(FollowCamera, _super);
  61229. function FollowCamera(name, position, scene, lockedTarget) {
  61230. if (lockedTarget === void 0) { lockedTarget = null; }
  61231. var _this = _super.call(this, name, position, scene) || this;
  61232. _this.radius = 12;
  61233. _this.rotationOffset = 0;
  61234. _this.heightOffset = 4;
  61235. _this.cameraAcceleration = 0.05;
  61236. _this.maxCameraSpeed = 20;
  61237. _this.lockedTarget = lockedTarget;
  61238. return _this;
  61239. }
  61240. FollowCamera.prototype.getRadians = function (degrees) {
  61241. return degrees * Math.PI / 180;
  61242. };
  61243. FollowCamera.prototype.follow = function (cameraTarget) {
  61244. if (!cameraTarget)
  61245. return;
  61246. var yRotation;
  61247. if (cameraTarget.rotationQuaternion) {
  61248. var rotMatrix = new BABYLON.Matrix();
  61249. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  61250. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  61251. }
  61252. else {
  61253. yRotation = cameraTarget.rotation.y;
  61254. }
  61255. var radians = this.getRadians(this.rotationOffset) + yRotation;
  61256. var targetPosition = cameraTarget.getAbsolutePosition();
  61257. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  61258. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  61259. var dx = targetX - this.position.x;
  61260. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  61261. var dz = (targetZ) - this.position.z;
  61262. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  61263. var vy = dy * this.cameraAcceleration;
  61264. var vz = dz * this.cameraAcceleration * 2;
  61265. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  61266. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  61267. }
  61268. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  61269. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  61270. }
  61271. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  61272. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  61273. }
  61274. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  61275. this.setTarget(targetPosition);
  61276. };
  61277. FollowCamera.prototype._checkInputs = function () {
  61278. _super.prototype._checkInputs.call(this);
  61279. if (this.lockedTarget) {
  61280. this.follow(this.lockedTarget);
  61281. }
  61282. };
  61283. FollowCamera.prototype.getClassName = function () {
  61284. return "FollowCamera";
  61285. };
  61286. __decorate([
  61287. BABYLON.serialize()
  61288. ], FollowCamera.prototype, "radius", void 0);
  61289. __decorate([
  61290. BABYLON.serialize()
  61291. ], FollowCamera.prototype, "rotationOffset", void 0);
  61292. __decorate([
  61293. BABYLON.serialize()
  61294. ], FollowCamera.prototype, "heightOffset", void 0);
  61295. __decorate([
  61296. BABYLON.serialize()
  61297. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  61298. __decorate([
  61299. BABYLON.serialize()
  61300. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  61301. __decorate([
  61302. BABYLON.serializeAsMeshReference("lockedTargetId")
  61303. ], FollowCamera.prototype, "lockedTarget", void 0);
  61304. return FollowCamera;
  61305. }(BABYLON.TargetCamera));
  61306. BABYLON.FollowCamera = FollowCamera;
  61307. var ArcFollowCamera = /** @class */ (function (_super) {
  61308. __extends(ArcFollowCamera, _super);
  61309. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  61310. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  61311. _this.alpha = alpha;
  61312. _this.beta = beta;
  61313. _this.radius = radius;
  61314. _this.target = target;
  61315. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  61316. _this.follow();
  61317. return _this;
  61318. }
  61319. ArcFollowCamera.prototype.follow = function () {
  61320. if (!this.target) {
  61321. return;
  61322. }
  61323. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  61324. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  61325. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  61326. var targetPosition = this.target.getAbsolutePosition();
  61327. this.position = targetPosition.add(this._cartesianCoordinates);
  61328. this.setTarget(targetPosition);
  61329. };
  61330. ArcFollowCamera.prototype._checkInputs = function () {
  61331. _super.prototype._checkInputs.call(this);
  61332. this.follow();
  61333. };
  61334. ArcFollowCamera.prototype.getClassName = function () {
  61335. return "ArcFollowCamera";
  61336. };
  61337. return ArcFollowCamera;
  61338. }(BABYLON.TargetCamera));
  61339. BABYLON.ArcFollowCamera = ArcFollowCamera;
  61340. })(BABYLON || (BABYLON = {}));
  61341. //# sourceMappingURL=babylon.followCamera.js.map
  61342. var BABYLON;
  61343. (function (BABYLON) {
  61344. // We're mainly based on the logic defined into the FreeCamera code
  61345. var UniversalCamera = /** @class */ (function (_super) {
  61346. __extends(UniversalCamera, _super);
  61347. //-- end properties for backward compatibility for inputs
  61348. function UniversalCamera(name, position, scene) {
  61349. var _this = _super.call(this, name, position, scene) || this;
  61350. _this.inputs.addGamepad();
  61351. return _this;
  61352. }
  61353. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  61354. //-- Begin properties for backward compatibility for inputs
  61355. get: function () {
  61356. var gamepad = this.inputs.attached["gamepad"];
  61357. if (gamepad)
  61358. return gamepad.gamepadAngularSensibility;
  61359. return 0;
  61360. },
  61361. set: function (value) {
  61362. var gamepad = this.inputs.attached["gamepad"];
  61363. if (gamepad)
  61364. gamepad.gamepadAngularSensibility = value;
  61365. },
  61366. enumerable: true,
  61367. configurable: true
  61368. });
  61369. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  61370. get: function () {
  61371. var gamepad = this.inputs.attached["gamepad"];
  61372. if (gamepad)
  61373. return gamepad.gamepadMoveSensibility;
  61374. return 0;
  61375. },
  61376. set: function (value) {
  61377. var gamepad = this.inputs.attached["gamepad"];
  61378. if (gamepad)
  61379. gamepad.gamepadMoveSensibility = value;
  61380. },
  61381. enumerable: true,
  61382. configurable: true
  61383. });
  61384. UniversalCamera.prototype.getClassName = function () {
  61385. return "UniversalCamera";
  61386. };
  61387. return UniversalCamera;
  61388. }(BABYLON.TouchCamera));
  61389. BABYLON.UniversalCamera = UniversalCamera;
  61390. })(BABYLON || (BABYLON = {}));
  61391. //# sourceMappingURL=babylon.universalCamera.js.map
  61392. var BABYLON;
  61393. (function (BABYLON) {
  61394. // We're mainly based on the logic defined into the FreeCamera code
  61395. var GamepadCamera = /** @class */ (function (_super) {
  61396. __extends(GamepadCamera, _super);
  61397. //-- end properties for backward compatibility for inputs
  61398. function GamepadCamera(name, position, scene) {
  61399. return _super.call(this, name, position, scene) || this;
  61400. }
  61401. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  61402. //-- Begin properties for backward compatibility for inputs
  61403. get: function () {
  61404. var gamepad = this.inputs.attached["gamepad"];
  61405. if (gamepad)
  61406. return gamepad.gamepadAngularSensibility;
  61407. return 0;
  61408. },
  61409. set: function (value) {
  61410. var gamepad = this.inputs.attached["gamepad"];
  61411. if (gamepad)
  61412. gamepad.gamepadAngularSensibility = value;
  61413. },
  61414. enumerable: true,
  61415. configurable: true
  61416. });
  61417. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  61418. get: function () {
  61419. var gamepad = this.inputs.attached["gamepad"];
  61420. if (gamepad)
  61421. return gamepad.gamepadMoveSensibility;
  61422. return 0;
  61423. },
  61424. set: function (value) {
  61425. var gamepad = this.inputs.attached["gamepad"];
  61426. if (gamepad)
  61427. gamepad.gamepadMoveSensibility = value;
  61428. },
  61429. enumerable: true,
  61430. configurable: true
  61431. });
  61432. GamepadCamera.prototype.getClassName = function () {
  61433. return "GamepadCamera";
  61434. };
  61435. return GamepadCamera;
  61436. }(BABYLON.UniversalCamera));
  61437. BABYLON.GamepadCamera = GamepadCamera;
  61438. })(BABYLON || (BABYLON = {}));
  61439. //# sourceMappingURL=babylon.gamepadCamera.js.map
  61440. var BABYLON;
  61441. (function (BABYLON) {
  61442. var PostProcessRenderPipelineManager = /** @class */ (function () {
  61443. function PostProcessRenderPipelineManager() {
  61444. this._renderPipelines = {};
  61445. }
  61446. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  61447. this._renderPipelines[renderPipeline._name] = renderPipeline;
  61448. };
  61449. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  61450. if (unique === void 0) { unique = false; }
  61451. var renderPipeline = this._renderPipelines[renderPipelineName];
  61452. if (!renderPipeline) {
  61453. return;
  61454. }
  61455. renderPipeline._attachCameras(cameras, unique);
  61456. };
  61457. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  61458. var renderPipeline = this._renderPipelines[renderPipelineName];
  61459. if (!renderPipeline) {
  61460. return;
  61461. }
  61462. renderPipeline._detachCameras(cameras);
  61463. };
  61464. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  61465. var renderPipeline = this._renderPipelines[renderPipelineName];
  61466. if (!renderPipeline) {
  61467. return;
  61468. }
  61469. renderPipeline._enableEffect(renderEffectName, cameras);
  61470. };
  61471. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  61472. var renderPipeline = this._renderPipelines[renderPipelineName];
  61473. if (!renderPipeline) {
  61474. return;
  61475. }
  61476. renderPipeline._disableEffect(renderEffectName, cameras);
  61477. };
  61478. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  61479. var renderPipeline = this._renderPipelines[renderPipelineName];
  61480. if (!renderPipeline) {
  61481. return;
  61482. }
  61483. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  61484. };
  61485. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  61486. var renderPipeline = this._renderPipelines[renderPipelineName];
  61487. if (!renderPipeline) {
  61488. return;
  61489. }
  61490. renderPipeline._disableDisplayOnlyPass(cameras);
  61491. };
  61492. PostProcessRenderPipelineManager.prototype.update = function () {
  61493. for (var renderPipelineName in this._renderPipelines) {
  61494. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  61495. var pipeline = this._renderPipelines[renderPipelineName];
  61496. if (!pipeline.isSupported) {
  61497. pipeline.dispose();
  61498. delete this._renderPipelines[renderPipelineName];
  61499. }
  61500. else {
  61501. pipeline._update();
  61502. }
  61503. }
  61504. }
  61505. };
  61506. PostProcessRenderPipelineManager.prototype._rebuild = function () {
  61507. for (var renderPipelineName in this._renderPipelines) {
  61508. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  61509. var pipeline = this._renderPipelines[renderPipelineName];
  61510. pipeline._rebuild();
  61511. }
  61512. }
  61513. };
  61514. PostProcessRenderPipelineManager.prototype.dispose = function () {
  61515. for (var renderPipelineName in this._renderPipelines) {
  61516. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  61517. var pipeline = this._renderPipelines[renderPipelineName];
  61518. pipeline.dispose();
  61519. }
  61520. }
  61521. };
  61522. return PostProcessRenderPipelineManager;
  61523. }());
  61524. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  61525. })(BABYLON || (BABYLON = {}));
  61526. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  61527. var BABYLON;
  61528. (function (BABYLON) {
  61529. var PostProcessRenderPass = /** @class */ (function () {
  61530. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  61531. this._refCount = 0;
  61532. this._name = name;
  61533. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  61534. this.setRenderList(renderList);
  61535. this._renderTexture.onBeforeRenderObservable.add(beforeRender);
  61536. this._renderTexture.onAfterRenderObservable.add(afterRender);
  61537. this._scene = scene;
  61538. this._renderList = renderList;
  61539. }
  61540. // private
  61541. PostProcessRenderPass.prototype._incRefCount = function () {
  61542. if (this._refCount === 0) {
  61543. this._scene.customRenderTargets.push(this._renderTexture);
  61544. }
  61545. return ++this._refCount;
  61546. };
  61547. PostProcessRenderPass.prototype._decRefCount = function () {
  61548. this._refCount--;
  61549. if (this._refCount <= 0) {
  61550. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  61551. }
  61552. return this._refCount;
  61553. };
  61554. PostProcessRenderPass.prototype._update = function () {
  61555. this.setRenderList(this._renderList);
  61556. };
  61557. // public
  61558. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  61559. this._renderTexture.renderList = renderList;
  61560. };
  61561. PostProcessRenderPass.prototype.getRenderTexture = function () {
  61562. return this._renderTexture;
  61563. };
  61564. return PostProcessRenderPass;
  61565. }());
  61566. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  61567. })(BABYLON || (BABYLON = {}));
  61568. //# sourceMappingURL=babylon.postProcessRenderPass.js.map
  61569. var BABYLON;
  61570. (function (BABYLON) {
  61571. var PostProcessRenderEffect = /** @class */ (function () {
  61572. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  61573. this._name = name;
  61574. this._singleInstance = singleInstance || true;
  61575. this._getPostProcess = getPostProcess;
  61576. this._cameras = {};
  61577. this._indicesForCamera = {};
  61578. this._postProcesses = {};
  61579. this._renderPasses = {};
  61580. this._renderEffectAsPasses = {};
  61581. }
  61582. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  61583. get: function () {
  61584. for (var index in this._postProcesses) {
  61585. if (!this._postProcesses[index].isSupported) {
  61586. return false;
  61587. }
  61588. }
  61589. return true;
  61590. },
  61591. enumerable: true,
  61592. configurable: true
  61593. });
  61594. PostProcessRenderEffect.prototype._update = function () {
  61595. for (var renderPassName in this._renderPasses) {
  61596. this._renderPasses[renderPassName]._update();
  61597. }
  61598. };
  61599. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  61600. this._renderPasses[renderPass._name] = renderPass;
  61601. this._linkParameters();
  61602. };
  61603. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  61604. delete this._renderPasses[renderPass._name];
  61605. this._linkParameters();
  61606. };
  61607. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  61608. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  61609. this._linkParameters();
  61610. };
  61611. PostProcessRenderEffect.prototype.getPass = function (passName) {
  61612. for (var renderPassName in this._renderPasses) {
  61613. if (renderPassName === passName) {
  61614. return this._renderPasses[passName];
  61615. }
  61616. }
  61617. return null;
  61618. };
  61619. PostProcessRenderEffect.prototype.emptyPasses = function () {
  61620. this._renderPasses = {};
  61621. this._linkParameters();
  61622. };
  61623. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  61624. var cameraKey;
  61625. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  61626. if (!cams) {
  61627. return;
  61628. }
  61629. for (var i = 0; i < cams.length; i++) {
  61630. var camera = cams[i];
  61631. var cameraName = camera.name;
  61632. if (this._singleInstance) {
  61633. cameraKey = 0;
  61634. }
  61635. else {
  61636. cameraKey = cameraName;
  61637. }
  61638. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  61639. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  61640. if (!this._indicesForCamera[cameraName]) {
  61641. this._indicesForCamera[cameraName] = [];
  61642. }
  61643. this._indicesForCamera[cameraName].push(index);
  61644. if (!this._cameras[cameraName]) {
  61645. this._cameras[cameraName] = camera;
  61646. }
  61647. for (var passName in this._renderPasses) {
  61648. this._renderPasses[passName]._incRefCount();
  61649. }
  61650. }
  61651. this._linkParameters();
  61652. };
  61653. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  61654. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  61655. if (!cams) {
  61656. return;
  61657. }
  61658. for (var i = 0; i < cams.length; i++) {
  61659. var camera = cams[i];
  61660. var cameraName = camera.name;
  61661. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName]);
  61662. if (this._cameras[cameraName]) {
  61663. //this._indicesForCamera.splice(index, 1);
  61664. this._cameras[cameraName] = null;
  61665. }
  61666. for (var passName in this._renderPasses) {
  61667. this._renderPasses[passName]._decRefCount();
  61668. }
  61669. }
  61670. };
  61671. PostProcessRenderEffect.prototype._enable = function (cameras) {
  61672. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  61673. if (!cams) {
  61674. return;
  61675. }
  61676. for (var i = 0; i < cams.length; i++) {
  61677. var camera = cams[i];
  61678. var cameraName = camera.name;
  61679. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  61680. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  61681. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  61682. }
  61683. }
  61684. for (var passName in this._renderPasses) {
  61685. this._renderPasses[passName]._incRefCount();
  61686. }
  61687. }
  61688. };
  61689. PostProcessRenderEffect.prototype._disable = function (cameras) {
  61690. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  61691. if (!cams) {
  61692. return;
  61693. }
  61694. for (var i = 0; i < cams.length; i++) {
  61695. var camera = cams[i];
  61696. var cameraName = camera.Name;
  61697. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName]);
  61698. for (var passName in this._renderPasses) {
  61699. this._renderPasses[passName]._decRefCount();
  61700. }
  61701. }
  61702. };
  61703. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  61704. if (this._singleInstance) {
  61705. return this._postProcesses[0];
  61706. }
  61707. else {
  61708. if (!camera) {
  61709. return null;
  61710. }
  61711. return this._postProcesses[camera.name];
  61712. }
  61713. };
  61714. PostProcessRenderEffect.prototype._linkParameters = function () {
  61715. var _this = this;
  61716. for (var index in this._postProcesses) {
  61717. if (this.applyParameters) {
  61718. this.applyParameters(this._postProcesses[index]);
  61719. }
  61720. this._postProcesses[index].onBeforeRenderObservable.add(function (effect) {
  61721. _this._linkTextures(effect);
  61722. });
  61723. }
  61724. };
  61725. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  61726. for (var renderPassName in this._renderPasses) {
  61727. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  61728. }
  61729. for (var renderEffectName in this._renderEffectAsPasses) {
  61730. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  61731. }
  61732. };
  61733. return PostProcessRenderEffect;
  61734. }());
  61735. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  61736. })(BABYLON || (BABYLON = {}));
  61737. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  61738. var BABYLON;
  61739. (function (BABYLON) {
  61740. var PostProcessRenderPipeline = /** @class */ (function () {
  61741. function PostProcessRenderPipeline(engine, name) {
  61742. this._engine = engine;
  61743. this._name = name;
  61744. this._renderEffects = {};
  61745. this._renderEffectsForIsolatedPass = new Array();
  61746. this._cameras = [];
  61747. }
  61748. PostProcessRenderPipeline.prototype.getClassName = function () {
  61749. return "PostProcessRenderPipeline";
  61750. };
  61751. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  61752. get: function () {
  61753. for (var renderEffectName in this._renderEffects) {
  61754. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  61755. if (!this._renderEffects[renderEffectName].isSupported) {
  61756. return false;
  61757. }
  61758. }
  61759. }
  61760. return true;
  61761. },
  61762. enumerable: true,
  61763. configurable: true
  61764. });
  61765. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  61766. this._renderEffects[renderEffect._name] = renderEffect;
  61767. };
  61768. // private
  61769. PostProcessRenderPipeline.prototype._rebuild = function () {
  61770. };
  61771. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  61772. var renderEffects = this._renderEffects[renderEffectName];
  61773. if (!renderEffects) {
  61774. return;
  61775. }
  61776. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  61777. };
  61778. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  61779. var renderEffects = this._renderEffects[renderEffectName];
  61780. if (!renderEffects) {
  61781. return;
  61782. }
  61783. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  61784. };
  61785. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  61786. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  61787. if (!cams) {
  61788. return;
  61789. }
  61790. var indicesToDelete = [];
  61791. var i;
  61792. for (i = 0; i < cams.length; i++) {
  61793. var camera = cams[i];
  61794. var cameraName = camera.name;
  61795. if (this._cameras.indexOf(camera) === -1) {
  61796. this._cameras[cameraName] = camera;
  61797. }
  61798. else if (unique) {
  61799. indicesToDelete.push(i);
  61800. }
  61801. }
  61802. for (i = 0; i < indicesToDelete.length; i++) {
  61803. cameras.splice(indicesToDelete[i], 1);
  61804. }
  61805. for (var renderEffectName in this._renderEffects) {
  61806. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  61807. this._renderEffects[renderEffectName]._attachCameras(cams);
  61808. }
  61809. }
  61810. };
  61811. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  61812. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  61813. if (!cams) {
  61814. return;
  61815. }
  61816. for (var renderEffectName in this._renderEffects) {
  61817. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  61818. this._renderEffects[renderEffectName]._detachCameras(cams);
  61819. }
  61820. }
  61821. for (var i = 0; i < cams.length; i++) {
  61822. this._cameras.splice(this._cameras.indexOf(cams[i]), 1);
  61823. }
  61824. };
  61825. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  61826. var _this = this;
  61827. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  61828. if (!cams) {
  61829. return;
  61830. }
  61831. var pass = null;
  61832. var renderEffectName;
  61833. for (renderEffectName in this._renderEffects) {
  61834. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  61835. pass = this._renderEffects[renderEffectName].getPass(passName);
  61836. if (pass != null) {
  61837. break;
  61838. }
  61839. }
  61840. }
  61841. if (pass === null) {
  61842. return;
  61843. }
  61844. for (renderEffectName in this._renderEffects) {
  61845. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  61846. this._renderEffects[renderEffectName]._disable(cams);
  61847. }
  61848. }
  61849. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  61850. for (var i = 0; i < cams.length; i++) {
  61851. var camera = cams[i];
  61852. var cameraName = camera.name;
  61853. 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); });
  61854. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  61855. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  61856. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  61857. }
  61858. };
  61859. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  61860. var _this = this;
  61861. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  61862. if (!cams) {
  61863. return;
  61864. }
  61865. for (var i = 0; i < cams.length; i++) {
  61866. var camera = cams[i];
  61867. var cameraName = camera.name;
  61868. 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); });
  61869. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  61870. }
  61871. for (var renderEffectName in this._renderEffects) {
  61872. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  61873. this._renderEffects[renderEffectName]._enable(cams);
  61874. }
  61875. }
  61876. };
  61877. PostProcessRenderPipeline.prototype._update = function () {
  61878. for (var renderEffectName in this._renderEffects) {
  61879. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  61880. this._renderEffects[renderEffectName]._update();
  61881. }
  61882. }
  61883. for (var i = 0; i < this._cameras.length; i++) {
  61884. var cameraName = this._cameras[i].name;
  61885. if (this._renderEffectsForIsolatedPass[cameraName]) {
  61886. this._renderEffectsForIsolatedPass[cameraName]._update();
  61887. }
  61888. }
  61889. };
  61890. PostProcessRenderPipeline.prototype._reset = function () {
  61891. this._renderEffects = {};
  61892. this._renderEffectsForIsolatedPass = new Array();
  61893. };
  61894. PostProcessRenderPipeline.prototype.dispose = function () {
  61895. // Must be implemented by children
  61896. };
  61897. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  61898. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  61899. __decorate([
  61900. BABYLON.serialize()
  61901. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  61902. return PostProcessRenderPipeline;
  61903. }());
  61904. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  61905. })(BABYLON || (BABYLON = {}));
  61906. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  61907. var BABYLON;
  61908. (function (BABYLON) {
  61909. var DepthRenderer = /** @class */ (function () {
  61910. function DepthRenderer(scene, type) {
  61911. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  61912. var _this = this;
  61913. this._scene = scene;
  61914. var engine = scene.getEngine();
  61915. // Render target
  61916. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  61917. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  61918. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  61919. this._depthMap.refreshRate = 1;
  61920. this._depthMap.renderParticles = false;
  61921. this._depthMap.renderList = null;
  61922. // set default depth value to 1.0 (far away)
  61923. this._depthMap.onClearObservable.add(function (engine) {
  61924. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  61925. });
  61926. // Custom render function
  61927. var renderSubMesh = function (subMesh) {
  61928. var mesh = subMesh.getRenderingMesh();
  61929. var scene = _this._scene;
  61930. var engine = scene.getEngine();
  61931. var material = subMesh.getMaterial();
  61932. if (!material) {
  61933. return;
  61934. }
  61935. // Culling and reverse (right handed system)
  61936. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  61937. // Managing instances
  61938. var batch = mesh._getInstancesRenderList(subMesh._id);
  61939. if (batch.mustReturn) {
  61940. return;
  61941. }
  61942. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  61943. if (_this.isReady(subMesh, hardwareInstancedRendering) && scene.activeCamera) {
  61944. engine.enableEffect(_this._effect);
  61945. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  61946. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  61947. _this._effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.minZ + scene.activeCamera.maxZ);
  61948. // Alpha test
  61949. if (material && material.needAlphaTesting()) {
  61950. var alphaTexture = material.getAlphaTestTexture();
  61951. if (alphaTexture) {
  61952. _this._effect.setTexture("diffuseSampler", alphaTexture);
  61953. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  61954. }
  61955. }
  61956. // Bones
  61957. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  61958. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  61959. }
  61960. // Draw
  61961. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  61962. }
  61963. };
  61964. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  61965. var index;
  61966. if (depthOnlySubMeshes.length) {
  61967. engine.setColorWrite(false);
  61968. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  61969. renderSubMesh(depthOnlySubMeshes.data[index]);
  61970. }
  61971. engine.setColorWrite(true);
  61972. }
  61973. for (index = 0; index < opaqueSubMeshes.length; index++) {
  61974. renderSubMesh(opaqueSubMeshes.data[index]);
  61975. }
  61976. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  61977. renderSubMesh(alphaTestSubMeshes.data[index]);
  61978. }
  61979. };
  61980. }
  61981. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  61982. var material = subMesh.getMaterial();
  61983. if (material.disableDepthWrite) {
  61984. return false;
  61985. }
  61986. var defines = [];
  61987. var attribs = [BABYLON.VertexBuffer.PositionKind];
  61988. var mesh = subMesh.getMesh();
  61989. // Alpha test
  61990. if (material && material.needAlphaTesting()) {
  61991. defines.push("#define ALPHATEST");
  61992. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  61993. attribs.push(BABYLON.VertexBuffer.UVKind);
  61994. defines.push("#define UV1");
  61995. }
  61996. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  61997. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  61998. defines.push("#define UV2");
  61999. }
  62000. }
  62001. // Bones
  62002. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  62003. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  62004. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  62005. if (mesh.numBoneInfluencers > 4) {
  62006. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  62007. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  62008. }
  62009. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  62010. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  62011. }
  62012. else {
  62013. defines.push("#define NUM_BONE_INFLUENCERS 0");
  62014. }
  62015. // Instances
  62016. if (useInstances) {
  62017. defines.push("#define INSTANCES");
  62018. attribs.push("world0");
  62019. attribs.push("world1");
  62020. attribs.push("world2");
  62021. attribs.push("world3");
  62022. }
  62023. // Get correct effect
  62024. var join = defines.join("\n");
  62025. if (this._cachedDefines !== join) {
  62026. this._cachedDefines = join;
  62027. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "depthValues"], ["diffuseSampler"], join);
  62028. }
  62029. return this._effect.isReady();
  62030. };
  62031. DepthRenderer.prototype.getDepthMap = function () {
  62032. return this._depthMap;
  62033. };
  62034. // Methods
  62035. DepthRenderer.prototype.dispose = function () {
  62036. this._depthMap.dispose();
  62037. };
  62038. return DepthRenderer;
  62039. }());
  62040. BABYLON.DepthRenderer = DepthRenderer;
  62041. })(BABYLON || (BABYLON = {}));
  62042. //# sourceMappingURL=babylon.depthRenderer.js.map
  62043. var BABYLON;
  62044. (function (BABYLON) {
  62045. var SSAORenderingPipeline = /** @class */ (function (_super) {
  62046. __extends(SSAORenderingPipeline, _super);
  62047. /**
  62048. * @constructor
  62049. * @param {string} name - The rendering pipeline name
  62050. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  62051. * @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 }
  62052. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  62053. */
  62054. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  62055. var _this = _super.call(this, scene.getEngine(), name) || this;
  62056. // Members
  62057. /**
  62058. * The PassPostProcess id in the pipeline that contains the original scene color
  62059. * @type {string}
  62060. */
  62061. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  62062. /**
  62063. * The SSAO PostProcess id in the pipeline
  62064. * @type {string}
  62065. */
  62066. _this.SSAORenderEffect = "SSAORenderEffect";
  62067. /**
  62068. * The horizontal blur PostProcess id in the pipeline
  62069. * @type {string}
  62070. */
  62071. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  62072. /**
  62073. * The vertical blur PostProcess id in the pipeline
  62074. * @type {string}
  62075. */
  62076. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  62077. /**
  62078. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  62079. * @type {string}
  62080. */
  62081. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  62082. /**
  62083. * The output strength of the SSAO post-process. Default value is 1.0.
  62084. * @type {number}
  62085. */
  62086. _this.totalStrength = 1.0;
  62087. /**
  62088. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  62089. * @type {number}
  62090. */
  62091. _this.radius = 0.0001;
  62092. /**
  62093. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  62094. * Must not be equal to fallOff and superior to fallOff.
  62095. * Default value is 0.975
  62096. * @type {number}
  62097. */
  62098. _this.area = 0.0075;
  62099. /**
  62100. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  62101. * Must not be equal to area and inferior to area.
  62102. * Default value is 0.0
  62103. * @type {number}
  62104. */
  62105. _this.fallOff = 0.000001;
  62106. /**
  62107. * The base color of the SSAO post-process
  62108. * The final result is "base + ssao" between [0, 1]
  62109. * @type {number}
  62110. */
  62111. _this.base = 0.5;
  62112. _this._firstUpdate = true;
  62113. _this._scene = scene;
  62114. // Set up assets
  62115. _this._createRandomTexture();
  62116. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  62117. var ssaoRatio = ratio.ssaoRatio || ratio;
  62118. var combineRatio = ratio.combineRatio || ratio;
  62119. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  62120. _this._createSSAOPostProcess(ssaoRatio);
  62121. _this._createBlurPostProcess(ssaoRatio);
  62122. _this._createSSAOCombinePostProcess(combineRatio);
  62123. // Set up pipeline
  62124. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  62125. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  62126. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  62127. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  62128. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  62129. // Finish
  62130. scene.postProcessRenderPipelineManager.addPipeline(_this);
  62131. if (cameras)
  62132. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  62133. return _this;
  62134. }
  62135. // Public Methods
  62136. /**
  62137. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  62138. */
  62139. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  62140. if (disableDepthRender === void 0) { disableDepthRender = false; }
  62141. for (var i = 0; i < this._scene.cameras.length; i++) {
  62142. var camera = this._scene.cameras[i];
  62143. this._originalColorPostProcess.dispose(camera);
  62144. this._ssaoPostProcess.dispose(camera);
  62145. this._blurHPostProcess.dispose(camera);
  62146. this._blurVPostProcess.dispose(camera);
  62147. this._ssaoCombinePostProcess.dispose(camera);
  62148. }
  62149. this._randomTexture.dispose();
  62150. if (disableDepthRender)
  62151. this._scene.disableDepthRenderer();
  62152. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  62153. _super.prototype.dispose.call(this);
  62154. };
  62155. // Private Methods
  62156. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  62157. var _this = this;
  62158. var size = 16;
  62159. this._blurHPostProcess = new BABYLON.BlurPostProcess("BlurH", new BABYLON.Vector2(1, 0), size, ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  62160. this._blurVPostProcess = new BABYLON.BlurPostProcess("BlurV", new BABYLON.Vector2(0, 1), size, ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  62161. this._blurHPostProcess.onActivateObservable.add(function () {
  62162. var dw = _this._blurHPostProcess.width / _this._scene.getEngine().getRenderWidth();
  62163. _this._blurHPostProcess.kernel = size * dw;
  62164. });
  62165. this._blurVPostProcess.onActivateObservable.add(function () {
  62166. var dw = _this._blurVPostProcess.height / _this._scene.getEngine().getRenderHeight();
  62167. _this._blurVPostProcess.kernel = size * dw;
  62168. });
  62169. };
  62170. SSAORenderingPipeline.prototype._rebuild = function () {
  62171. this._firstUpdate = true;
  62172. _super.prototype._rebuild.call(this);
  62173. };
  62174. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  62175. var _this = this;
  62176. var numSamples = 16;
  62177. var sampleSphere = [
  62178. 0.5381, 0.1856, -0.4319,
  62179. 0.1379, 0.2486, 0.4430,
  62180. 0.3371, 0.5679, -0.0057,
  62181. -0.6999, -0.0451, -0.0019,
  62182. 0.0689, -0.1598, -0.8547,
  62183. 0.0560, 0.0069, -0.1843,
  62184. -0.0146, 0.1402, 0.0762,
  62185. 0.0100, -0.1924, -0.0344,
  62186. -0.3577, -0.5301, -0.4358,
  62187. -0.3169, 0.1063, 0.0158,
  62188. 0.0103, -0.5869, 0.0046,
  62189. -0.0897, -0.4940, 0.3287,
  62190. 0.7119, -0.0154, -0.0918,
  62191. -0.0533, 0.0596, -0.5411,
  62192. 0.0352, -0.0631, 0.5460,
  62193. -0.4776, 0.2847, -0.0271
  62194. ];
  62195. var samplesFactor = 1.0 / numSamples;
  62196. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  62197. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  62198. "area", "fallOff", "base", "range", "viewport"
  62199. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  62200. this._ssaoPostProcess.onApply = function (effect) {
  62201. if (_this._firstUpdate) {
  62202. effect.setArray3("sampleSphere", sampleSphere);
  62203. effect.setFloat("samplesFactor", samplesFactor);
  62204. effect.setFloat("randTextureTiles", 4.0);
  62205. }
  62206. effect.setFloat("totalStrength", _this.totalStrength);
  62207. effect.setFloat("radius", _this.radius);
  62208. effect.setFloat("area", _this.area);
  62209. effect.setFloat("fallOff", _this.fallOff);
  62210. effect.setFloat("base", _this.base);
  62211. effect.setTexture("textureSampler", _this._depthTexture);
  62212. effect.setTexture("randomSampler", _this._randomTexture);
  62213. };
  62214. };
  62215. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  62216. var _this = this;
  62217. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  62218. this._ssaoCombinePostProcess.onApply = function (effect) {
  62219. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  62220. };
  62221. };
  62222. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  62223. var size = 512;
  62224. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  62225. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  62226. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  62227. var context = this._randomTexture.getContext();
  62228. var rand = function (min, max) {
  62229. return Math.random() * (max - min) + min;
  62230. };
  62231. var randVector = BABYLON.Vector3.Zero();
  62232. for (var x = 0; x < size; x++) {
  62233. for (var y = 0; y < size; y++) {
  62234. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  62235. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  62236. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  62237. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  62238. context.fillRect(x, y, 1, 1);
  62239. }
  62240. }
  62241. this._randomTexture.update(false);
  62242. };
  62243. __decorate([
  62244. BABYLON.serialize()
  62245. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  62246. __decorate([
  62247. BABYLON.serialize()
  62248. ], SSAORenderingPipeline.prototype, "radius", void 0);
  62249. __decorate([
  62250. BABYLON.serialize()
  62251. ], SSAORenderingPipeline.prototype, "area", void 0);
  62252. __decorate([
  62253. BABYLON.serialize()
  62254. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  62255. __decorate([
  62256. BABYLON.serialize()
  62257. ], SSAORenderingPipeline.prototype, "base", void 0);
  62258. return SSAORenderingPipeline;
  62259. }(BABYLON.PostProcessRenderPipeline));
  62260. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  62261. })(BABYLON || (BABYLON = {}));
  62262. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  62263. var BABYLON;
  62264. (function (BABYLON) {
  62265. var SSAO2RenderingPipeline = /** @class */ (function (_super) {
  62266. __extends(SSAO2RenderingPipeline, _super);
  62267. /**
  62268. * @constructor
  62269. * @param {string} name - The rendering pipeline name
  62270. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  62271. * @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 }
  62272. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  62273. */
  62274. function SSAO2RenderingPipeline(name, scene, ratio, cameras) {
  62275. var _this = _super.call(this, scene.getEngine(), name) || this;
  62276. // Members
  62277. /**
  62278. * The PassPostProcess id in the pipeline that contains the original scene color
  62279. * @type {string}
  62280. */
  62281. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  62282. /**
  62283. * The SSAO PostProcess id in the pipeline
  62284. * @type {string}
  62285. */
  62286. _this.SSAORenderEffect = "SSAORenderEffect";
  62287. /**
  62288. * The horizontal blur PostProcess id in the pipeline
  62289. * @type {string}
  62290. */
  62291. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  62292. /**
  62293. * The vertical blur PostProcess id in the pipeline
  62294. * @type {string}
  62295. */
  62296. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  62297. /**
  62298. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  62299. * @type {string}
  62300. */
  62301. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  62302. /**
  62303. * The output strength of the SSAO post-process. Default value is 1.0.
  62304. * @type {number}
  62305. */
  62306. _this.totalStrength = 1.0;
  62307. /**
  62308. * Maximum depth value to still render AO. A smooth falloff makes the dimming more natural, so there will be no abrupt shading change.
  62309. * @type {number}
  62310. */
  62311. _this.maxZ = 100.0;
  62312. /**
  62313. * In order to save performances, SSAO radius is clamped on close geometry. This ratio changes by how much
  62314. * @type {number}
  62315. */
  62316. _this.minZAspect = 0.2;
  62317. /**
  62318. * Number of samples used for the SSAO calculations. Default value is 8
  62319. * @type {number}
  62320. */
  62321. _this._samples = 8;
  62322. /**
  62323. * Are we using bilateral blur ?
  62324. * @type {boolean}
  62325. */
  62326. _this._expensiveBlur = true;
  62327. /**
  62328. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 2.0
  62329. * @type {number}
  62330. */
  62331. _this.radius = 2.0;
  62332. /**
  62333. * The base color of the SSAO post-process
  62334. * The final result is "base + ssao" between [0, 1]
  62335. * @type {number}
  62336. */
  62337. _this.base = 0.1;
  62338. _this._firstUpdate = true;
  62339. _this._scene = scene;
  62340. if (!_this.isSupported) {
  62341. BABYLON.Tools.Error("SSAO 2 needs WebGL 2 support.");
  62342. return _this;
  62343. }
  62344. var ssaoRatio = ratio.ssaoRatio || ratio;
  62345. var blurRatio = ratio.blurRatio || ratio;
  62346. // Set up assets
  62347. var geometryBufferRenderer = scene.enableGeometryBufferRenderer();
  62348. _this._createRandomTexture();
  62349. _this._depthTexture = geometryBufferRenderer.getGBuffer().textures[0];
  62350. _this._normalTexture = geometryBufferRenderer.getGBuffer().textures[1];
  62351. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  62352. _this._createSSAOPostProcess(1.0);
  62353. _this._createBlurPostProcess(ssaoRatio, blurRatio);
  62354. _this._createSSAOCombinePostProcess(blurRatio);
  62355. // Set up pipeline
  62356. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  62357. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  62358. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  62359. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  62360. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  62361. // Finish
  62362. scene.postProcessRenderPipelineManager.addPipeline(_this);
  62363. if (cameras)
  62364. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  62365. return _this;
  62366. }
  62367. Object.defineProperty(SSAO2RenderingPipeline.prototype, "samples", {
  62368. get: function () {
  62369. return this._samples;
  62370. },
  62371. set: function (n) {
  62372. this._ssaoPostProcess.updateEffect("#define SAMPLES " + n + "\n#define SSAO");
  62373. this._samples = n;
  62374. this._sampleSphere = this._generateHemisphere();
  62375. this._firstUpdate = true;
  62376. },
  62377. enumerable: true,
  62378. configurable: true
  62379. });
  62380. Object.defineProperty(SSAO2RenderingPipeline.prototype, "expensiveBlur", {
  62381. get: function () {
  62382. return this._expensiveBlur;
  62383. },
  62384. set: function (b) {
  62385. 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"]);
  62386. this._blurVPostProcess.updateEffect("#define BILATERAL_BLUR\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  62387. this._expensiveBlur = b;
  62388. this._firstUpdate = true;
  62389. },
  62390. enumerable: true,
  62391. configurable: true
  62392. });
  62393. Object.defineProperty(SSAO2RenderingPipeline, "IsSupported", {
  62394. /**
  62395. * Support test.
  62396. * @type {boolean}
  62397. */
  62398. get: function () {
  62399. var engine = BABYLON.Engine.LastCreatedEngine;
  62400. if (!engine) {
  62401. return false;
  62402. }
  62403. return engine.getCaps().drawBuffersExtension;
  62404. },
  62405. enumerable: true,
  62406. configurable: true
  62407. });
  62408. // Public Methods
  62409. /**
  62410. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  62411. */
  62412. SSAO2RenderingPipeline.prototype.dispose = function (disableGeometryBufferRenderer) {
  62413. if (disableGeometryBufferRenderer === void 0) { disableGeometryBufferRenderer = false; }
  62414. for (var i = 0; i < this._scene.cameras.length; i++) {
  62415. var camera = this._scene.cameras[i];
  62416. this._originalColorPostProcess.dispose(camera);
  62417. this._ssaoPostProcess.dispose(camera);
  62418. this._blurHPostProcess.dispose(camera);
  62419. this._blurVPostProcess.dispose(camera);
  62420. this._ssaoCombinePostProcess.dispose(camera);
  62421. }
  62422. this._randomTexture.dispose();
  62423. if (disableGeometryBufferRenderer)
  62424. this._scene.disableGeometryBufferRenderer();
  62425. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  62426. _super.prototype.dispose.call(this);
  62427. };
  62428. // Private Methods
  62429. SSAO2RenderingPipeline.prototype._createBlurPostProcess = function (ssaoRatio, blurRatio) {
  62430. var _this = this;
  62431. this._samplerOffsets = [];
  62432. var expensive = this.expensiveBlur;
  62433. for (var i = -8; i < 8; i++) {
  62434. this._samplerOffsets.push(i * 2 + 0.5);
  62435. }
  62436. 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");
  62437. this._blurHPostProcess.onApply = function (effect) {
  62438. if (!_this._scene.activeCamera) {
  62439. return;
  62440. }
  62441. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width > 0 ? _this._ssaoCombinePostProcess.width : _this._originalColorPostProcess.width);
  62442. effect.setFloat("near", _this._scene.activeCamera.minZ);
  62443. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  62444. effect.setFloat("radius", _this.radius);
  62445. effect.setTexture("depthSampler", _this._depthTexture);
  62446. if (_this._firstUpdate) {
  62447. effect.setArray("samplerOffsets", _this._samplerOffsets);
  62448. }
  62449. };
  62450. 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");
  62451. this._blurVPostProcess.onApply = function (effect) {
  62452. if (!_this._scene.activeCamera) {
  62453. return;
  62454. }
  62455. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height > 0 ? _this._ssaoCombinePostProcess.height : _this._originalColorPostProcess.height);
  62456. effect.setFloat("near", _this._scene.activeCamera.minZ);
  62457. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  62458. effect.setFloat("radius", _this.radius);
  62459. effect.setTexture("depthSampler", _this._depthTexture);
  62460. if (_this._firstUpdate) {
  62461. effect.setArray("samplerOffsets", _this._samplerOffsets);
  62462. _this._firstUpdate = false;
  62463. }
  62464. };
  62465. };
  62466. SSAO2RenderingPipeline.prototype._rebuild = function () {
  62467. this._firstUpdate = true;
  62468. _super.prototype._rebuild.call(this);
  62469. };
  62470. SSAO2RenderingPipeline.prototype._generateHemisphere = function () {
  62471. var numSamples = this.samples;
  62472. var result = [];
  62473. var vector, scale;
  62474. var rand = function (min, max) {
  62475. return Math.random() * (max - min) + min;
  62476. };
  62477. var i = 0;
  62478. while (i < numSamples) {
  62479. vector = new BABYLON.Vector3(rand(-1.0, 1.0), rand(-1.0, 1.0), rand(0.30, 1.0));
  62480. vector.normalize();
  62481. scale = i / numSamples;
  62482. scale = BABYLON.Scalar.Lerp(0.1, 1.0, scale * scale);
  62483. vector.scaleInPlace(scale);
  62484. result.push(vector.x, vector.y, vector.z);
  62485. i++;
  62486. }
  62487. return result;
  62488. };
  62489. SSAO2RenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  62490. var _this = this;
  62491. var numSamples = this.samples;
  62492. this._sampleSphere = this._generateHemisphere();
  62493. this._ssaoPostProcess = new BABYLON.PostProcess("ssao2", "ssao2", [
  62494. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  62495. "base", "range", "projection", "near", "far", "texelSize",
  62496. "xViewport", "yViewport", "maxZ", "minZAspect"
  62497. ], ["randomSampler", "normalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  62498. this._ssaoPostProcess.onApply = function (effect) {
  62499. if (_this._firstUpdate) {
  62500. effect.setArray3("sampleSphere", _this._sampleSphere);
  62501. effect.setFloat("randTextureTiles", 4.0);
  62502. }
  62503. if (!_this._scene.activeCamera) {
  62504. return;
  62505. }
  62506. effect.setFloat("samplesFactor", 1 / _this.samples);
  62507. effect.setFloat("totalStrength", _this.totalStrength);
  62508. effect.setFloat2("texelSize", 1 / _this._ssaoPostProcess.width, 1 / _this._ssaoPostProcess.height);
  62509. effect.setFloat("radius", _this.radius);
  62510. effect.setFloat("maxZ", _this.maxZ);
  62511. effect.setFloat("minZAspect", _this.minZAspect);
  62512. effect.setFloat("base", _this.base);
  62513. effect.setFloat("near", _this._scene.activeCamera.minZ);
  62514. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  62515. effect.setFloat("xViewport", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.getEngine().getAspectRatio(_this._scene.activeCamera, true));
  62516. effect.setFloat("yViewport", Math.tan(_this._scene.activeCamera.fov / 2));
  62517. effect.setMatrix("projection", _this._scene.getProjectionMatrix());
  62518. effect.setTexture("textureSampler", _this._depthTexture);
  62519. effect.setTexture("normalSampler", _this._normalTexture);
  62520. effect.setTexture("randomSampler", _this._randomTexture);
  62521. };
  62522. };
  62523. SSAO2RenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  62524. var _this = this;
  62525. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  62526. this._ssaoCombinePostProcess.onApply = function (effect) {
  62527. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  62528. };
  62529. };
  62530. SSAO2RenderingPipeline.prototype._createRandomTexture = function () {
  62531. var size = 512;
  62532. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  62533. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  62534. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  62535. var context = this._randomTexture.getContext();
  62536. var rand = function (min, max) {
  62537. return Math.random() * (max - min) + min;
  62538. };
  62539. var randVector = BABYLON.Vector3.Zero();
  62540. for (var x = 0; x < size; x++) {
  62541. for (var y = 0; y < size; y++) {
  62542. randVector.x = rand(0.0, 1.0);
  62543. randVector.y = rand(0.0, 1.0);
  62544. randVector.z = 0.0;
  62545. randVector.normalize();
  62546. randVector.scaleInPlace(255);
  62547. randVector.x = Math.floor(randVector.x);
  62548. randVector.y = Math.floor(randVector.y);
  62549. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  62550. context.fillRect(x, y, 1, 1);
  62551. }
  62552. }
  62553. this._randomTexture.update(false);
  62554. };
  62555. __decorate([
  62556. BABYLON.serialize()
  62557. ], SSAO2RenderingPipeline.prototype, "totalStrength", void 0);
  62558. __decorate([
  62559. BABYLON.serialize()
  62560. ], SSAO2RenderingPipeline.prototype, "maxZ", void 0);
  62561. __decorate([
  62562. BABYLON.serialize()
  62563. ], SSAO2RenderingPipeline.prototype, "minZAspect", void 0);
  62564. __decorate([
  62565. BABYLON.serialize("samples")
  62566. ], SSAO2RenderingPipeline.prototype, "_samples", void 0);
  62567. __decorate([
  62568. BABYLON.serialize("expensiveBlur")
  62569. ], SSAO2RenderingPipeline.prototype, "_expensiveBlur", void 0);
  62570. __decorate([
  62571. BABYLON.serialize()
  62572. ], SSAO2RenderingPipeline.prototype, "radius", void 0);
  62573. __decorate([
  62574. BABYLON.serialize()
  62575. ], SSAO2RenderingPipeline.prototype, "base", void 0);
  62576. return SSAO2RenderingPipeline;
  62577. }(BABYLON.PostProcessRenderPipeline));
  62578. BABYLON.SSAO2RenderingPipeline = SSAO2RenderingPipeline;
  62579. })(BABYLON || (BABYLON = {}));
  62580. //# sourceMappingURL=babylon.ssao2RenderingPipeline.js.map
  62581. // BABYLON.JS Chromatic Aberration GLSL Shader
  62582. // Author: Olivier Guyot
  62583. // Separates very slightly R, G and B colors on the edges of the screen
  62584. // Inspired by Francois Tarlier & Martins Upitis
  62585. var BABYLON;
  62586. (function (BABYLON) {
  62587. var LensRenderingPipeline = /** @class */ (function (_super) {
  62588. __extends(LensRenderingPipeline, _super);
  62589. /**
  62590. * @constructor
  62591. *
  62592. * Effect parameters are as follow:
  62593. * {
  62594. * chromatic_aberration: number; // from 0 to x (1 for realism)
  62595. * edge_blur: number; // from 0 to x (1 for realism)
  62596. * distortion: number; // from 0 to x (1 for realism)
  62597. * grain_amount: number; // from 0 to 1
  62598. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  62599. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  62600. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  62601. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  62602. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  62603. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  62604. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  62605. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  62606. * }
  62607. * Note: if an effect parameter is unset, effect is disabled
  62608. *
  62609. * @param {string} name - The rendering pipeline name
  62610. * @param {object} parameters - An object containing all parameters (see above)
  62611. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  62612. * @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)
  62613. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  62614. */
  62615. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  62616. if (ratio === void 0) { ratio = 1.0; }
  62617. var _this = _super.call(this, scene.getEngine(), name) || this;
  62618. // Lens effects can be of the following:
  62619. // - chromatic aberration (slight shift of RGB colors)
  62620. // - blur on the edge of the lens
  62621. // - lens distortion
  62622. // - depth-of-field blur & highlights enhancing
  62623. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  62624. // - grain effect (noise or custom texture)
  62625. // Two additional texture samplers are needed:
  62626. // - depth map (for depth-of-field)
  62627. // - grain texture
  62628. /**
  62629. * The chromatic aberration PostProcess id in the pipeline
  62630. * @type {string}
  62631. */
  62632. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  62633. /**
  62634. * The highlights enhancing PostProcess id in the pipeline
  62635. * @type {string}
  62636. */
  62637. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  62638. /**
  62639. * The depth-of-field PostProcess id in the pipeline
  62640. * @type {string}
  62641. */
  62642. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  62643. _this._scene = scene;
  62644. // Fetch texture samplers
  62645. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  62646. if (parameters.grain_texture) {
  62647. _this._grainTexture = parameters.grain_texture;
  62648. }
  62649. else {
  62650. _this._createGrainTexture();
  62651. }
  62652. // save parameters
  62653. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  62654. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  62655. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  62656. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  62657. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  62658. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  62659. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  62660. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  62661. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  62662. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  62663. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  62664. // Create effects
  62665. _this._createChromaticAberrationPostProcess(ratio);
  62666. _this._createHighlightsPostProcess(ratio);
  62667. _this._createDepthOfFieldPostProcess(ratio / 4);
  62668. // Set up pipeline
  62669. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  62670. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  62671. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  62672. if (_this._highlightsGain === -1) {
  62673. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  62674. }
  62675. // Finish
  62676. scene.postProcessRenderPipelineManager.addPipeline(_this);
  62677. if (cameras) {
  62678. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  62679. }
  62680. return _this;
  62681. }
  62682. // public methods (self explanatory)
  62683. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  62684. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  62685. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  62686. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  62687. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  62688. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  62689. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  62690. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  62691. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  62692. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  62693. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  62694. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  62695. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  62696. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  62697. };
  62698. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  62699. this._highlightsPostProcess.updateEffect();
  62700. };
  62701. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  62702. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  62703. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  62704. this._highlightsGain = amount;
  62705. };
  62706. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  62707. if (this._highlightsGain === -1) {
  62708. this._highlightsGain = 1.0;
  62709. }
  62710. this._highlightsThreshold = amount;
  62711. };
  62712. LensRenderingPipeline.prototype.disableHighlights = function () {
  62713. this._highlightsGain = -1;
  62714. };
  62715. /**
  62716. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  62717. */
  62718. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  62719. if (disableDepthRender === void 0) { disableDepthRender = false; }
  62720. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  62721. this._chromaticAberrationPostProcess = null;
  62722. this._highlightsPostProcess = null;
  62723. this._depthOfFieldPostProcess = null;
  62724. this._grainTexture.dispose();
  62725. if (disableDepthRender)
  62726. this._scene.disableDepthRenderer();
  62727. };
  62728. // colors shifting and distortion
  62729. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  62730. var _this = this;
  62731. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height"], // uniforms
  62732. [], // samplers
  62733. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  62734. this._chromaticAberrationPostProcess.onApply = function (effect) {
  62735. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  62736. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  62737. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  62738. };
  62739. };
  62740. // highlights enhancing
  62741. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  62742. var _this = this;
  62743. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  62744. [], // samplers
  62745. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  62746. this._highlightsPostProcess.onApply = function (effect) {
  62747. effect.setFloat('gain', _this._highlightsGain);
  62748. effect.setFloat('threshold', _this._highlightsThreshold);
  62749. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  62750. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  62751. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  62752. };
  62753. };
  62754. // colors shifting and distortion
  62755. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  62756. var _this = this;
  62757. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  62758. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  62759. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  62760. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  62761. this._depthOfFieldPostProcess.onApply = function (effect) {
  62762. effect.setTexture("depthSampler", _this._depthTexture);
  62763. effect.setTexture("grainSampler", _this._grainTexture);
  62764. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  62765. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  62766. effect.setFloat('grain_amount', _this._grainAmount);
  62767. effect.setBool('blur_noise', _this._blurNoise);
  62768. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  62769. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  62770. effect.setFloat('distortion', _this._distortion);
  62771. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  62772. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  62773. effect.setFloat('aperture', _this._dofAperture);
  62774. effect.setFloat('darken', _this._dofDarken);
  62775. effect.setFloat('edge_blur', _this._edgeBlur);
  62776. effect.setBool('highlights', (_this._highlightsGain !== -1));
  62777. if (_this._scene.activeCamera) {
  62778. effect.setFloat('near', _this._scene.activeCamera.minZ);
  62779. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  62780. }
  62781. };
  62782. };
  62783. // creates a black and white random noise texture, 512x512
  62784. LensRenderingPipeline.prototype._createGrainTexture = function () {
  62785. var size = 512;
  62786. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  62787. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  62788. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  62789. var context = this._grainTexture.getContext();
  62790. var rand = function (min, max) {
  62791. return Math.random() * (max - min) + min;
  62792. };
  62793. var value;
  62794. for (var x = 0; x < size; x++) {
  62795. for (var y = 0; y < size; y++) {
  62796. value = Math.floor(rand(0.42, 0.58) * 255);
  62797. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  62798. context.fillRect(x, y, 1, 1);
  62799. }
  62800. }
  62801. this._grainTexture.update(false);
  62802. };
  62803. return LensRenderingPipeline;
  62804. }(BABYLON.PostProcessRenderPipeline));
  62805. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  62806. })(BABYLON || (BABYLON = {}));
  62807. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  62808. var BABYLON;
  62809. (function (BABYLON) {
  62810. var StandardRenderingPipeline = /** @class */ (function (_super) {
  62811. __extends(StandardRenderingPipeline, _super);
  62812. /**
  62813. * @constructor
  62814. * @param {string} name - The rendering pipeline name
  62815. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  62816. * @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)
  62817. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  62818. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  62819. */
  62820. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  62821. if (originalPostProcess === void 0) { originalPostProcess = null; }
  62822. var _this = _super.call(this, scene.getEngine(), name) || this;
  62823. _this.downSampleX4PostProcess = null;
  62824. _this.brightPassPostProcess = null;
  62825. _this.blurHPostProcesses = [];
  62826. _this.blurVPostProcesses = [];
  62827. _this.textureAdderPostProcess = null;
  62828. _this.volumetricLightPostProcess = null;
  62829. _this.volumetricLightSmoothXPostProcess = null;
  62830. _this.volumetricLightSmoothYPostProcess = null;
  62831. _this.volumetricLightMergePostProces = null;
  62832. _this.volumetricLightFinalPostProcess = null;
  62833. _this.luminancePostProcess = null;
  62834. _this.luminanceDownSamplePostProcesses = [];
  62835. _this.hdrPostProcess = null;
  62836. _this.textureAdderFinalPostProcess = null;
  62837. _this.lensFlareFinalPostProcess = null;
  62838. _this.hdrFinalPostProcess = null;
  62839. _this.lensFlarePostProcess = null;
  62840. _this.lensFlareComposePostProcess = null;
  62841. _this.motionBlurPostProcess = null;
  62842. _this.depthOfFieldPostProcess = null;
  62843. // Values
  62844. _this.brightThreshold = 1.0;
  62845. _this.blurWidth = 512.0;
  62846. _this.horizontalBlur = false;
  62847. _this.exposure = 1.0;
  62848. _this.lensTexture = null;
  62849. _this.volumetricLightCoefficient = 0.2;
  62850. _this.volumetricLightPower = 4.0;
  62851. _this.volumetricLightBlurScale = 64.0;
  62852. _this.sourceLight = null;
  62853. _this.hdrMinimumLuminance = 1.0;
  62854. _this.hdrDecreaseRate = 0.5;
  62855. _this.hdrIncreaseRate = 0.5;
  62856. _this.lensColorTexture = null;
  62857. _this.lensFlareStrength = 20.0;
  62858. _this.lensFlareGhostDispersal = 1.4;
  62859. _this.lensFlareHaloWidth = 0.7;
  62860. _this.lensFlareDistortionStrength = 16.0;
  62861. _this.lensStarTexture = null;
  62862. _this.lensFlareDirtTexture = null;
  62863. _this.depthOfFieldDistance = 10.0;
  62864. _this.depthOfFieldBlurWidth = 64.0;
  62865. _this.motionStrength = 1.0;
  62866. // IAnimatable
  62867. _this.animations = [];
  62868. _this._currentDepthOfFieldSource = null;
  62869. _this._hdrCurrentLuminance = 1.0;
  62870. // Getters and setters
  62871. _this._bloomEnabled = true;
  62872. _this._depthOfFieldEnabled = false;
  62873. _this._vlsEnabled = false;
  62874. _this._lensFlareEnabled = false;
  62875. _this._hdrEnabled = false;
  62876. _this._motionBlurEnabled = false;
  62877. _this._motionBlurSamples = 64.0;
  62878. _this._volumetricLightStepsCount = 50.0;
  62879. _this._cameras = cameras || [];
  62880. // Initialize
  62881. _this._scene = scene;
  62882. _this._basePostProcess = originalPostProcess;
  62883. _this._ratio = ratio;
  62884. // Misc
  62885. _this._floatTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  62886. // Finish
  62887. scene.postProcessRenderPipelineManager.addPipeline(_this);
  62888. _this._buildPipeline();
  62889. return _this;
  62890. }
  62891. Object.defineProperty(StandardRenderingPipeline.prototype, "BloomEnabled", {
  62892. get: function () {
  62893. return this._bloomEnabled;
  62894. },
  62895. set: function (enabled) {
  62896. if (this._bloomEnabled === enabled) {
  62897. return;
  62898. }
  62899. this._bloomEnabled = enabled;
  62900. this._buildPipeline();
  62901. },
  62902. enumerable: true,
  62903. configurable: true
  62904. });
  62905. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  62906. get: function () {
  62907. return this._depthOfFieldEnabled;
  62908. },
  62909. set: function (enabled) {
  62910. if (this._depthOfFieldEnabled === enabled) {
  62911. return;
  62912. }
  62913. this._depthOfFieldEnabled = enabled;
  62914. this._buildPipeline();
  62915. },
  62916. enumerable: true,
  62917. configurable: true
  62918. });
  62919. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  62920. get: function () {
  62921. return this._lensFlareEnabled;
  62922. },
  62923. set: function (enabled) {
  62924. if (this._lensFlareEnabled === enabled) {
  62925. return;
  62926. }
  62927. this._lensFlareEnabled = enabled;
  62928. this._buildPipeline();
  62929. },
  62930. enumerable: true,
  62931. configurable: true
  62932. });
  62933. Object.defineProperty(StandardRenderingPipeline.prototype, "HDREnabled", {
  62934. get: function () {
  62935. return this._hdrEnabled;
  62936. },
  62937. set: function (enabled) {
  62938. if (this._hdrEnabled === enabled) {
  62939. return;
  62940. }
  62941. this._hdrEnabled = enabled;
  62942. this._buildPipeline();
  62943. },
  62944. enumerable: true,
  62945. configurable: true
  62946. });
  62947. Object.defineProperty(StandardRenderingPipeline.prototype, "VLSEnabled", {
  62948. get: function () {
  62949. return this._vlsEnabled;
  62950. },
  62951. set: function (enabled) {
  62952. if (this._vlsEnabled === enabled) {
  62953. return;
  62954. }
  62955. if (enabled) {
  62956. var geometry = this._scene.enableGeometryBufferRenderer();
  62957. if (!geometry) {
  62958. BABYLON.Tools.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");
  62959. return;
  62960. }
  62961. }
  62962. this._vlsEnabled = enabled;
  62963. this._buildPipeline();
  62964. },
  62965. enumerable: true,
  62966. configurable: true
  62967. });
  62968. Object.defineProperty(StandardRenderingPipeline.prototype, "MotionBlurEnabled", {
  62969. get: function () {
  62970. return this._motionBlurEnabled;
  62971. },
  62972. set: function (enabled) {
  62973. if (this._motionBlurEnabled === enabled) {
  62974. return;
  62975. }
  62976. this._motionBlurEnabled = enabled;
  62977. this._buildPipeline();
  62978. },
  62979. enumerable: true,
  62980. configurable: true
  62981. });
  62982. Object.defineProperty(StandardRenderingPipeline.prototype, "volumetricLightStepsCount", {
  62983. get: function () {
  62984. return this._volumetricLightStepsCount;
  62985. },
  62986. set: function (count) {
  62987. if (this.volumetricLightPostProcess) {
  62988. this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS " + count.toFixed(1));
  62989. }
  62990. this._volumetricLightStepsCount = count;
  62991. },
  62992. enumerable: true,
  62993. configurable: true
  62994. });
  62995. Object.defineProperty(StandardRenderingPipeline.prototype, "motionBlurSamples", {
  62996. get: function () {
  62997. return this._motionBlurSamples;
  62998. },
  62999. set: function (samples) {
  63000. if (this.motionBlurPostProcess) {
  63001. this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + samples.toFixed(1));
  63002. }
  63003. this._motionBlurSamples = samples;
  63004. },
  63005. enumerable: true,
  63006. configurable: true
  63007. });
  63008. StandardRenderingPipeline.prototype._buildPipeline = function () {
  63009. var _this = this;
  63010. var ratio = this._ratio;
  63011. var scene = this._scene;
  63012. this._disposePostProcesses();
  63013. this._reset();
  63014. // Create pass post-process
  63015. if (!this._basePostProcess) {
  63016. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", this._floatTextureType);
  63017. this.originalPostProcess.onApply = function (effect) {
  63018. _this._currentDepthOfFieldSource = _this.originalPostProcess;
  63019. };
  63020. }
  63021. else {
  63022. this.originalPostProcess = this._basePostProcess;
  63023. }
  63024. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  63025. this._currentDepthOfFieldSource = this.originalPostProcess;
  63026. if (this._vlsEnabled) {
  63027. // Create volumetric light
  63028. this._createVolumetricLightPostProcess(scene, ratio);
  63029. // Create volumetric light final post-process
  63030. 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);
  63031. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSFinal", function () { return _this.volumetricLightFinalPostProcess; }, true));
  63032. }
  63033. if (this._bloomEnabled) {
  63034. // Create down sample X4 post-process
  63035. this._createDownSampleX4PostProcess(scene, ratio / 2);
  63036. // Create bright pass post-process
  63037. this._createBrightPassPostProcess(scene, ratio / 2);
  63038. // Create gaussian blur post-processes (down sampling blurs)
  63039. this._createBlurPostProcesses(scene, ratio / 4, 1);
  63040. // Create texture adder post-process
  63041. this._createTextureAdderPostProcess(scene, ratio);
  63042. // Create depth-of-field source post-process
  63043. 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);
  63044. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  63045. }
  63046. if (this._lensFlareEnabled) {
  63047. // Create lens flare post-process
  63048. this._createLensFlarePostProcess(scene, ratio);
  63049. // Create depth-of-field source post-process post lens-flare and disable it now
  63050. 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);
  63051. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  63052. }
  63053. if (this._hdrEnabled) {
  63054. // Create luminance
  63055. this._createLuminancePostProcesses(scene, this._floatTextureType);
  63056. // Create HDR
  63057. this._createHdrPostProcess(scene, ratio);
  63058. // Create depth-of-field source post-process post hdr and disable it now
  63059. 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);
  63060. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", function () { return _this.hdrFinalPostProcess; }, true));
  63061. }
  63062. if (this._depthOfFieldEnabled) {
  63063. // Create gaussian blur used by depth-of-field
  63064. this._createBlurPostProcesses(scene, ratio / 2, 3, "depthOfFieldBlurWidth");
  63065. // Create depth-of-field post-process
  63066. this._createDepthOfFieldPostProcess(scene, ratio);
  63067. }
  63068. if (this._motionBlurEnabled) {
  63069. // Create motion blur post-process
  63070. this._createMotionBlurPostProcess(scene, ratio);
  63071. }
  63072. if (this._cameras !== null) {
  63073. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  63074. }
  63075. };
  63076. // Down Sample X4 Post-Processs
  63077. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  63078. var _this = this;
  63079. var downSampleX4Offsets = new Array(32);
  63080. 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);
  63081. this.downSampleX4PostProcess.onApply = function (effect) {
  63082. var id = 0;
  63083. var width = _this.downSampleX4PostProcess.width;
  63084. var height = _this.downSampleX4PostProcess.height;
  63085. for (var i = -2; i < 2; i++) {
  63086. for (var j = -2; j < 2; j++) {
  63087. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / width);
  63088. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / height);
  63089. id += 2;
  63090. }
  63091. }
  63092. effect.setArray2("dsOffsets", downSampleX4Offsets);
  63093. };
  63094. // Add to pipeline
  63095. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  63096. };
  63097. // Brightpass Post-Process
  63098. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  63099. var _this = this;
  63100. var brightOffsets = new Array(8);
  63101. 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);
  63102. this.brightPassPostProcess.onApply = function (effect) {
  63103. var sU = (1.0 / _this.brightPassPostProcess.width);
  63104. var sV = (1.0 / _this.brightPassPostProcess.height);
  63105. brightOffsets[0] = -0.5 * sU;
  63106. brightOffsets[1] = 0.5 * sV;
  63107. brightOffsets[2] = 0.5 * sU;
  63108. brightOffsets[3] = 0.5 * sV;
  63109. brightOffsets[4] = -0.5 * sU;
  63110. brightOffsets[5] = -0.5 * sV;
  63111. brightOffsets[6] = 0.5 * sU;
  63112. brightOffsets[7] = -0.5 * sV;
  63113. effect.setArray2("dsOffsets", brightOffsets);
  63114. effect.setFloat("brightThreshold", _this.brightThreshold);
  63115. };
  63116. // Add to pipeline
  63117. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  63118. };
  63119. // Create blur H&V post-processes
  63120. StandardRenderingPipeline.prototype._createBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  63121. var _this = this;
  63122. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  63123. var engine = scene.getEngine();
  63124. 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);
  63125. 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);
  63126. blurX.onActivateObservable.add(function () {
  63127. var dw = blurX.width / engine.getRenderWidth();
  63128. blurX.kernel = _this[blurWidthKey] * dw;
  63129. });
  63130. blurY.onActivateObservable.add(function () {
  63131. var dw = blurY.height / engine.getRenderHeight();
  63132. blurY.kernel = _this.horizontalBlur ? 64 * dw : _this[blurWidthKey] * dw;
  63133. });
  63134. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurH" + indice, function () { return blurX; }, true));
  63135. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurV" + indice, function () { return blurY; }, true));
  63136. this.blurHPostProcesses.push(blurX);
  63137. this.blurVPostProcesses.push(blurY);
  63138. };
  63139. // Create texture adder post-process
  63140. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  63141. var _this = this;
  63142. 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);
  63143. this.textureAdderPostProcess.onApply = function (effect) {
  63144. effect.setTextureFromPostProcess("otherSampler", _this._vlsEnabled ? _this._currentDepthOfFieldSource : _this.originalPostProcess);
  63145. effect.setTexture("lensSampler", _this.lensTexture);
  63146. effect.setFloat("exposure", _this.exposure);
  63147. _this._currentDepthOfFieldSource = _this.textureAdderFinalPostProcess;
  63148. };
  63149. // Add to pipeline
  63150. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  63151. };
  63152. StandardRenderingPipeline.prototype._createVolumetricLightPostProcess = function (scene, ratio) {
  63153. var _this = this;
  63154. var geometryRenderer = scene.enableGeometryBufferRenderer();
  63155. geometryRenderer.enablePosition = true;
  63156. var geometry = geometryRenderer.getGBuffer();
  63157. // Base post-process
  63158. 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));
  63159. var depthValues = BABYLON.Vector2.Zero();
  63160. this.volumetricLightPostProcess.onApply = function (effect) {
  63161. if (_this.sourceLight && _this.sourceLight.getShadowGenerator() && _this._scene.activeCamera) {
  63162. var generator = _this.sourceLight.getShadowGenerator();
  63163. effect.setTexture("shadowMapSampler", generator.getShadowMap());
  63164. effect.setTexture("positionSampler", geometry.textures[2]);
  63165. effect.setColor3("sunColor", _this.sourceLight.diffuse);
  63166. effect.setVector3("sunDirection", _this.sourceLight.getShadowDirection());
  63167. effect.setVector3("cameraPosition", _this._scene.activeCamera.globalPosition);
  63168. effect.setMatrix("shadowViewProjection", generator.getTransformMatrix());
  63169. effect.setFloat("scatteringCoefficient", _this.volumetricLightCoefficient);
  63170. effect.setFloat("scatteringPower", _this.volumetricLightPower);
  63171. depthValues.x = generator.getLight().getDepthMinZ(_this._scene.activeCamera);
  63172. depthValues.y = generator.getLight().getDepthMaxZ(_this._scene.activeCamera);
  63173. effect.setVector2("depthValues", depthValues);
  63174. }
  63175. };
  63176. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLS", function () { return _this.volumetricLightPostProcess; }, true));
  63177. // Smooth
  63178. this._createBlurPostProcesses(scene, ratio / 4, 0, "volumetricLightBlurScale");
  63179. // Merge
  63180. this.volumetricLightMergePostProces = new BABYLON.PostProcess("HDRVLSMerge", "standard", [], ["originalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLSMERGE");
  63181. this.volumetricLightMergePostProces.onApply = function (effect) {
  63182. effect.setTextureFromPostProcess("originalSampler", _this.originalPostProcess);
  63183. _this._currentDepthOfFieldSource = _this.volumetricLightFinalPostProcess;
  63184. };
  63185. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSMerge", function () { return _this.volumetricLightMergePostProces; }, true));
  63186. };
  63187. // Create luminance
  63188. StandardRenderingPipeline.prototype._createLuminancePostProcesses = function (scene, textureType) {
  63189. var _this = this;
  63190. // Create luminance
  63191. var size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);
  63192. this.luminancePostProcess = new BABYLON.PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", textureType);
  63193. var offsets = [];
  63194. this.luminancePostProcess.onApply = function (effect) {
  63195. var sU = (1.0 / _this.luminancePostProcess.width);
  63196. var sV = (1.0 / _this.luminancePostProcess.height);
  63197. offsets[0] = -0.5 * sU;
  63198. offsets[1] = 0.5 * sV;
  63199. offsets[2] = 0.5 * sU;
  63200. offsets[3] = 0.5 * sV;
  63201. offsets[4] = -0.5 * sU;
  63202. offsets[5] = -0.5 * sV;
  63203. offsets[6] = 0.5 * sU;
  63204. offsets[7] = -0.5 * sV;
  63205. effect.setArray2("lumOffsets", offsets);
  63206. };
  63207. // Add to pipeline
  63208. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", function () { return _this.luminancePostProcess; }, true));
  63209. // Create down sample luminance
  63210. for (var i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) {
  63211. var size = Math.pow(3, i);
  63212. var defines = "#define LUMINANCE_DOWN_SAMPLE\n";
  63213. if (i === 0) {
  63214. defines += "#define FINAL_DOWN_SAMPLER";
  63215. }
  63216. var postProcess = new BABYLON.PostProcess("HDRLuminanceDownSample" + i, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType);
  63217. this.luminanceDownSamplePostProcesses.push(postProcess);
  63218. }
  63219. // Create callbacks and add effects
  63220. var lastLuminance = this.luminancePostProcess;
  63221. this.luminanceDownSamplePostProcesses.forEach(function (pp, index) {
  63222. var downSampleOffsets = new Array(18);
  63223. pp.onApply = function (effect) {
  63224. if (!lastLuminance) {
  63225. return;
  63226. }
  63227. var id = 0;
  63228. for (var x = -1; x < 2; x++) {
  63229. for (var y = -1; y < 2; y++) {
  63230. downSampleOffsets[id] = x / lastLuminance.width;
  63231. downSampleOffsets[id + 1] = y / lastLuminance.height;
  63232. id += 2;
  63233. }
  63234. }
  63235. effect.setArray2("dsOffsets", downSampleOffsets);
  63236. effect.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width);
  63237. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  63238. lastLuminance = _this.luminancePostProcess;
  63239. }
  63240. else {
  63241. lastLuminance = pp;
  63242. }
  63243. };
  63244. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  63245. pp.onAfterRender = function (effect) {
  63246. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  63247. 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);
  63248. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  63249. };
  63250. }
  63251. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, function () { return pp; }, true));
  63252. });
  63253. };
  63254. // Create HDR post-process
  63255. StandardRenderingPipeline.prototype._createHdrPostProcess = function (scene, ratio) {
  63256. var _this = this;
  63257. 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);
  63258. var outputLiminance = 1;
  63259. var time = 0;
  63260. var lastTime = 0;
  63261. this.hdrPostProcess.onApply = function (effect) {
  63262. effect.setTextureFromPostProcess("textureAdderSampler", _this._currentDepthOfFieldSource);
  63263. time += scene.getEngine().getDeltaTime();
  63264. if (outputLiminance < 0) {
  63265. outputLiminance = _this._hdrCurrentLuminance;
  63266. }
  63267. else {
  63268. var dt = (lastTime - time) / 1000.0;
  63269. if (_this._hdrCurrentLuminance < outputLiminance + _this.hdrDecreaseRate * dt) {
  63270. outputLiminance += _this.hdrDecreaseRate * dt;
  63271. }
  63272. else if (_this._hdrCurrentLuminance > outputLiminance - _this.hdrIncreaseRate * dt) {
  63273. outputLiminance -= _this.hdrIncreaseRate * dt;
  63274. }
  63275. else {
  63276. outputLiminance = _this._hdrCurrentLuminance;
  63277. }
  63278. }
  63279. outputLiminance = BABYLON.Scalar.Clamp(outputLiminance, _this.hdrMinimumLuminance, 1e20);
  63280. effect.setFloat("averageLuminance", outputLiminance);
  63281. lastTime = time;
  63282. _this._currentDepthOfFieldSource = _this.hdrFinalPostProcess;
  63283. };
  63284. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this.hdrPostProcess; }, true));
  63285. };
  63286. // Create lens flare post-process
  63287. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  63288. var _this = this;
  63289. 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);
  63290. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  63291. this._createBlurPostProcesses(scene, ratio / 4, 2);
  63292. 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);
  63293. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  63294. var resolution = new BABYLON.Vector2(0, 0);
  63295. // Lens flare
  63296. this.lensFlarePostProcess.onApply = function (effect) {
  63297. effect.setTextureFromPostProcess("textureSampler", _this._bloomEnabled ? _this.blurHPostProcesses[0] : _this.originalPostProcess);
  63298. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  63299. effect.setFloat("strength", _this.lensFlareStrength);
  63300. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  63301. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  63302. // Shift
  63303. resolution.x = _this.lensFlarePostProcess.width;
  63304. resolution.y = _this.lensFlarePostProcess.height;
  63305. effect.setVector2("resolution", resolution);
  63306. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  63307. };
  63308. // Compose
  63309. 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);
  63310. 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);
  63311. this.lensFlareComposePostProcess.onApply = function (effect) {
  63312. if (!_this._scene.activeCamera) {
  63313. return;
  63314. }
  63315. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  63316. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  63317. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  63318. // Lens start rotation matrix
  63319. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  63320. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  63321. 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));
  63322. camRot *= 4.0;
  63323. 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);
  63324. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  63325. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  63326. _this._currentDepthOfFieldSource = _this.lensFlareFinalPostProcess;
  63327. };
  63328. };
  63329. // Create depth-of-field post-process
  63330. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  63331. var _this = this;
  63332. 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);
  63333. this.depthOfFieldPostProcess.onApply = function (effect) {
  63334. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  63335. effect.setTexture("depthSampler", _this._getDepthTexture());
  63336. effect.setFloat("distance", _this.depthOfFieldDistance);
  63337. };
  63338. // Add to pipeline
  63339. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  63340. };
  63341. // Create motion blur post-process
  63342. StandardRenderingPipeline.prototype._createMotionBlurPostProcess = function (scene, ratio) {
  63343. var _this = this;
  63344. 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);
  63345. var motionScale = 0;
  63346. var prevViewProjection = BABYLON.Matrix.Identity();
  63347. var invViewProjection = BABYLON.Matrix.Identity();
  63348. var viewProjection = BABYLON.Matrix.Identity();
  63349. var screenSize = BABYLON.Vector2.Zero();
  63350. this.motionBlurPostProcess.onApply = function (effect) {
  63351. viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix());
  63352. viewProjection.invertToRef(invViewProjection);
  63353. effect.setMatrix("inverseViewProjection", invViewProjection);
  63354. effect.setMatrix("prevViewProjection", prevViewProjection);
  63355. prevViewProjection = viewProjection;
  63356. screenSize.x = _this.motionBlurPostProcess.width;
  63357. screenSize.y = _this.motionBlurPostProcess.height;
  63358. effect.setVector2("screenSize", screenSize);
  63359. motionScale = scene.getEngine().getFps() / 60.0;
  63360. effect.setFloat("motionScale", motionScale);
  63361. effect.setFloat("motionStrength", _this.motionStrength);
  63362. effect.setTexture("depthSampler", _this._getDepthTexture());
  63363. };
  63364. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRMotionBlur", function () { return _this.motionBlurPostProcess; }, true));
  63365. };
  63366. StandardRenderingPipeline.prototype._getDepthTexture = function () {
  63367. if (this._scene.getEngine().getCaps().drawBuffersExtension) {
  63368. var renderer = this._scene.enableGeometryBufferRenderer();
  63369. return renderer.getGBuffer().textures[0];
  63370. }
  63371. return this._scene.enableDepthRenderer().getDepthMap();
  63372. };
  63373. StandardRenderingPipeline.prototype._disposePostProcesses = function () {
  63374. for (var i = 0; i < this._cameras.length; i++) {
  63375. var camera = this._cameras[i];
  63376. if (this.originalPostProcess) {
  63377. this.originalPostProcess.dispose(camera);
  63378. }
  63379. if (this.downSampleX4PostProcess) {
  63380. this.downSampleX4PostProcess.dispose(camera);
  63381. }
  63382. if (this.brightPassPostProcess) {
  63383. this.brightPassPostProcess.dispose(camera);
  63384. }
  63385. if (this.textureAdderPostProcess) {
  63386. this.textureAdderPostProcess.dispose(camera);
  63387. }
  63388. if (this.textureAdderFinalPostProcess) {
  63389. this.textureAdderFinalPostProcess.dispose(camera);
  63390. }
  63391. if (this.volumetricLightPostProcess) {
  63392. this.volumetricLightPostProcess.dispose(camera);
  63393. }
  63394. if (this.volumetricLightSmoothXPostProcess) {
  63395. this.volumetricLightSmoothXPostProcess.dispose(camera);
  63396. }
  63397. if (this.volumetricLightSmoothYPostProcess) {
  63398. this.volumetricLightSmoothYPostProcess.dispose(camera);
  63399. }
  63400. if (this.volumetricLightMergePostProces) {
  63401. this.volumetricLightMergePostProces.dispose(camera);
  63402. }
  63403. if (this.volumetricLightFinalPostProcess) {
  63404. this.volumetricLightFinalPostProcess.dispose(camera);
  63405. }
  63406. if (this.lensFlarePostProcess) {
  63407. this.lensFlarePostProcess.dispose(camera);
  63408. }
  63409. if (this.lensFlareComposePostProcess) {
  63410. this.lensFlareComposePostProcess.dispose(camera);
  63411. }
  63412. for (var j = 0; j < this.luminanceDownSamplePostProcesses.length; j++) {
  63413. this.luminanceDownSamplePostProcesses[j].dispose(camera);
  63414. }
  63415. if (this.luminancePostProcess) {
  63416. this.luminancePostProcess.dispose(camera);
  63417. }
  63418. if (this.hdrPostProcess) {
  63419. this.hdrPostProcess.dispose(camera);
  63420. }
  63421. if (this.hdrFinalPostProcess) {
  63422. this.hdrFinalPostProcess.dispose(camera);
  63423. }
  63424. if (this.depthOfFieldPostProcess) {
  63425. this.depthOfFieldPostProcess.dispose(camera);
  63426. }
  63427. if (this.motionBlurPostProcess) {
  63428. this.motionBlurPostProcess.dispose(camera);
  63429. }
  63430. for (var j = 0; j < this.blurHPostProcesses.length; j++) {
  63431. this.blurHPostProcesses[j].dispose(camera);
  63432. }
  63433. for (var j = 0; j < this.blurVPostProcesses.length; j++) {
  63434. this.blurVPostProcesses[j].dispose(camera);
  63435. }
  63436. }
  63437. this.originalPostProcess = null;
  63438. this.downSampleX4PostProcess = null;
  63439. this.brightPassPostProcess = null;
  63440. this.textureAdderPostProcess = null;
  63441. this.textureAdderFinalPostProcess = null;
  63442. this.volumetricLightPostProcess = null;
  63443. this.volumetricLightSmoothXPostProcess = null;
  63444. this.volumetricLightSmoothYPostProcess = null;
  63445. this.volumetricLightMergePostProces = null;
  63446. this.volumetricLightFinalPostProcess = null;
  63447. this.lensFlarePostProcess = null;
  63448. this.lensFlareComposePostProcess = null;
  63449. this.luminancePostProcess = null;
  63450. this.hdrPostProcess = null;
  63451. this.hdrFinalPostProcess = null;
  63452. this.depthOfFieldPostProcess = null;
  63453. this.motionBlurPostProcess = null;
  63454. this.luminanceDownSamplePostProcesses = [];
  63455. this.blurHPostProcesses = [];
  63456. this.blurVPostProcesses = [];
  63457. };
  63458. // Dispose
  63459. StandardRenderingPipeline.prototype.dispose = function () {
  63460. this._disposePostProcesses();
  63461. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  63462. _super.prototype.dispose.call(this);
  63463. };
  63464. // Serialize rendering pipeline
  63465. StandardRenderingPipeline.prototype.serialize = function () {
  63466. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  63467. serializationObject.customType = "StandardRenderingPipeline";
  63468. return serializationObject;
  63469. };
  63470. /**
  63471. * Static members
  63472. */
  63473. // Parse serialized pipeline
  63474. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  63475. return BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  63476. };
  63477. // Luminance steps
  63478. StandardRenderingPipeline.LuminanceSteps = 6;
  63479. __decorate([
  63480. BABYLON.serialize()
  63481. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  63482. __decorate([
  63483. BABYLON.serialize()
  63484. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  63485. __decorate([
  63486. BABYLON.serialize()
  63487. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  63488. __decorate([
  63489. BABYLON.serialize()
  63490. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  63491. __decorate([
  63492. BABYLON.serializeAsTexture("lensTexture")
  63493. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  63494. __decorate([
  63495. BABYLON.serialize()
  63496. ], StandardRenderingPipeline.prototype, "volumetricLightCoefficient", void 0);
  63497. __decorate([
  63498. BABYLON.serialize()
  63499. ], StandardRenderingPipeline.prototype, "volumetricLightPower", void 0);
  63500. __decorate([
  63501. BABYLON.serialize()
  63502. ], StandardRenderingPipeline.prototype, "volumetricLightBlurScale", void 0);
  63503. __decorate([
  63504. BABYLON.serialize()
  63505. ], StandardRenderingPipeline.prototype, "hdrMinimumLuminance", void 0);
  63506. __decorate([
  63507. BABYLON.serialize()
  63508. ], StandardRenderingPipeline.prototype, "hdrDecreaseRate", void 0);
  63509. __decorate([
  63510. BABYLON.serialize()
  63511. ], StandardRenderingPipeline.prototype, "hdrIncreaseRate", void 0);
  63512. __decorate([
  63513. BABYLON.serializeAsTexture("lensColorTexture")
  63514. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  63515. __decorate([
  63516. BABYLON.serialize()
  63517. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  63518. __decorate([
  63519. BABYLON.serialize()
  63520. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  63521. __decorate([
  63522. BABYLON.serialize()
  63523. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  63524. __decorate([
  63525. BABYLON.serialize()
  63526. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  63527. __decorate([
  63528. BABYLON.serializeAsTexture("lensStarTexture")
  63529. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  63530. __decorate([
  63531. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  63532. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  63533. __decorate([
  63534. BABYLON.serialize()
  63535. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  63536. __decorate([
  63537. BABYLON.serialize()
  63538. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  63539. __decorate([
  63540. BABYLON.serialize()
  63541. ], StandardRenderingPipeline.prototype, "motionStrength", void 0);
  63542. __decorate([
  63543. BABYLON.serialize()
  63544. ], StandardRenderingPipeline.prototype, "_ratio", void 0);
  63545. __decorate([
  63546. BABYLON.serialize()
  63547. ], StandardRenderingPipeline.prototype, "BloomEnabled", null);
  63548. __decorate([
  63549. BABYLON.serialize()
  63550. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  63551. __decorate([
  63552. BABYLON.serialize()
  63553. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  63554. __decorate([
  63555. BABYLON.serialize()
  63556. ], StandardRenderingPipeline.prototype, "HDREnabled", null);
  63557. __decorate([
  63558. BABYLON.serialize()
  63559. ], StandardRenderingPipeline.prototype, "VLSEnabled", null);
  63560. __decorate([
  63561. BABYLON.serialize()
  63562. ], StandardRenderingPipeline.prototype, "MotionBlurEnabled", null);
  63563. __decorate([
  63564. BABYLON.serialize()
  63565. ], StandardRenderingPipeline.prototype, "volumetricLightStepsCount", null);
  63566. __decorate([
  63567. BABYLON.serialize()
  63568. ], StandardRenderingPipeline.prototype, "motionBlurSamples", null);
  63569. return StandardRenderingPipeline;
  63570. }(BABYLON.PostProcessRenderPipeline));
  63571. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  63572. })(BABYLON || (BABYLON = {}));
  63573. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  63574. var BABYLON;
  63575. (function (BABYLON) {
  63576. var FxaaPostProcess = /** @class */ (function (_super) {
  63577. __extends(FxaaPostProcess, _super);
  63578. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  63579. if (camera === void 0) { camera = null; }
  63580. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  63581. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa") || this;
  63582. _this.onApplyObservable.add(function (effect) {
  63583. var texelSize = _this.texelSize;
  63584. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  63585. });
  63586. return _this;
  63587. }
  63588. return FxaaPostProcess;
  63589. }(BABYLON.PostProcess));
  63590. BABYLON.FxaaPostProcess = FxaaPostProcess;
  63591. })(BABYLON || (BABYLON = {}));
  63592. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  63593. var BABYLON;
  63594. (function (BABYLON) {
  63595. var DefaultRenderingPipeline = /** @class */ (function (_super) {
  63596. __extends(DefaultRenderingPipeline, _super);
  63597. /**
  63598. * @constructor
  63599. * @param {string} name - The rendering pipeline name
  63600. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  63601. * @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)
  63602. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  63603. * @param {boolean} automaticBuild - if false, you will have to manually call prepare() to update the pipeline
  63604. */
  63605. function DefaultRenderingPipeline(name, hdr, scene, cameras, automaticBuild) {
  63606. if (automaticBuild === void 0) { automaticBuild = true; }
  63607. var _this = _super.call(this, scene.getEngine(), name) || this;
  63608. _this.PassPostProcessId = "PassPostProcessEffect";
  63609. _this.HighLightsPostProcessId = "HighLightsPostProcessEffect";
  63610. _this.BlurXPostProcessId = "BlurXPostProcessEffect";
  63611. _this.BlurYPostProcessId = "BlurYPostProcessEffect";
  63612. _this.CopyBackPostProcessId = "CopyBackPostProcessEffect";
  63613. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  63614. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  63615. _this.FinalMergePostProcessId = "FinalMergePostProcessEffect";
  63616. // IAnimatable
  63617. _this.animations = [];
  63618. // Values
  63619. _this._bloomEnabled = false;
  63620. _this._fxaaEnabled = false;
  63621. _this._imageProcessingEnabled = true;
  63622. _this._bloomScale = 0.6;
  63623. _this._buildAllowed = true;
  63624. /**
  63625. * Specifies the size of the bloom blur kernel, relative to the final output size
  63626. */
  63627. _this.bloomKernel = 64;
  63628. /**
  63629. * Specifies the weight of the bloom in the final rendering
  63630. */
  63631. _this._bloomWeight = 0.15;
  63632. _this._cameras = cameras || [];
  63633. _this._buildAllowed = automaticBuild;
  63634. // Initialize
  63635. _this._scene = scene;
  63636. var caps = _this._scene.getEngine().getCaps();
  63637. _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
  63638. // Misc
  63639. if (_this._hdr) {
  63640. if (caps.textureHalfFloatRender) {
  63641. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  63642. }
  63643. else if (caps.textureFloatRender) {
  63644. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  63645. }
  63646. }
  63647. else {
  63648. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  63649. }
  63650. // Attach
  63651. scene.postProcessRenderPipelineManager.addPipeline(_this);
  63652. _this._buildPipeline();
  63653. return _this;
  63654. }
  63655. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  63656. get: function () {
  63657. return this._bloomWeight;
  63658. },
  63659. set: function (value) {
  63660. if (this._bloomWeight === value) {
  63661. return;
  63662. }
  63663. this._bloomWeight = value;
  63664. if (this._hdr && this.copyBack) {
  63665. this.copyBack.alphaConstants = new BABYLON.Color4(value, value, value, value);
  63666. }
  63667. },
  63668. enumerable: true,
  63669. configurable: true
  63670. });
  63671. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  63672. get: function () {
  63673. return this._bloomScale;
  63674. },
  63675. set: function (value) {
  63676. if (this._bloomScale === value) {
  63677. return;
  63678. }
  63679. this._bloomScale = value;
  63680. this._buildPipeline();
  63681. },
  63682. enumerable: true,
  63683. configurable: true
  63684. });
  63685. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  63686. get: function () {
  63687. return this._bloomEnabled;
  63688. },
  63689. set: function (enabled) {
  63690. if (this._bloomEnabled === enabled) {
  63691. return;
  63692. }
  63693. this._bloomEnabled = enabled;
  63694. this._buildPipeline();
  63695. },
  63696. enumerable: true,
  63697. configurable: true
  63698. });
  63699. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  63700. get: function () {
  63701. return this._fxaaEnabled;
  63702. },
  63703. set: function (enabled) {
  63704. if (this._fxaaEnabled === enabled) {
  63705. return;
  63706. }
  63707. this._fxaaEnabled = enabled;
  63708. this._buildPipeline();
  63709. },
  63710. enumerable: true,
  63711. configurable: true
  63712. });
  63713. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  63714. get: function () {
  63715. return this._imageProcessingEnabled;
  63716. },
  63717. set: function (enabled) {
  63718. if (this._imageProcessingEnabled === enabled) {
  63719. return;
  63720. }
  63721. this._imageProcessingEnabled = enabled;
  63722. this._buildPipeline();
  63723. },
  63724. enumerable: true,
  63725. configurable: true
  63726. });
  63727. /**
  63728. * Force the compilation of the entire pipeline.
  63729. */
  63730. DefaultRenderingPipeline.prototype.prepare = function () {
  63731. var previousState = this._buildAllowed;
  63732. this._buildAllowed = true;
  63733. this._buildPipeline();
  63734. this._buildAllowed = previousState;
  63735. };
  63736. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  63737. var _this = this;
  63738. if (!this._buildAllowed) {
  63739. return;
  63740. }
  63741. var engine = this._scene.getEngine();
  63742. this._disposePostProcesses();
  63743. this._reset();
  63744. if (this.bloomEnabled) {
  63745. this.pass = new BABYLON.PassPostProcess("sceneRenderTarget", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  63746. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.PassPostProcessId, function () { return _this.pass; }, true));
  63747. if (!this._hdr) {
  63748. this.highlights = new BABYLON.HighlightsPostProcess("highlights", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  63749. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.HighLightsPostProcessId, function () { return _this.highlights; }, true));
  63750. this.highlights.autoClear = false;
  63751. this.highlights.alwaysForcePOT = true;
  63752. }
  63753. 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);
  63754. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurXPostProcessId, function () { return _this.blurX; }, true));
  63755. this.blurX.alwaysForcePOT = true;
  63756. this.blurX.autoClear = false;
  63757. this.blurX.onActivateObservable.add(function () {
  63758. var dw = _this.blurX.width / engine.getRenderWidth(true);
  63759. _this.blurX.kernel = _this.bloomKernel * dw;
  63760. });
  63761. 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);
  63762. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurYPostProcessId, function () { return _this.blurY; }, true));
  63763. this.blurY.alwaysForcePOT = true;
  63764. this.blurY.autoClear = false;
  63765. this.blurY.onActivateObservable.add(function () {
  63766. var dh = _this.blurY.height / engine.getRenderHeight(true);
  63767. _this.blurY.kernel = _this.bloomKernel * dh;
  63768. });
  63769. this.copyBack = new BABYLON.PassPostProcess("bloomBlendBlit", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  63770. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.CopyBackPostProcessId, function () { return _this.copyBack; }, true));
  63771. this.copyBack.alwaysForcePOT = true;
  63772. if (this._hdr) {
  63773. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_INTERPOLATE;
  63774. var w = this.bloomWeight;
  63775. this.copyBack.alphaConstants = new BABYLON.Color4(w, w, w, w);
  63776. }
  63777. else {
  63778. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_SCREENMODE;
  63779. }
  63780. this.copyBack.autoClear = false;
  63781. }
  63782. if (this._imageProcessingEnabled) {
  63783. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  63784. if (this._hdr) {
  63785. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  63786. }
  63787. else {
  63788. this._scene.imageProcessingConfiguration.applyByPostProcess = false;
  63789. }
  63790. }
  63791. if (this.fxaaEnabled) {
  63792. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  63793. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  63794. this.fxaa.autoClear = !this.bloomEnabled && (!this._hdr || !this.imageProcessing);
  63795. }
  63796. else if (this._hdr && this.imageProcessing) {
  63797. this.finalMerge = this.imageProcessing;
  63798. }
  63799. else {
  63800. this.finalMerge = new BABYLON.PassPostProcess("finalMerge", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  63801. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FinalMergePostProcessId, function () { return _this.finalMerge; }, true));
  63802. this.finalMerge.autoClear = !this.bloomEnabled && (!this._hdr || !this.imageProcessing);
  63803. }
  63804. if (this.bloomEnabled) {
  63805. if (this._hdr) {
  63806. this.copyBack.shareOutputWith(this.blurX);
  63807. if (this.imageProcessing) {
  63808. this.imageProcessing.shareOutputWith(this.pass);
  63809. this.imageProcessing.autoClear = false;
  63810. }
  63811. else if (this.fxaa) {
  63812. this.fxaa.shareOutputWith(this.pass);
  63813. }
  63814. else {
  63815. this.finalMerge.shareOutputWith(this.pass);
  63816. }
  63817. }
  63818. else {
  63819. if (this.fxaa) {
  63820. this.fxaa.shareOutputWith(this.pass);
  63821. }
  63822. else {
  63823. this.finalMerge.shareOutputWith(this.pass);
  63824. }
  63825. }
  63826. }
  63827. if (this._cameras !== null) {
  63828. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  63829. }
  63830. };
  63831. DefaultRenderingPipeline.prototype._disposePostProcesses = function () {
  63832. for (var i = 0; i < this._cameras.length; i++) {
  63833. var camera = this._cameras[i];
  63834. if (this.pass) {
  63835. this.pass.dispose(camera);
  63836. }
  63837. if (this.highlights) {
  63838. this.highlights.dispose(camera);
  63839. }
  63840. if (this.blurX) {
  63841. this.blurX.dispose(camera);
  63842. }
  63843. if (this.blurY) {
  63844. this.blurY.dispose(camera);
  63845. }
  63846. if (this.copyBack) {
  63847. this.copyBack.dispose(camera);
  63848. }
  63849. if (this.imageProcessing) {
  63850. this.imageProcessing.dispose(camera);
  63851. }
  63852. if (this.fxaa) {
  63853. this.fxaa.dispose(camera);
  63854. }
  63855. if (this.finalMerge) {
  63856. this.finalMerge.dispose(camera);
  63857. }
  63858. }
  63859. this.pass = null;
  63860. this.highlights = null;
  63861. this.blurX = null;
  63862. this.blurY = null;
  63863. this.copyBack = null;
  63864. this.imageProcessing = null;
  63865. this.fxaa = null;
  63866. this.finalMerge = null;
  63867. };
  63868. // Dispose
  63869. DefaultRenderingPipeline.prototype.dispose = function () {
  63870. this._disposePostProcesses();
  63871. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  63872. _super.prototype.dispose.call(this);
  63873. };
  63874. // Serialize rendering pipeline
  63875. DefaultRenderingPipeline.prototype.serialize = function () {
  63876. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  63877. serializationObject.customType = "DefaultRenderingPipeline";
  63878. return serializationObject;
  63879. };
  63880. // Parse serialized pipeline
  63881. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  63882. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  63883. };
  63884. __decorate([
  63885. BABYLON.serialize()
  63886. ], DefaultRenderingPipeline.prototype, "bloomKernel", void 0);
  63887. __decorate([
  63888. BABYLON.serialize()
  63889. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  63890. __decorate([
  63891. BABYLON.serialize()
  63892. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  63893. __decorate([
  63894. BABYLON.serialize()
  63895. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  63896. __decorate([
  63897. BABYLON.serialize()
  63898. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  63899. __decorate([
  63900. BABYLON.serialize()
  63901. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  63902. __decorate([
  63903. BABYLON.serialize()
  63904. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  63905. __decorate([
  63906. BABYLON.serialize()
  63907. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  63908. return DefaultRenderingPipeline;
  63909. }(BABYLON.PostProcessRenderPipeline));
  63910. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  63911. })(BABYLON || (BABYLON = {}));
  63912. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  63913. var BABYLON;
  63914. (function (BABYLON) {
  63915. /**
  63916. * This renderer is helpfull to fill one of the render target with a geometry buffer.
  63917. */
  63918. var GeometryBufferRenderer = /** @class */ (function () {
  63919. /**
  63920. * Creates a new G Buffer for the scene. @see GeometryBufferRenderer
  63921. * @param scene The scene the buffer belongs to
  63922. * @param ratio How big is the buffer related to the main canvas.
  63923. */
  63924. function GeometryBufferRenderer(scene, ratio) {
  63925. if (ratio === void 0) { ratio = 1; }
  63926. this._enablePosition = false;
  63927. this._scene = scene;
  63928. this._ratio = ratio;
  63929. // Render target
  63930. this._createRenderTargets();
  63931. }
  63932. Object.defineProperty(GeometryBufferRenderer.prototype, "renderList", {
  63933. /**
  63934. * Set the render list (meshes to be rendered) used in the G buffer.
  63935. */
  63936. set: function (meshes) {
  63937. this._multiRenderTarget.renderList = meshes;
  63938. },
  63939. enumerable: true,
  63940. configurable: true
  63941. });
  63942. Object.defineProperty(GeometryBufferRenderer.prototype, "isSupported", {
  63943. /**
  63944. * Gets wether or not G buffer are supported by the running hardware.
  63945. * This requires draw buffer supports
  63946. */
  63947. get: function () {
  63948. return this._multiRenderTarget.isSupported;
  63949. },
  63950. enumerable: true,
  63951. configurable: true
  63952. });
  63953. Object.defineProperty(GeometryBufferRenderer.prototype, "enablePosition", {
  63954. /**
  63955. * Gets wether or not position are enabled for the G buffer.
  63956. */
  63957. get: function () {
  63958. return this._enablePosition;
  63959. },
  63960. /**
  63961. * Sets wether or not position are enabled for the G buffer.
  63962. */
  63963. set: function (enable) {
  63964. this._enablePosition = enable;
  63965. this.dispose();
  63966. this._createRenderTargets();
  63967. },
  63968. enumerable: true,
  63969. configurable: true
  63970. });
  63971. Object.defineProperty(GeometryBufferRenderer.prototype, "scene", {
  63972. /**
  63973. * Gets the scene associated with the buffer.
  63974. */
  63975. get: function () {
  63976. return this._scene;
  63977. },
  63978. enumerable: true,
  63979. configurable: true
  63980. });
  63981. Object.defineProperty(GeometryBufferRenderer.prototype, "ratio", {
  63982. /**
  63983. * Gets the ratio used by the buffer during its creation.
  63984. * How big is the buffer related to the main canvas.
  63985. */
  63986. get: function () {
  63987. return this._ratio;
  63988. },
  63989. enumerable: true,
  63990. configurable: true
  63991. });
  63992. /**
  63993. * Checks wether everything is ready to render a submesh to the G buffer.
  63994. * @param subMesh the submesh to check readiness for
  63995. * @param useInstances is the mesh drawn using instance or not
  63996. * @returns true if ready otherwise false
  63997. */
  63998. GeometryBufferRenderer.prototype.isReady = function (subMesh, useInstances) {
  63999. var material = subMesh.getMaterial();
  64000. if (material && material.disableDepthWrite) {
  64001. return false;
  64002. }
  64003. var defines = [];
  64004. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  64005. var mesh = subMesh.getMesh();
  64006. // Alpha test
  64007. if (material && material.needAlphaTesting()) {
  64008. defines.push("#define ALPHATEST");
  64009. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  64010. attribs.push(BABYLON.VertexBuffer.UVKind);
  64011. defines.push("#define UV1");
  64012. }
  64013. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  64014. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  64015. defines.push("#define UV2");
  64016. }
  64017. }
  64018. // Buffers
  64019. if (this._enablePosition) {
  64020. defines.push("#define POSITION");
  64021. }
  64022. // Bones
  64023. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  64024. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  64025. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  64026. if (mesh.numBoneInfluencers > 4) {
  64027. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  64028. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  64029. }
  64030. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  64031. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  64032. }
  64033. else {
  64034. defines.push("#define NUM_BONE_INFLUENCERS 0");
  64035. }
  64036. // Instances
  64037. if (useInstances) {
  64038. defines.push("#define INSTANCES");
  64039. attribs.push("world0");
  64040. attribs.push("world1");
  64041. attribs.push("world2");
  64042. attribs.push("world3");
  64043. }
  64044. // Get correct effect
  64045. var join = defines.join("\n");
  64046. if (this._cachedDefines !== join) {
  64047. this._cachedDefines = join;
  64048. this._effect = this._scene.getEngine().createEffect("geometry", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "view"], ["diffuseSampler"], join, undefined, undefined, undefined, { buffersCount: this._enablePosition ? 3 : 2 });
  64049. }
  64050. return this._effect.isReady();
  64051. };
  64052. /**
  64053. * Gets the current underlying G Buffer.
  64054. * @returns the buffer
  64055. */
  64056. GeometryBufferRenderer.prototype.getGBuffer = function () {
  64057. return this._multiRenderTarget;
  64058. };
  64059. Object.defineProperty(GeometryBufferRenderer.prototype, "samples", {
  64060. /**
  64061. * Gets the number of samples used to render the buffer (anti aliasing).
  64062. */
  64063. get: function () {
  64064. return this._multiRenderTarget.samples;
  64065. },
  64066. /**
  64067. * Sets the number of samples used to render the buffer (anti aliasing).
  64068. */
  64069. set: function (value) {
  64070. this._multiRenderTarget.samples = value;
  64071. },
  64072. enumerable: true,
  64073. configurable: true
  64074. });
  64075. /**
  64076. * Disposes the renderer and frees up associated resources.
  64077. */
  64078. GeometryBufferRenderer.prototype.dispose = function () {
  64079. this.getGBuffer().dispose();
  64080. };
  64081. GeometryBufferRenderer.prototype._createRenderTargets = function () {
  64082. var _this = this;
  64083. var engine = this._scene.getEngine();
  64084. var count = this._enablePosition ? 3 : 2;
  64085. this._multiRenderTarget = new BABYLON.MultiRenderTarget("gBuffer", { width: engine.getRenderWidth() * this._ratio, height: engine.getRenderHeight() * this._ratio }, count, this._scene, { generateMipMaps: false, generateDepthTexture: true, defaultType: BABYLON.Engine.TEXTURETYPE_FLOAT });
  64086. if (!this.isSupported) {
  64087. return;
  64088. }
  64089. this._multiRenderTarget.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64090. this._multiRenderTarget.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64091. this._multiRenderTarget.refreshRate = 1;
  64092. this._multiRenderTarget.renderParticles = false;
  64093. this._multiRenderTarget.renderList = null;
  64094. // set default depth value to 1.0 (far away)
  64095. this._multiRenderTarget.onClearObservable.add(function (engine) {
  64096. engine.clear(new BABYLON.Color4(0.0, 0.0, 0.0, 1.0), true, true, true);
  64097. });
  64098. // Custom render function
  64099. var renderSubMesh = function (subMesh) {
  64100. var mesh = subMesh.getRenderingMesh();
  64101. var scene = _this._scene;
  64102. var engine = scene.getEngine();
  64103. var material = subMesh.getMaterial();
  64104. if (!material) {
  64105. return;
  64106. }
  64107. // Culling
  64108. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  64109. // Managing instances
  64110. var batch = mesh._getInstancesRenderList(subMesh._id);
  64111. if (batch.mustReturn) {
  64112. return;
  64113. }
  64114. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  64115. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  64116. engine.enableEffect(_this._effect);
  64117. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  64118. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  64119. _this._effect.setMatrix("view", scene.getViewMatrix());
  64120. // Alpha test
  64121. if (material && material.needAlphaTesting()) {
  64122. var alphaTexture = material.getAlphaTestTexture();
  64123. if (alphaTexture) {
  64124. _this._effect.setTexture("diffuseSampler", alphaTexture);
  64125. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  64126. }
  64127. }
  64128. // Bones
  64129. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  64130. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  64131. }
  64132. // Draw
  64133. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  64134. }
  64135. };
  64136. this._multiRenderTarget.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  64137. var index;
  64138. if (depthOnlySubMeshes.length) {
  64139. engine.setColorWrite(false);
  64140. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  64141. renderSubMesh(depthOnlySubMeshes.data[index]);
  64142. }
  64143. engine.setColorWrite(true);
  64144. }
  64145. for (index = 0; index < opaqueSubMeshes.length; index++) {
  64146. renderSubMesh(opaqueSubMeshes.data[index]);
  64147. }
  64148. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  64149. renderSubMesh(alphaTestSubMeshes.data[index]);
  64150. }
  64151. };
  64152. };
  64153. return GeometryBufferRenderer;
  64154. }());
  64155. BABYLON.GeometryBufferRenderer = GeometryBufferRenderer;
  64156. })(BABYLON || (BABYLON = {}));
  64157. //# sourceMappingURL=babylon.geometryBufferRenderer.js.map
  64158. var BABYLON;
  64159. (function (BABYLON) {
  64160. var RefractionPostProcess = /** @class */ (function (_super) {
  64161. __extends(RefractionPostProcess, _super);
  64162. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  64163. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  64164. _this.color = color;
  64165. _this.depth = depth;
  64166. _this.colorLevel = colorLevel;
  64167. _this.onActivateObservable.add(function (cam) {
  64168. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  64169. });
  64170. _this.onApplyObservable.add(function (effect) {
  64171. effect.setColor3("baseColor", _this.color);
  64172. effect.setFloat("depth", _this.depth);
  64173. effect.setFloat("colorLevel", _this.colorLevel);
  64174. effect.setTexture("refractionSampler", _this._refRexture);
  64175. });
  64176. return _this;
  64177. }
  64178. // Methods
  64179. RefractionPostProcess.prototype.dispose = function (camera) {
  64180. if (this._refRexture) {
  64181. this._refRexture.dispose();
  64182. }
  64183. _super.prototype.dispose.call(this, camera);
  64184. };
  64185. return RefractionPostProcess;
  64186. }(BABYLON.PostProcess));
  64187. BABYLON.RefractionPostProcess = RefractionPostProcess;
  64188. })(BABYLON || (BABYLON = {}));
  64189. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  64190. var BABYLON;
  64191. (function (BABYLON) {
  64192. var BlackAndWhitePostProcess = /** @class */ (function (_super) {
  64193. __extends(BlackAndWhitePostProcess, _super);
  64194. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  64195. var _this = _super.call(this, name, "blackAndWhite", ["degree"], null, options, camera, samplingMode, engine, reusable) || this;
  64196. _this.degree = 1;
  64197. _this.onApplyObservable.add(function (effect) {
  64198. effect.setFloat("degree", _this.degree);
  64199. });
  64200. return _this;
  64201. }
  64202. return BlackAndWhitePostProcess;
  64203. }(BABYLON.PostProcess));
  64204. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  64205. })(BABYLON || (BABYLON = {}));
  64206. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  64207. var BABYLON;
  64208. (function (BABYLON) {
  64209. var ConvolutionPostProcess = /** @class */ (function (_super) {
  64210. __extends(ConvolutionPostProcess, _super);
  64211. function ConvolutionPostProcess(name, kernel, options, camera, samplingMode, engine, reusable) {
  64212. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable) || this;
  64213. _this.kernel = kernel;
  64214. _this.onApply = function (effect) {
  64215. effect.setFloat2("screenSize", _this.width, _this.height);
  64216. effect.setArray("kernel", _this.kernel);
  64217. };
  64218. return _this;
  64219. }
  64220. // Statics
  64221. // Based on http://en.wikipedia.org/wiki/Kernel_(image_processing)
  64222. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  64223. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  64224. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  64225. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  64226. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  64227. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  64228. return ConvolutionPostProcess;
  64229. }(BABYLON.PostProcess));
  64230. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  64231. })(BABYLON || (BABYLON = {}));
  64232. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  64233. var BABYLON;
  64234. (function (BABYLON) {
  64235. var FilterPostProcess = /** @class */ (function (_super) {
  64236. __extends(FilterPostProcess, _super);
  64237. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  64238. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  64239. _this.kernelMatrix = kernelMatrix;
  64240. _this.onApply = function (effect) {
  64241. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  64242. };
  64243. return _this;
  64244. }
  64245. return FilterPostProcess;
  64246. }(BABYLON.PostProcess));
  64247. BABYLON.FilterPostProcess = FilterPostProcess;
  64248. })(BABYLON || (BABYLON = {}));
  64249. //# sourceMappingURL=babylon.filterPostProcess.js.map
  64250. var BABYLON;
  64251. (function (BABYLON) {
  64252. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  64253. var VolumetricLightScatteringPostProcess = /** @class */ (function (_super) {
  64254. __extends(VolumetricLightScatteringPostProcess, _super);
  64255. /**
  64256. * @constructor
  64257. * @param {string} name - The post-process name
  64258. * @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)
  64259. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  64260. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  64261. * @param {number} samples - The post-process quality, default 100
  64262. * @param {number} samplingMode - The post-process filtering mode
  64263. * @param {BABYLON.Engine} engine - The babylon engine
  64264. * @param {boolean} reusable - If the post-process is reusable
  64265. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  64266. */
  64267. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  64268. if (samples === void 0) { samples = 100; }
  64269. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  64270. 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;
  64271. _this._screenCoordinates = BABYLON.Vector2.Zero();
  64272. /**
  64273. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  64274. * @type {Vector3}
  64275. */
  64276. _this.customMeshPosition = BABYLON.Vector3.Zero();
  64277. /**
  64278. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  64279. * @type {boolean}
  64280. */
  64281. _this.useCustomMeshPosition = false;
  64282. /**
  64283. * If the post-process should inverse the light scattering direction
  64284. * @type {boolean}
  64285. */
  64286. _this.invert = true;
  64287. /**
  64288. * Array containing the excluded meshes not rendered in the internal pass
  64289. */
  64290. _this.excludedMeshes = new Array();
  64291. /**
  64292. * Controls the overall intensity of the post-process
  64293. * @type {number}
  64294. */
  64295. _this.exposure = 0.3;
  64296. /**
  64297. * Dissipates each sample's contribution in range [0, 1]
  64298. * @type {number}
  64299. */
  64300. _this.decay = 0.96815;
  64301. /**
  64302. * Controls the overall intensity of each sample
  64303. * @type {number}
  64304. */
  64305. _this.weight = 0.58767;
  64306. /**
  64307. * Controls the density of each sample
  64308. * @type {number}
  64309. */
  64310. _this.density = 0.926;
  64311. scene = ((camera === null) ? scene : camera.getScene()); // parameter "scene" can be null.
  64312. engine = scene.getEngine();
  64313. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  64314. // Configure mesh
  64315. _this.mesh = ((mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene));
  64316. // Configure
  64317. _this._createPass(scene, ratio.passRatio || ratio);
  64318. _this.onActivate = function (camera) {
  64319. if (!_this.isSupported) {
  64320. _this.dispose(camera);
  64321. }
  64322. _this.onActivate = null;
  64323. };
  64324. _this.onApplyObservable.add(function (effect) {
  64325. _this._updateMeshScreenCoordinates(scene);
  64326. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  64327. effect.setFloat("exposure", _this.exposure);
  64328. effect.setFloat("decay", _this.decay);
  64329. effect.setFloat("weight", _this.weight);
  64330. effect.setFloat("density", _this.density);
  64331. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  64332. });
  64333. return _this;
  64334. }
  64335. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  64336. get: function () {
  64337. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  64338. return false;
  64339. },
  64340. set: function (useDiffuseColor) {
  64341. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  64342. },
  64343. enumerable: true,
  64344. configurable: true
  64345. });
  64346. VolumetricLightScatteringPostProcess.prototype.getClassName = function () {
  64347. return "VolumetricLightScatteringPostProcess";
  64348. };
  64349. VolumetricLightScatteringPostProcess.prototype._isReady = function (subMesh, useInstances) {
  64350. var mesh = subMesh.getMesh();
  64351. // Render this.mesh as default
  64352. if (mesh === this.mesh && mesh.material) {
  64353. return mesh.material.isReady(mesh);
  64354. }
  64355. var defines = [];
  64356. var attribs = [BABYLON.VertexBuffer.PositionKind];
  64357. var material = subMesh.getMaterial();
  64358. // Alpha test
  64359. if (material) {
  64360. if (material.needAlphaTesting()) {
  64361. defines.push("#define ALPHATEST");
  64362. }
  64363. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  64364. attribs.push(BABYLON.VertexBuffer.UVKind);
  64365. defines.push("#define UV1");
  64366. }
  64367. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  64368. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  64369. defines.push("#define UV2");
  64370. }
  64371. }
  64372. // Bones
  64373. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  64374. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  64375. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  64376. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  64377. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  64378. }
  64379. else {
  64380. defines.push("#define NUM_BONE_INFLUENCERS 0");
  64381. }
  64382. // Instances
  64383. if (useInstances) {
  64384. defines.push("#define INSTANCES");
  64385. attribs.push("world0");
  64386. attribs.push("world1");
  64387. attribs.push("world2");
  64388. attribs.push("world3");
  64389. }
  64390. // Get correct effect
  64391. var join = defines.join("\n");
  64392. if (this._cachedDefines !== join) {
  64393. this._cachedDefines = join;
  64394. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  64395. }
  64396. return this._volumetricLightScatteringPass.isReady();
  64397. };
  64398. /**
  64399. * Sets the new light position for light scattering effect
  64400. * @param {BABYLON.Vector3} The new custom light position
  64401. */
  64402. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  64403. this.customMeshPosition = position;
  64404. };
  64405. /**
  64406. * Returns the light position for light scattering effect
  64407. * @return {BABYLON.Vector3} The custom light position
  64408. */
  64409. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  64410. return this.customMeshPosition;
  64411. };
  64412. /**
  64413. * Disposes the internal assets and detaches the post-process from the camera
  64414. */
  64415. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  64416. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  64417. if (rttIndex !== -1) {
  64418. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  64419. }
  64420. this._volumetricLightScatteringRTT.dispose();
  64421. _super.prototype.dispose.call(this, camera);
  64422. };
  64423. /**
  64424. * Returns the render target texture used by the post-process
  64425. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  64426. */
  64427. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  64428. return this._volumetricLightScatteringRTT;
  64429. };
  64430. // Private methods
  64431. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  64432. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  64433. return true;
  64434. }
  64435. return false;
  64436. };
  64437. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  64438. var _this = this;
  64439. var engine = scene.getEngine();
  64440. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  64441. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64442. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64443. this._volumetricLightScatteringRTT.renderList = null;
  64444. this._volumetricLightScatteringRTT.renderParticles = false;
  64445. var camera = this.getCamera();
  64446. if (camera) {
  64447. camera.customRenderTargets.push(this._volumetricLightScatteringRTT);
  64448. }
  64449. else {
  64450. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  64451. }
  64452. // Custom render function for submeshes
  64453. var renderSubMesh = function (subMesh) {
  64454. var mesh = subMesh.getRenderingMesh();
  64455. if (_this._meshExcluded(mesh)) {
  64456. return;
  64457. }
  64458. var material = subMesh.getMaterial();
  64459. if (!material) {
  64460. return;
  64461. }
  64462. var scene = mesh.getScene();
  64463. var engine = scene.getEngine();
  64464. // Culling
  64465. engine.setState(material.backFaceCulling);
  64466. // Managing instances
  64467. var batch = mesh._getInstancesRenderList(subMesh._id);
  64468. if (batch.mustReturn) {
  64469. return;
  64470. }
  64471. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  64472. if (_this._isReady(subMesh, hardwareInstancedRendering)) {
  64473. var effect = _this._volumetricLightScatteringPass;
  64474. if (mesh === _this.mesh) {
  64475. if (subMesh.effect) {
  64476. effect = subMesh.effect;
  64477. }
  64478. else {
  64479. effect = material.getEffect();
  64480. }
  64481. }
  64482. engine.enableEffect(effect);
  64483. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  64484. if (mesh === _this.mesh) {
  64485. material.bind(mesh.getWorldMatrix(), mesh);
  64486. }
  64487. else {
  64488. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  64489. // Alpha test
  64490. if (material && material.needAlphaTesting()) {
  64491. var alphaTexture = material.getAlphaTestTexture();
  64492. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  64493. if (alphaTexture) {
  64494. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  64495. }
  64496. }
  64497. // Bones
  64498. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  64499. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  64500. }
  64501. }
  64502. // Draw
  64503. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  64504. }
  64505. };
  64506. // Render target texture callbacks
  64507. var savedSceneClearColor;
  64508. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  64509. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  64510. savedSceneClearColor = scene.clearColor;
  64511. scene.clearColor = sceneClearColor;
  64512. });
  64513. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  64514. scene.clearColor = savedSceneClearColor;
  64515. });
  64516. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  64517. var engine = scene.getEngine();
  64518. var index;
  64519. if (depthOnlySubMeshes.length) {
  64520. engine.setColorWrite(false);
  64521. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  64522. renderSubMesh(depthOnlySubMeshes.data[index]);
  64523. }
  64524. engine.setColorWrite(true);
  64525. }
  64526. for (index = 0; index < opaqueSubMeshes.length; index++) {
  64527. renderSubMesh(opaqueSubMeshes.data[index]);
  64528. }
  64529. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  64530. renderSubMesh(alphaTestSubMeshes.data[index]);
  64531. }
  64532. if (transparentSubMeshes.length) {
  64533. // Sort sub meshes
  64534. for (index = 0; index < transparentSubMeshes.length; index++) {
  64535. var submesh = transparentSubMeshes.data[index];
  64536. var boundingInfo = submesh.getBoundingInfo();
  64537. if (boundingInfo && scene.activeCamera) {
  64538. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  64539. submesh._distanceToCamera = boundingInfo.boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  64540. }
  64541. }
  64542. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  64543. sortedArray.sort(function (a, b) {
  64544. // Alpha index first
  64545. if (a._alphaIndex > b._alphaIndex) {
  64546. return 1;
  64547. }
  64548. if (a._alphaIndex < b._alphaIndex) {
  64549. return -1;
  64550. }
  64551. // Then distance to camera
  64552. if (a._distanceToCamera < b._distanceToCamera) {
  64553. return 1;
  64554. }
  64555. if (a._distanceToCamera > b._distanceToCamera) {
  64556. return -1;
  64557. }
  64558. return 0;
  64559. });
  64560. // Render sub meshes
  64561. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  64562. for (index = 0; index < sortedArray.length; index++) {
  64563. renderSubMesh(sortedArray[index]);
  64564. }
  64565. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  64566. }
  64567. };
  64568. };
  64569. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  64570. var transform = scene.getTransformMatrix();
  64571. var meshPosition;
  64572. if (this.useCustomMeshPosition) {
  64573. meshPosition = this.customMeshPosition;
  64574. }
  64575. else if (this.attachedNode) {
  64576. meshPosition = this.attachedNode.position;
  64577. }
  64578. else {
  64579. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  64580. }
  64581. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  64582. this._screenCoordinates.x = pos.x / this._viewPort.width;
  64583. this._screenCoordinates.y = pos.y / this._viewPort.height;
  64584. if (this.invert)
  64585. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  64586. };
  64587. // Static methods
  64588. /**
  64589. * Creates a default mesh for the Volumeric Light Scattering post-process
  64590. * @param {string} The mesh name
  64591. * @param {BABYLON.Scene} The scene where to create the mesh
  64592. * @return {BABYLON.Mesh} the default mesh
  64593. */
  64594. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  64595. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  64596. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  64597. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  64598. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  64599. mesh.material = material;
  64600. return mesh;
  64601. };
  64602. __decorate([
  64603. BABYLON.serializeAsVector3()
  64604. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  64605. __decorate([
  64606. BABYLON.serialize()
  64607. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  64608. __decorate([
  64609. BABYLON.serialize()
  64610. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  64611. __decorate([
  64612. BABYLON.serializeAsMeshReference()
  64613. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  64614. __decorate([
  64615. BABYLON.serialize()
  64616. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  64617. __decorate([
  64618. BABYLON.serialize()
  64619. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  64620. __decorate([
  64621. BABYLON.serialize()
  64622. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  64623. __decorate([
  64624. BABYLON.serialize()
  64625. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  64626. __decorate([
  64627. BABYLON.serialize()
  64628. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  64629. return VolumetricLightScatteringPostProcess;
  64630. }(BABYLON.PostProcess));
  64631. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  64632. })(BABYLON || (BABYLON = {}));
  64633. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  64634. //
  64635. // This post-process allows the modification of rendered colors by using
  64636. // a 'look-up table' (LUT). This effect is also called Color Grading.
  64637. //
  64638. // The object needs to be provided an url to a texture containing the color
  64639. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  64640. // Use an image editing software to tweak the LUT to match your needs.
  64641. //
  64642. // For an example of a color LUT, see here:
  64643. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  64644. // For explanations on color grading, see here:
  64645. // http://udn.epicgames.com/Three/ColorGrading.html
  64646. //
  64647. var BABYLON;
  64648. (function (BABYLON) {
  64649. var ColorCorrectionPostProcess = /** @class */ (function (_super) {
  64650. __extends(ColorCorrectionPostProcess, _super);
  64651. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  64652. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  64653. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  64654. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  64655. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64656. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64657. _this.onApply = function (effect) {
  64658. effect.setTexture("colorTable", _this._colorTableTexture);
  64659. };
  64660. return _this;
  64661. }
  64662. return ColorCorrectionPostProcess;
  64663. }(BABYLON.PostProcess));
  64664. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  64665. })(BABYLON || (BABYLON = {}));
  64666. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  64667. var BABYLON;
  64668. (function (BABYLON) {
  64669. var TonemappingOperator;
  64670. (function (TonemappingOperator) {
  64671. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  64672. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  64673. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  64674. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  64675. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  64676. ;
  64677. var TonemapPostProcess = /** @class */ (function (_super) {
  64678. __extends(TonemapPostProcess, _super);
  64679. function TonemapPostProcess(name, _operator, exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  64680. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  64681. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  64682. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, null, textureFormat) || this;
  64683. _this._operator = _operator;
  64684. _this.exposureAdjustment = exposureAdjustment;
  64685. var defines = "#define ";
  64686. if (_this._operator === TonemappingOperator.Hable)
  64687. defines += "HABLE_TONEMAPPING";
  64688. else if (_this._operator === TonemappingOperator.Reinhard)
  64689. defines += "REINHARD_TONEMAPPING";
  64690. else if (_this._operator === TonemappingOperator.HejiDawson)
  64691. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  64692. else if (_this._operator === TonemappingOperator.Photographic)
  64693. defines += "PHOTOGRAPHIC_TONEMAPPING";
  64694. //sadly a second call to create the effect.
  64695. _this.updateEffect(defines);
  64696. _this.onApply = function (effect) {
  64697. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  64698. };
  64699. return _this;
  64700. }
  64701. return TonemapPostProcess;
  64702. }(BABYLON.PostProcess));
  64703. BABYLON.TonemapPostProcess = TonemapPostProcess;
  64704. })(BABYLON || (BABYLON = {}));
  64705. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  64706. var BABYLON;
  64707. (function (BABYLON) {
  64708. var DisplayPassPostProcess = /** @class */ (function (_super) {
  64709. __extends(DisplayPassPostProcess, _super);
  64710. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  64711. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  64712. }
  64713. return DisplayPassPostProcess;
  64714. }(BABYLON.PostProcess));
  64715. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  64716. })(BABYLON || (BABYLON = {}));
  64717. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  64718. var BABYLON;
  64719. (function (BABYLON) {
  64720. var HighlightsPostProcess = /** @class */ (function (_super) {
  64721. __extends(HighlightsPostProcess, _super);
  64722. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  64723. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  64724. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  64725. }
  64726. return HighlightsPostProcess;
  64727. }(BABYLON.PostProcess));
  64728. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  64729. })(BABYLON || (BABYLON = {}));
  64730. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  64731. var BABYLON;
  64732. (function (BABYLON) {
  64733. var ImageProcessingPostProcess = /** @class */ (function (_super) {
  64734. __extends(ImageProcessingPostProcess, _super);
  64735. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, imageProcessingConfiguration) {
  64736. if (camera === void 0) { camera = null; }
  64737. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  64738. var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  64739. _this._fromLinearSpace = true;
  64740. /**
  64741. * Defines cache preventing GC.
  64742. */
  64743. _this._defines = {
  64744. IMAGEPROCESSING: false,
  64745. VIGNETTE: false,
  64746. VIGNETTEBLENDMODEMULTIPLY: false,
  64747. VIGNETTEBLENDMODEOPAQUE: false,
  64748. TONEMAPPING: false,
  64749. CONTRAST: false,
  64750. COLORCURVES: false,
  64751. COLORGRADING: false,
  64752. COLORGRADING3D: false,
  64753. FROMLINEARSPACE: false,
  64754. SAMPLER3DGREENDEPTH: false,
  64755. SAMPLER3DBGRMAP: false,
  64756. IMAGEPROCESSINGPOSTPROCESS: false,
  64757. EXPOSURE: false,
  64758. };
  64759. // Setup the configuration as forced by the constructor. This would then not force the
  64760. // scene materials output in linear space and let untouched the default forward pass.
  64761. if (imageProcessingConfiguration) {
  64762. imageProcessingConfiguration.applyByPostProcess = true;
  64763. _this._attachImageProcessingConfiguration(imageProcessingConfiguration, true);
  64764. // This will cause the shader to be compiled
  64765. _this.fromLinearSpace = false;
  64766. }
  64767. else {
  64768. _this._attachImageProcessingConfiguration(null, true);
  64769. _this.imageProcessingConfiguration.applyByPostProcess = true;
  64770. }
  64771. _this.onApply = function (effect) {
  64772. _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
  64773. };
  64774. return _this;
  64775. }
  64776. Object.defineProperty(ImageProcessingPostProcess.prototype, "imageProcessingConfiguration", {
  64777. /**
  64778. * Gets the image processing configuration used either in this material.
  64779. */
  64780. get: function () {
  64781. return this._imageProcessingConfiguration;
  64782. },
  64783. /**
  64784. * Sets the Default image processing configuration used either in the this material.
  64785. *
  64786. * If sets to null, the scene one is in use.
  64787. */
  64788. set: function (value) {
  64789. this._attachImageProcessingConfiguration(value);
  64790. },
  64791. enumerable: true,
  64792. configurable: true
  64793. });
  64794. /**
  64795. * Attaches a new image processing configuration to the PBR Material.
  64796. * @param configuration
  64797. */
  64798. ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration, doNotBuild) {
  64799. var _this = this;
  64800. if (doNotBuild === void 0) { doNotBuild = false; }
  64801. if (configuration === this._imageProcessingConfiguration) {
  64802. return;
  64803. }
  64804. // Detaches observer.
  64805. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  64806. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  64807. }
  64808. // Pick the scene configuration if needed.
  64809. if (!configuration) {
  64810. var scene = null;
  64811. var engine = this.getEngine();
  64812. var camera = this.getCamera();
  64813. if (camera) {
  64814. scene = camera.getScene();
  64815. }
  64816. else if (engine && engine.scenes) {
  64817. var scenes = engine.scenes;
  64818. scene = scenes[scenes.length - 1];
  64819. }
  64820. else {
  64821. scene = BABYLON.Engine.LastCreatedScene;
  64822. }
  64823. this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
  64824. }
  64825. else {
  64826. this._imageProcessingConfiguration = configuration;
  64827. }
  64828. // Attaches observer.
  64829. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  64830. _this._updateParameters();
  64831. });
  64832. // Ensure the effect will be rebuilt.
  64833. if (!doNotBuild) {
  64834. this._updateParameters();
  64835. }
  64836. };
  64837. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", {
  64838. /**
  64839. * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  64840. */
  64841. get: function () {
  64842. return this.imageProcessingConfiguration.colorCurves;
  64843. },
  64844. /**
  64845. * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  64846. */
  64847. set: function (value) {
  64848. this.imageProcessingConfiguration.colorCurves = value;
  64849. },
  64850. enumerable: true,
  64851. configurable: true
  64852. });
  64853. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  64854. /**
  64855. * Gets wether the color curves effect is enabled.
  64856. */
  64857. get: function () {
  64858. return this.imageProcessingConfiguration.colorCurvesEnabled;
  64859. },
  64860. /**
  64861. * Sets wether the color curves effect is enabled.
  64862. */
  64863. set: function (value) {
  64864. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  64865. },
  64866. enumerable: true,
  64867. configurable: true
  64868. });
  64869. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  64870. /**
  64871. * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  64872. */
  64873. get: function () {
  64874. return this.imageProcessingConfiguration.colorGradingTexture;
  64875. },
  64876. /**
  64877. * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  64878. */
  64879. set: function (value) {
  64880. this.imageProcessingConfiguration.colorGradingTexture = value;
  64881. },
  64882. enumerable: true,
  64883. configurable: true
  64884. });
  64885. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", {
  64886. /**
  64887. * Gets wether the color grading effect is enabled.
  64888. */
  64889. get: function () {
  64890. return this.imageProcessingConfiguration.colorGradingEnabled;
  64891. },
  64892. /**
  64893. * Gets wether the color grading effect is enabled.
  64894. */
  64895. set: function (value) {
  64896. this.imageProcessingConfiguration.colorGradingEnabled = value;
  64897. },
  64898. enumerable: true,
  64899. configurable: true
  64900. });
  64901. Object.defineProperty(ImageProcessingPostProcess.prototype, "exposure", {
  64902. /**
  64903. * Gets exposure used in the effect.
  64904. */
  64905. get: function () {
  64906. return this.imageProcessingConfiguration.exposure;
  64907. },
  64908. /**
  64909. * Sets exposure used in the effect.
  64910. */
  64911. set: function (value) {
  64912. this.imageProcessingConfiguration.exposure = value;
  64913. },
  64914. enumerable: true,
  64915. configurable: true
  64916. });
  64917. Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", {
  64918. /**
  64919. * Gets wether tonemapping is enabled or not.
  64920. */
  64921. get: function () {
  64922. return this._imageProcessingConfiguration.toneMappingEnabled;
  64923. },
  64924. /**
  64925. * Sets wether tonemapping is enabled or not
  64926. */
  64927. set: function (value) {
  64928. this._imageProcessingConfiguration.toneMappingEnabled = value;
  64929. },
  64930. enumerable: true,
  64931. configurable: true
  64932. });
  64933. ;
  64934. ;
  64935. Object.defineProperty(ImageProcessingPostProcess.prototype, "contrast", {
  64936. /**
  64937. * Gets contrast used in the effect.
  64938. */
  64939. get: function () {
  64940. return this.imageProcessingConfiguration.contrast;
  64941. },
  64942. /**
  64943. * Sets contrast used in the effect.
  64944. */
  64945. set: function (value) {
  64946. this.imageProcessingConfiguration.contrast = value;
  64947. },
  64948. enumerable: true,
  64949. configurable: true
  64950. });
  64951. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", {
  64952. /**
  64953. * Gets Vignette stretch size.
  64954. */
  64955. get: function () {
  64956. return this.imageProcessingConfiguration.vignetteStretch;
  64957. },
  64958. /**
  64959. * Sets Vignette stretch size.
  64960. */
  64961. set: function (value) {
  64962. this.imageProcessingConfiguration.vignetteStretch = value;
  64963. },
  64964. enumerable: true,
  64965. configurable: true
  64966. });
  64967. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", {
  64968. /**
  64969. * Gets Vignette centre X Offset.
  64970. */
  64971. get: function () {
  64972. return this.imageProcessingConfiguration.vignetteCentreX;
  64973. },
  64974. /**
  64975. * Sets Vignette centre X Offset.
  64976. */
  64977. set: function (value) {
  64978. this.imageProcessingConfiguration.vignetteCentreX = value;
  64979. },
  64980. enumerable: true,
  64981. configurable: true
  64982. });
  64983. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", {
  64984. /**
  64985. * Gets Vignette centre Y Offset.
  64986. */
  64987. get: function () {
  64988. return this.imageProcessingConfiguration.vignetteCentreY;
  64989. },
  64990. /**
  64991. * Sets Vignette centre Y Offset.
  64992. */
  64993. set: function (value) {
  64994. this.imageProcessingConfiguration.vignetteCentreY = value;
  64995. },
  64996. enumerable: true,
  64997. configurable: true
  64998. });
  64999. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", {
  65000. /**
  65001. * Gets Vignette weight or intensity of the vignette effect.
  65002. */
  65003. get: function () {
  65004. return this.imageProcessingConfiguration.vignetteWeight;
  65005. },
  65006. /**
  65007. * Sets Vignette weight or intensity of the vignette effect.
  65008. */
  65009. set: function (value) {
  65010. this.imageProcessingConfiguration.vignetteWeight = value;
  65011. },
  65012. enumerable: true,
  65013. configurable: true
  65014. });
  65015. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", {
  65016. /**
  65017. * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  65018. * if vignetteEnabled is set to true.
  65019. */
  65020. get: function () {
  65021. return this.imageProcessingConfiguration.vignetteColor;
  65022. },
  65023. /**
  65024. * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  65025. * if vignetteEnabled is set to true.
  65026. */
  65027. set: function (value) {
  65028. this.imageProcessingConfiguration.vignetteColor = value;
  65029. },
  65030. enumerable: true,
  65031. configurable: true
  65032. });
  65033. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", {
  65034. /**
  65035. * Gets Camera field of view used by the Vignette effect.
  65036. */
  65037. get: function () {
  65038. return this.imageProcessingConfiguration.vignetteCameraFov;
  65039. },
  65040. /**
  65041. * Sets Camera field of view used by the Vignette effect.
  65042. */
  65043. set: function (value) {
  65044. this.imageProcessingConfiguration.vignetteCameraFov = value;
  65045. },
  65046. enumerable: true,
  65047. configurable: true
  65048. });
  65049. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  65050. /**
  65051. * Gets the vignette blend mode allowing different kind of effect.
  65052. */
  65053. get: function () {
  65054. return this.imageProcessingConfiguration.vignetteBlendMode;
  65055. },
  65056. /**
  65057. * Sets the vignette blend mode allowing different kind of effect.
  65058. */
  65059. set: function (value) {
  65060. this.imageProcessingConfiguration.vignetteBlendMode = value;
  65061. },
  65062. enumerable: true,
  65063. configurable: true
  65064. });
  65065. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  65066. /**
  65067. * Gets wether the vignette effect is enabled.
  65068. */
  65069. get: function () {
  65070. return this.imageProcessingConfiguration.vignetteEnabled;
  65071. },
  65072. /**
  65073. * Sets wether the vignette effect is enabled.
  65074. */
  65075. set: function (value) {
  65076. this.imageProcessingConfiguration.vignetteEnabled = value;
  65077. },
  65078. enumerable: true,
  65079. configurable: true
  65080. });
  65081. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  65082. /**
  65083. * Gets wether the input of the processing is in Gamma or Linear Space.
  65084. */
  65085. get: function () {
  65086. return this._fromLinearSpace;
  65087. },
  65088. /**
  65089. * Sets wether the input of the processing is in Gamma or Linear Space.
  65090. */
  65091. set: function (value) {
  65092. if (this._fromLinearSpace === value) {
  65093. return;
  65094. }
  65095. this._fromLinearSpace = value;
  65096. this._updateParameters();
  65097. },
  65098. enumerable: true,
  65099. configurable: true
  65100. });
  65101. ImageProcessingPostProcess.prototype.getClassName = function () {
  65102. return "ImageProcessingPostProcess";
  65103. };
  65104. ImageProcessingPostProcess.prototype._updateParameters = function () {
  65105. this._defines.FROMLINEARSPACE = this._fromLinearSpace;
  65106. this.imageProcessingConfiguration.prepareDefines(this._defines, true);
  65107. var defines = "";
  65108. for (var define in this._defines) {
  65109. if (this._defines[define]) {
  65110. defines += "#define " + define + ";\r\n";
  65111. }
  65112. }
  65113. var samplers = ["textureSampler"];
  65114. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
  65115. var uniforms = ["scale"];
  65116. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
  65117. this.updateEffect(defines, uniforms, samplers);
  65118. };
  65119. ImageProcessingPostProcess.prototype.dispose = function (camera) {
  65120. _super.prototype.dispose.call(this, camera);
  65121. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  65122. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  65123. }
  65124. this.imageProcessingConfiguration.applyByPostProcess = false;
  65125. };
  65126. __decorate([
  65127. BABYLON.serialize()
  65128. ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0);
  65129. return ImageProcessingPostProcess;
  65130. }(BABYLON.PostProcess));
  65131. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  65132. })(BABYLON || (BABYLON = {}));
  65133. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  65134. var BABYLON;
  65135. (function (BABYLON) {
  65136. var BlurPostProcess = /** @class */ (function (_super) {
  65137. __extends(BlurPostProcess, _super);
  65138. function BlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable, textureType) {
  65139. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  65140. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  65141. var _this = _super.call(this, name, "kernelBlur", ["delta", "direction"], null, options, camera, samplingMode, engine, reusable, null, textureType, "kernelBlur", { varyingCount: 0, depCount: 0 }, true) || this;
  65142. _this.direction = direction;
  65143. _this._packedFloat = false;
  65144. _this.onApplyObservable.add(function (effect) {
  65145. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  65146. });
  65147. _this.kernel = kernel;
  65148. return _this;
  65149. }
  65150. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  65151. /**
  65152. * Gets the length in pixels of the blur sample region
  65153. */
  65154. get: function () {
  65155. return this._idealKernel;
  65156. },
  65157. /**
  65158. * Sets the length in pixels of the blur sample region
  65159. */
  65160. set: function (v) {
  65161. if (this._idealKernel === v) {
  65162. return;
  65163. }
  65164. v = Math.max(v, 1);
  65165. this._idealKernel = v;
  65166. this._kernel = this._nearestBestKernel(v);
  65167. this._updateParameters();
  65168. },
  65169. enumerable: true,
  65170. configurable: true
  65171. });
  65172. Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
  65173. /**
  65174. * Gets wether or not the blur is unpacking/repacking floats
  65175. */
  65176. get: function () {
  65177. return this._packedFloat;
  65178. },
  65179. /**
  65180. * Sets wether or not the blur needs to unpack/repack floats
  65181. */
  65182. set: function (v) {
  65183. if (this._packedFloat === v) {
  65184. return;
  65185. }
  65186. this._packedFloat = v;
  65187. this._updateParameters();
  65188. },
  65189. enumerable: true,
  65190. configurable: true
  65191. });
  65192. BlurPostProcess.prototype._updateParameters = function () {
  65193. // Generate sampling offsets and weights
  65194. var N = this._kernel;
  65195. var centerIndex = (N - 1) / 2;
  65196. // Generate Gaussian sampling weights over kernel
  65197. var offsets = [];
  65198. var weights = [];
  65199. var totalWeight = 0;
  65200. for (var i = 0; i < N; i++) {
  65201. var u = i / (N - 1);
  65202. var w = this._gaussianWeight(u * 2.0 - 1);
  65203. offsets[i] = (i - centerIndex);
  65204. weights[i] = w;
  65205. totalWeight += w;
  65206. }
  65207. // Normalize weights
  65208. for (var i = 0; i < weights.length; i++) {
  65209. weights[i] /= totalWeight;
  65210. }
  65211. // Optimize: combine samples to take advantage of hardware linear sampling
  65212. // Walk from left to center, combining pairs (symmetrically)
  65213. var linearSamplingWeights = [];
  65214. var linearSamplingOffsets = [];
  65215. var linearSamplingMap = [];
  65216. for (var i = 0; i <= centerIndex; i += 2) {
  65217. var j = Math.min(i + 1, Math.floor(centerIndex));
  65218. var singleCenterSample = i === j;
  65219. if (singleCenterSample) {
  65220. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  65221. }
  65222. else {
  65223. var sharedCell = j === centerIndex;
  65224. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  65225. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  65226. if (offsetLinear === 0) {
  65227. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  65228. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  65229. }
  65230. else {
  65231. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  65232. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  65233. }
  65234. }
  65235. }
  65236. for (var i = 0; i < linearSamplingMap.length; i++) {
  65237. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  65238. linearSamplingWeights[i] = linearSamplingMap[i].w;
  65239. }
  65240. // Replace with optimized
  65241. offsets = linearSamplingOffsets;
  65242. weights = linearSamplingWeights;
  65243. // Generate shaders
  65244. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  65245. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  65246. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  65247. var defines = "";
  65248. for (var i = 0; i < varyingCount; i++) {
  65249. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  65250. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  65251. }
  65252. var depCount = 0;
  65253. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  65254. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  65255. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  65256. depCount++;
  65257. }
  65258. if (this.packedFloat) {
  65259. defines += "#define PACKEDFLOAT 1";
  65260. }
  65261. this.updateEffect(defines, null, null, {
  65262. varyingCount: varyingCount,
  65263. depCount: depCount
  65264. });
  65265. };
  65266. /**
  65267. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  65268. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  65269. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  65270. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  65271. * The gaps between physical kernels are compensated for in the weighting of the samples
  65272. * @param idealKernel Ideal blur kernel.
  65273. * @return Nearest best kernel.
  65274. */
  65275. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  65276. var v = Math.round(idealKernel);
  65277. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  65278. var k = _a[_i];
  65279. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  65280. return Math.max(k, 3);
  65281. }
  65282. }
  65283. return Math.max(v, 3);
  65284. };
  65285. /**
  65286. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  65287. * @param x The point on the Gaussian distribution to sample.
  65288. * @return the value of the Gaussian function at x.
  65289. */
  65290. BlurPostProcess.prototype._gaussianWeight = function (x) {
  65291. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  65292. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  65293. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  65294. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  65295. // truncated at around 1.3% of peak strength.
  65296. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  65297. var sigma = (1 / 3);
  65298. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  65299. var exponent = -((x * x) / (2.0 * sigma * sigma));
  65300. var weight = (1.0 / denominator) * Math.exp(exponent);
  65301. return weight;
  65302. };
  65303. /**
  65304. * Generates a string that can be used as a floating point number in GLSL.
  65305. * @param x Value to print.
  65306. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  65307. * @return GLSL float string.
  65308. */
  65309. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  65310. if (decimalFigures === void 0) { decimalFigures = 8; }
  65311. return x.toFixed(decimalFigures).replace(/0+$/, '');
  65312. };
  65313. return BlurPostProcess;
  65314. }(BABYLON.PostProcess));
  65315. BABYLON.BlurPostProcess = BlurPostProcess;
  65316. })(BABYLON || (BABYLON = {}));
  65317. //# sourceMappingURL=babylon.blurPostProcess.js.map
  65318. var BABYLON;
  65319. (function (BABYLON) {
  65320. var Bone = /** @class */ (function (_super) {
  65321. __extends(Bone, _super);
  65322. function Bone(name, skeleton, parentBone, localMatrix, restPose, baseMatrix, index) {
  65323. if (parentBone === void 0) { parentBone = null; }
  65324. if (localMatrix === void 0) { localMatrix = null; }
  65325. if (restPose === void 0) { restPose = null; }
  65326. if (baseMatrix === void 0) { baseMatrix = null; }
  65327. if (index === void 0) { index = null; }
  65328. var _this = _super.call(this, name, skeleton.getScene()) || this;
  65329. _this.name = name;
  65330. _this.children = new Array();
  65331. _this.animations = new Array();
  65332. // Set this value to map this bone to a different index in the transform matrices.
  65333. // Set this value to -1 to exclude the bone from the transform matrices.
  65334. _this._index = null;
  65335. _this._worldTransform = new BABYLON.Matrix();
  65336. _this._absoluteTransform = new BABYLON.Matrix();
  65337. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  65338. _this._scaleMatrix = BABYLON.Matrix.Identity();
  65339. _this._scaleVector = BABYLON.Vector3.One();
  65340. _this._negateScaleChildren = BABYLON.Vector3.One();
  65341. _this._scalingDeterminant = 1;
  65342. _this._skeleton = skeleton;
  65343. _this._localMatrix = localMatrix ? localMatrix : BABYLON.Matrix.Identity();
  65344. _this._restPose = restPose ? restPose : _this._localMatrix.clone();
  65345. _this._baseMatrix = baseMatrix ? baseMatrix : _this._localMatrix.clone();
  65346. _this._index = index;
  65347. skeleton.bones.push(_this);
  65348. _this.setParent(parentBone, false);
  65349. _this._updateDifferenceMatrix();
  65350. return _this;
  65351. }
  65352. Object.defineProperty(Bone.prototype, "_matrix", {
  65353. get: function () {
  65354. return this._localMatrix;
  65355. },
  65356. set: function (val) {
  65357. if (this._localMatrix) {
  65358. this._localMatrix.copyFrom(val);
  65359. }
  65360. else {
  65361. this._localMatrix = val;
  65362. }
  65363. },
  65364. enumerable: true,
  65365. configurable: true
  65366. });
  65367. // Members
  65368. Bone.prototype.getSkeleton = function () {
  65369. return this._skeleton;
  65370. };
  65371. Bone.prototype.getParent = function () {
  65372. return this._parent;
  65373. };
  65374. Bone.prototype.setParent = function (parent, updateDifferenceMatrix) {
  65375. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  65376. if (this._parent === parent) {
  65377. return;
  65378. }
  65379. if (this._parent) {
  65380. var index = this._parent.children.indexOf(this);
  65381. if (index !== -1) {
  65382. this._parent.children.splice(index, 1);
  65383. }
  65384. }
  65385. this._parent = parent;
  65386. if (this._parent) {
  65387. this._parent.children.push(this);
  65388. }
  65389. if (updateDifferenceMatrix) {
  65390. this._updateDifferenceMatrix();
  65391. }
  65392. };
  65393. Bone.prototype.getLocalMatrix = function () {
  65394. return this._localMatrix;
  65395. };
  65396. Bone.prototype.getBaseMatrix = function () {
  65397. return this._baseMatrix;
  65398. };
  65399. Bone.prototype.getRestPose = function () {
  65400. return this._restPose;
  65401. };
  65402. Bone.prototype.returnToRest = function () {
  65403. this.updateMatrix(this._restPose.clone());
  65404. };
  65405. Bone.prototype.getWorldMatrix = function () {
  65406. return this._worldTransform;
  65407. };
  65408. Bone.prototype.getInvertedAbsoluteTransform = function () {
  65409. return this._invertedAbsoluteTransform;
  65410. };
  65411. Bone.prototype.getAbsoluteTransform = function () {
  65412. return this._absoluteTransform;
  65413. };
  65414. Object.defineProperty(Bone.prototype, "position", {
  65415. // Properties (matches AbstractMesh properties)
  65416. get: function () {
  65417. return this.getPosition();
  65418. },
  65419. set: function (newPosition) {
  65420. this.setPosition(newPosition);
  65421. },
  65422. enumerable: true,
  65423. configurable: true
  65424. });
  65425. Object.defineProperty(Bone.prototype, "rotation", {
  65426. get: function () {
  65427. return this.getRotation();
  65428. },
  65429. set: function (newRotation) {
  65430. this.setRotation(newRotation);
  65431. },
  65432. enumerable: true,
  65433. configurable: true
  65434. });
  65435. Object.defineProperty(Bone.prototype, "rotationQuaternion", {
  65436. get: function () {
  65437. return this.getRotationQuaternion();
  65438. },
  65439. set: function (newRotation) {
  65440. this.setRotationQuaternion(newRotation);
  65441. },
  65442. enumerable: true,
  65443. configurable: true
  65444. });
  65445. Object.defineProperty(Bone.prototype, "scaling", {
  65446. get: function () {
  65447. return this.getScale();
  65448. },
  65449. set: function (newScaling) {
  65450. this.setScale(newScaling.x, newScaling.y, newScaling.z);
  65451. },
  65452. enumerable: true,
  65453. configurable: true
  65454. });
  65455. // Methods
  65456. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix) {
  65457. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  65458. this._baseMatrix = matrix.clone();
  65459. this._localMatrix = matrix.clone();
  65460. this._skeleton._markAsDirty();
  65461. if (updateDifferenceMatrix) {
  65462. this._updateDifferenceMatrix();
  65463. }
  65464. };
  65465. Bone.prototype._updateDifferenceMatrix = function (rootMatrix) {
  65466. if (!rootMatrix) {
  65467. rootMatrix = this._baseMatrix;
  65468. }
  65469. if (this._parent) {
  65470. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  65471. }
  65472. else {
  65473. this._absoluteTransform.copyFrom(rootMatrix);
  65474. }
  65475. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  65476. for (var index = 0; index < this.children.length; index++) {
  65477. this.children[index]._updateDifferenceMatrix();
  65478. }
  65479. this._scalingDeterminant = (this._absoluteTransform.determinant() < 0 ? -1 : 1);
  65480. };
  65481. Bone.prototype.markAsDirty = function () {
  65482. this._currentRenderId++;
  65483. this._skeleton._markAsDirty();
  65484. };
  65485. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  65486. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  65487. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  65488. // all animation may be coming from a library skeleton, so may need to create animation
  65489. if (this.animations.length === 0) {
  65490. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  65491. this.animations[0].setKeys([]);
  65492. }
  65493. // get animation info / verify there is such a range from the source bone
  65494. var sourceRange = source.animations[0].getRange(rangeName);
  65495. if (!sourceRange) {
  65496. return false;
  65497. }
  65498. var from = sourceRange.from;
  65499. var to = sourceRange.to;
  65500. var sourceKeys = source.animations[0].getKeys();
  65501. // rescaling prep
  65502. var sourceBoneLength = source.length;
  65503. var sourceParent = source.getParent();
  65504. var parent = this.getParent();
  65505. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  65506. var parentRatio = parentScalingReqd && parent && sourceParent ? parent.length / sourceParent.length : 1;
  65507. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  65508. var destKeys = this.animations[0].getKeys();
  65509. // loop vars declaration
  65510. var orig;
  65511. var origTranslation;
  65512. var mat;
  65513. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  65514. orig = sourceKeys[key];
  65515. if (orig.frame >= from && orig.frame <= to) {
  65516. if (rescaleAsRequired) {
  65517. mat = orig.value.clone();
  65518. // scale based on parent ratio, when bone has parent
  65519. if (parentScalingReqd) {
  65520. origTranslation = mat.getTranslation();
  65521. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  65522. // scale based on skeleton dimension ratio when root bone, and value is passed
  65523. }
  65524. else if (dimensionsScalingReqd && skelDimensionsRatio) {
  65525. origTranslation = mat.getTranslation();
  65526. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  65527. // use original when root bone, and no data for skelDimensionsRatio
  65528. }
  65529. else {
  65530. mat = orig.value;
  65531. }
  65532. }
  65533. else {
  65534. mat = orig.value;
  65535. }
  65536. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  65537. }
  65538. }
  65539. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  65540. return true;
  65541. };
  65542. /**
  65543. * Translate the bone in local or world space.
  65544. * @param vec The amount to translate the bone.
  65545. * @param space The space that the translation is in.
  65546. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  65547. */
  65548. Bone.prototype.translate = function (vec, space, mesh) {
  65549. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  65550. var lm = this.getLocalMatrix();
  65551. if (space == BABYLON.Space.LOCAL) {
  65552. lm.m[12] += vec.x;
  65553. lm.m[13] += vec.y;
  65554. lm.m[14] += vec.z;
  65555. }
  65556. else {
  65557. var wm = null;
  65558. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  65559. if (mesh) {
  65560. wm = mesh.getWorldMatrix();
  65561. }
  65562. this._skeleton.computeAbsoluteTransforms();
  65563. var tmat = Bone._tmpMats[0];
  65564. var tvec = Bone._tmpVecs[0];
  65565. if (this._parent) {
  65566. if (mesh && wm) {
  65567. tmat.copyFrom(this._parent.getAbsoluteTransform());
  65568. tmat.multiplyToRef(wm, tmat);
  65569. }
  65570. else {
  65571. tmat.copyFrom(this._parent.getAbsoluteTransform());
  65572. }
  65573. }
  65574. tmat.m[12] = 0;
  65575. tmat.m[13] = 0;
  65576. tmat.m[14] = 0;
  65577. tmat.invert();
  65578. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  65579. lm.m[12] += tvec.x;
  65580. lm.m[13] += tvec.y;
  65581. lm.m[14] += tvec.z;
  65582. }
  65583. this.markAsDirty();
  65584. };
  65585. /**
  65586. * Set the postion of the bone in local or world space.
  65587. * @param position The position to set the bone.
  65588. * @param space The space that the position is in.
  65589. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  65590. */
  65591. Bone.prototype.setPosition = function (position, space, mesh) {
  65592. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  65593. var lm = this.getLocalMatrix();
  65594. if (space == BABYLON.Space.LOCAL) {
  65595. lm.m[12] = position.x;
  65596. lm.m[13] = position.y;
  65597. lm.m[14] = position.z;
  65598. }
  65599. else {
  65600. var wm = null;
  65601. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  65602. if (mesh) {
  65603. wm = mesh.getWorldMatrix();
  65604. }
  65605. this._skeleton.computeAbsoluteTransforms();
  65606. var tmat = Bone._tmpMats[0];
  65607. var vec = Bone._tmpVecs[0];
  65608. if (this._parent) {
  65609. if (mesh && wm) {
  65610. tmat.copyFrom(this._parent.getAbsoluteTransform());
  65611. tmat.multiplyToRef(wm, tmat);
  65612. }
  65613. else {
  65614. tmat.copyFrom(this._parent.getAbsoluteTransform());
  65615. }
  65616. }
  65617. tmat.invert();
  65618. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  65619. lm.m[12] = vec.x;
  65620. lm.m[13] = vec.y;
  65621. lm.m[14] = vec.z;
  65622. }
  65623. this.markAsDirty();
  65624. };
  65625. /**
  65626. * Set the absolute postion of the bone (world space).
  65627. * @param position The position to set the bone.
  65628. * @param mesh The mesh that this bone is attached to.
  65629. */
  65630. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  65631. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  65632. };
  65633. /**
  65634. * Set the scale of the bone on the x, y and z axes.
  65635. * @param x The scale of the bone on the x axis.
  65636. * @param x The scale of the bone on the y axis.
  65637. * @param z The scale of the bone on the z axis.
  65638. * @param scaleChildren Set this to true if children of the bone should be scaled.
  65639. */
  65640. Bone.prototype.setScale = function (x, y, z, scaleChildren) {
  65641. if (scaleChildren === void 0) { scaleChildren = false; }
  65642. if (this.animations[0] && !this.animations[0].hasRunningRuntimeAnimations) {
  65643. if (!scaleChildren) {
  65644. this._negateScaleChildren.x = 1 / x;
  65645. this._negateScaleChildren.y = 1 / y;
  65646. this._negateScaleChildren.z = 1 / z;
  65647. }
  65648. this._syncScaleVector();
  65649. }
  65650. this.scale(x / this._scaleVector.x, y / this._scaleVector.y, z / this._scaleVector.z, scaleChildren);
  65651. };
  65652. /**
  65653. * Scale the bone on the x, y and z axes.
  65654. * @param x The amount to scale the bone on the x axis.
  65655. * @param x The amount to scale the bone on the y axis.
  65656. * @param z The amount to scale the bone on the z axis.
  65657. * @param scaleChildren Set this to true if children of the bone should be scaled.
  65658. */
  65659. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  65660. if (scaleChildren === void 0) { scaleChildren = false; }
  65661. var locMat = this.getLocalMatrix();
  65662. var origLocMat = Bone._tmpMats[0];
  65663. origLocMat.copyFrom(locMat);
  65664. var origLocMatInv = Bone._tmpMats[1];
  65665. origLocMatInv.copyFrom(origLocMat);
  65666. origLocMatInv.invert();
  65667. var scaleMat = Bone._tmpMats[2];
  65668. BABYLON.Matrix.FromValuesToRef(x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1, scaleMat);
  65669. this._scaleMatrix.multiplyToRef(scaleMat, this._scaleMatrix);
  65670. this._scaleVector.x *= x;
  65671. this._scaleVector.y *= y;
  65672. this._scaleVector.z *= z;
  65673. locMat.multiplyToRef(origLocMatInv, locMat);
  65674. locMat.multiplyToRef(scaleMat, locMat);
  65675. locMat.multiplyToRef(origLocMat, locMat);
  65676. var parent = this.getParent();
  65677. if (parent) {
  65678. locMat.multiplyToRef(parent.getAbsoluteTransform(), this.getAbsoluteTransform());
  65679. }
  65680. else {
  65681. this.getAbsoluteTransform().copyFrom(locMat);
  65682. }
  65683. var len = this.children.length;
  65684. scaleMat.invert();
  65685. for (var i = 0; i < len; i++) {
  65686. var child = this.children[i];
  65687. var cm = child.getLocalMatrix();
  65688. cm.multiplyToRef(scaleMat, cm);
  65689. var lm = child.getLocalMatrix();
  65690. lm.m[12] *= x;
  65691. lm.m[13] *= y;
  65692. lm.m[14] *= z;
  65693. }
  65694. this.computeAbsoluteTransforms();
  65695. if (scaleChildren) {
  65696. for (var i = 0; i < len; i++) {
  65697. this.children[i].scale(x, y, z, scaleChildren);
  65698. }
  65699. }
  65700. this.markAsDirty();
  65701. };
  65702. /**
  65703. * Set the yaw, pitch, and roll of the bone in local or world space.
  65704. * @param yaw The rotation of the bone on the y axis.
  65705. * @param pitch The rotation of the bone on the x axis.
  65706. * @param roll The rotation of the bone on the z axis.
  65707. * @param space The space that the axes of rotation are in.
  65708. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  65709. */
  65710. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  65711. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  65712. var rotMat = Bone._tmpMats[0];
  65713. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  65714. var rotMatInv = Bone._tmpMats[1];
  65715. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  65716. rotMatInv.multiplyToRef(rotMat, rotMat);
  65717. this._rotateWithMatrix(rotMat, space, mesh);
  65718. };
  65719. /**
  65720. * Rotate the bone on an axis in local or world space.
  65721. * @param axis The axis to rotate the bone on.
  65722. * @param amount The amount to rotate the bone.
  65723. * @param space The space that the axis is in.
  65724. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  65725. */
  65726. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  65727. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  65728. var rmat = Bone._tmpMats[0];
  65729. rmat.m[12] = 0;
  65730. rmat.m[13] = 0;
  65731. rmat.m[14] = 0;
  65732. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  65733. this._rotateWithMatrix(rmat, space, mesh);
  65734. };
  65735. /**
  65736. * Set the rotation of the bone to a particular axis angle in local or world space.
  65737. * @param axis The axis to rotate the bone on.
  65738. * @param angle The angle that the bone should be rotated to.
  65739. * @param space The space that the axis is in.
  65740. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  65741. */
  65742. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  65743. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  65744. var rotMat = Bone._tmpMats[0];
  65745. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  65746. var rotMatInv = Bone._tmpMats[1];
  65747. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  65748. rotMatInv.multiplyToRef(rotMat, rotMat);
  65749. this._rotateWithMatrix(rotMat, space, mesh);
  65750. };
  65751. /**
  65752. * Set the euler rotation of the bone in local of world space.
  65753. * @param rotation The euler rotation that the bone should be set to.
  65754. * @param space The space that the rotation is in.
  65755. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  65756. */
  65757. Bone.prototype.setRotation = function (rotation, space, mesh) {
  65758. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  65759. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  65760. };
  65761. /**
  65762. * Set the quaternion rotation of the bone in local of world space.
  65763. * @param quat The quaternion rotation that the bone should be set to.
  65764. * @param space The space that the rotation is in.
  65765. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  65766. */
  65767. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  65768. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  65769. var rotMatInv = Bone._tmpMats[0];
  65770. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  65771. var rotMat = Bone._tmpMats[1];
  65772. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  65773. rotMatInv.multiplyToRef(rotMat, rotMat);
  65774. this._rotateWithMatrix(rotMat, space, mesh);
  65775. };
  65776. /**
  65777. * Set the rotation matrix of the bone in local of world space.
  65778. * @param rotMat The rotation matrix that the bone should be set to.
  65779. * @param space The space that the rotation is in.
  65780. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  65781. */
  65782. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  65783. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  65784. var rotMatInv = Bone._tmpMats[0];
  65785. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  65786. var rotMat2 = Bone._tmpMats[1];
  65787. rotMat2.copyFrom(rotMat);
  65788. rotMatInv.multiplyToRef(rotMat, rotMat2);
  65789. this._rotateWithMatrix(rotMat2, space, mesh);
  65790. };
  65791. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  65792. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  65793. var lmat = this.getLocalMatrix();
  65794. var lx = lmat.m[12];
  65795. var ly = lmat.m[13];
  65796. var lz = lmat.m[14];
  65797. var parent = this.getParent();
  65798. var parentScale = Bone._tmpMats[3];
  65799. var parentScaleInv = Bone._tmpMats[4];
  65800. if (parent) {
  65801. if (space == BABYLON.Space.WORLD) {
  65802. if (mesh) {
  65803. parentScale.copyFrom(mesh.getWorldMatrix());
  65804. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  65805. }
  65806. else {
  65807. parentScale.copyFrom(parent.getAbsoluteTransform());
  65808. }
  65809. }
  65810. else {
  65811. parentScale = parent._scaleMatrix;
  65812. }
  65813. parentScaleInv.copyFrom(parentScale);
  65814. parentScaleInv.invert();
  65815. lmat.multiplyToRef(parentScale, lmat);
  65816. lmat.multiplyToRef(rmat, lmat);
  65817. lmat.multiplyToRef(parentScaleInv, lmat);
  65818. }
  65819. else {
  65820. if (space == BABYLON.Space.WORLD && mesh) {
  65821. parentScale.copyFrom(mesh.getWorldMatrix());
  65822. parentScaleInv.copyFrom(parentScale);
  65823. parentScaleInv.invert();
  65824. lmat.multiplyToRef(parentScale, lmat);
  65825. lmat.multiplyToRef(rmat, lmat);
  65826. lmat.multiplyToRef(parentScaleInv, lmat);
  65827. }
  65828. else {
  65829. lmat.multiplyToRef(rmat, lmat);
  65830. }
  65831. }
  65832. lmat.m[12] = lx;
  65833. lmat.m[13] = ly;
  65834. lmat.m[14] = lz;
  65835. this.computeAbsoluteTransforms();
  65836. this.markAsDirty();
  65837. };
  65838. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, space, mesh) {
  65839. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  65840. if (space == BABYLON.Space.WORLD) {
  65841. var scaleMatrix = Bone._tmpMats[2];
  65842. scaleMatrix.copyFrom(this._scaleMatrix);
  65843. rotMatInv.copyFrom(this.getAbsoluteTransform());
  65844. if (mesh) {
  65845. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  65846. var meshScale = Bone._tmpMats[3];
  65847. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, meshScale);
  65848. scaleMatrix.multiplyToRef(meshScale, scaleMatrix);
  65849. }
  65850. rotMatInv.invert();
  65851. scaleMatrix.m[0] *= this._scalingDeterminant;
  65852. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  65853. }
  65854. else {
  65855. rotMatInv.copyFrom(this.getLocalMatrix());
  65856. rotMatInv.invert();
  65857. var scaleMatrix = Bone._tmpMats[2];
  65858. scaleMatrix.copyFrom(this._scaleMatrix);
  65859. if (this._parent) {
  65860. var pscaleMatrix = Bone._tmpMats[3];
  65861. pscaleMatrix.copyFrom(this._parent._scaleMatrix);
  65862. pscaleMatrix.invert();
  65863. pscaleMatrix.multiplyToRef(rotMatInv, rotMatInv);
  65864. }
  65865. else {
  65866. scaleMatrix.m[0] *= this._scalingDeterminant;
  65867. }
  65868. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  65869. }
  65870. };
  65871. /**
  65872. * Get the scale of the bone
  65873. * @returns the scale of the bone
  65874. */
  65875. Bone.prototype.getScale = function () {
  65876. return this._scaleVector.clone();
  65877. };
  65878. /**
  65879. * Copy the scale of the bone to a vector3.
  65880. * @param result The vector3 to copy the scale to
  65881. */
  65882. Bone.prototype.getScaleToRef = function (result) {
  65883. result.copyFrom(this._scaleVector);
  65884. };
  65885. /**
  65886. * Get the position of the bone in local or world space.
  65887. * @param space The space that the returned position is in.
  65888. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  65889. * @returns The position of the bone
  65890. */
  65891. Bone.prototype.getPosition = function (space, mesh) {
  65892. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  65893. if (mesh === void 0) { mesh = null; }
  65894. var pos = BABYLON.Vector3.Zero();
  65895. this.getPositionToRef(space, mesh, pos);
  65896. return pos;
  65897. };
  65898. /**
  65899. * Copy the position of the bone to a vector3 in local or world space.
  65900. * @param space The space that the returned position is in.
  65901. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  65902. * @param result The vector3 to copy the position to.
  65903. */
  65904. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  65905. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  65906. if (space == BABYLON.Space.LOCAL) {
  65907. var lm = this.getLocalMatrix();
  65908. result.x = lm.m[12];
  65909. result.y = lm.m[13];
  65910. result.z = lm.m[14];
  65911. }
  65912. else {
  65913. var wm = null;
  65914. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  65915. if (mesh) {
  65916. wm = mesh.getWorldMatrix();
  65917. }
  65918. this._skeleton.computeAbsoluteTransforms();
  65919. var tmat = Bone._tmpMats[0];
  65920. if (mesh && wm) {
  65921. tmat.copyFrom(this.getAbsoluteTransform());
  65922. tmat.multiplyToRef(wm, tmat);
  65923. }
  65924. else {
  65925. tmat = this.getAbsoluteTransform();
  65926. }
  65927. result.x = tmat.m[12];
  65928. result.y = tmat.m[13];
  65929. result.z = tmat.m[14];
  65930. }
  65931. };
  65932. /**
  65933. * Get the absolute position of the bone (world space).
  65934. * @param mesh The mesh that this bone is attached to.
  65935. * @returns The absolute position of the bone
  65936. */
  65937. Bone.prototype.getAbsolutePosition = function (mesh) {
  65938. if (mesh === void 0) { mesh = null; }
  65939. var pos = BABYLON.Vector3.Zero();
  65940. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  65941. return pos;
  65942. };
  65943. /**
  65944. * Copy the absolute position of the bone (world space) to the result param.
  65945. * @param mesh The mesh that this bone is attached to.
  65946. * @param result The vector3 to copy the absolute position to.
  65947. */
  65948. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  65949. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  65950. };
  65951. /**
  65952. * Compute the absolute transforms of this bone and its children.
  65953. */
  65954. Bone.prototype.computeAbsoluteTransforms = function () {
  65955. if (this._parent) {
  65956. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  65957. }
  65958. else {
  65959. this._absoluteTransform.copyFrom(this._localMatrix);
  65960. var poseMatrix = this._skeleton.getPoseMatrix();
  65961. if (poseMatrix) {
  65962. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  65963. }
  65964. }
  65965. var children = this.children;
  65966. var len = children.length;
  65967. for (var i = 0; i < len; i++) {
  65968. children[i].computeAbsoluteTransforms();
  65969. }
  65970. };
  65971. Bone.prototype._syncScaleVector = function () {
  65972. var lm = this.getLocalMatrix();
  65973. var xsq = (lm.m[0] * lm.m[0] + lm.m[1] * lm.m[1] + lm.m[2] * lm.m[2]);
  65974. var ysq = (lm.m[4] * lm.m[4] + lm.m[5] * lm.m[5] + lm.m[6] * lm.m[6]);
  65975. var zsq = (lm.m[8] * lm.m[8] + lm.m[9] * lm.m[9] + lm.m[10] * lm.m[10]);
  65976. var xs = lm.m[0] * lm.m[1] * lm.m[2] * lm.m[3] < 0 ? -1 : 1;
  65977. var ys = lm.m[4] * lm.m[5] * lm.m[6] * lm.m[7] < 0 ? -1 : 1;
  65978. var zs = lm.m[8] * lm.m[9] * lm.m[10] * lm.m[11] < 0 ? -1 : 1;
  65979. this._scaleVector.x = xs * Math.sqrt(xsq);
  65980. this._scaleVector.y = ys * Math.sqrt(ysq);
  65981. this._scaleVector.z = zs * Math.sqrt(zsq);
  65982. if (this._parent) {
  65983. this._scaleVector.x /= this._parent._negateScaleChildren.x;
  65984. this._scaleVector.y /= this._parent._negateScaleChildren.y;
  65985. this._scaleVector.z /= this._parent._negateScaleChildren.z;
  65986. }
  65987. 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);
  65988. };
  65989. /**
  65990. * Get the world direction from an axis that is in the local space of the bone.
  65991. * @param localAxis The local direction that is used to compute the world direction.
  65992. * @param mesh The mesh that this bone is attached to.
  65993. * @returns The world direction
  65994. */
  65995. Bone.prototype.getDirection = function (localAxis, mesh) {
  65996. if (mesh === void 0) { mesh = null; }
  65997. var result = BABYLON.Vector3.Zero();
  65998. this.getDirectionToRef(localAxis, mesh, result);
  65999. return result;
  66000. };
  66001. /**
  66002. * Copy the world direction to a vector3 from an axis that is in the local space of the bone.
  66003. * @param localAxis The local direction that is used to compute the world direction.
  66004. * @param mesh The mesh that this bone is attached to.
  66005. * @param result The vector3 that the world direction will be copied to.
  66006. */
  66007. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  66008. if (mesh === void 0) { mesh = null; }
  66009. var wm = null;
  66010. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  66011. if (mesh) {
  66012. wm = mesh.getWorldMatrix();
  66013. }
  66014. this._skeleton.computeAbsoluteTransforms();
  66015. var mat = Bone._tmpMats[0];
  66016. mat.copyFrom(this.getAbsoluteTransform());
  66017. if (mesh && wm) {
  66018. mat.multiplyToRef(wm, mat);
  66019. }
  66020. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  66021. result.normalize();
  66022. };
  66023. /**
  66024. * Get the euler rotation of the bone in local or world space.
  66025. * @param space The space that the rotation should be in.
  66026. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  66027. * @returns The euler rotation
  66028. */
  66029. Bone.prototype.getRotation = function (space, mesh) {
  66030. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  66031. if (mesh === void 0) { mesh = null; }
  66032. var result = BABYLON.Vector3.Zero();
  66033. this.getRotationToRef(space, mesh, result);
  66034. return result;
  66035. };
  66036. /**
  66037. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space.
  66038. * @param space The space that the rotation should be in.
  66039. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  66040. * @param result The vector3 that the rotation should be copied to.
  66041. */
  66042. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  66043. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  66044. if (mesh === void 0) { mesh = null; }
  66045. var quat = Bone._tmpQuat;
  66046. this.getRotationQuaternionToRef(space, mesh, quat);
  66047. quat.toEulerAnglesToRef(result);
  66048. };
  66049. /**
  66050. * Get the quaternion rotation of the bone in either local or world space.
  66051. * @param space The space that the rotation should be in.
  66052. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  66053. * @returns The quaternion rotation
  66054. */
  66055. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  66056. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  66057. if (mesh === void 0) { mesh = null; }
  66058. var result = BABYLON.Quaternion.Identity();
  66059. this.getRotationQuaternionToRef(space, mesh, result);
  66060. return result;
  66061. };
  66062. /**
  66063. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space.
  66064. * @param space The space that the rotation should be in.
  66065. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  66066. * @param result The quaternion that the rotation should be copied to.
  66067. */
  66068. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  66069. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  66070. if (mesh === void 0) { mesh = null; }
  66071. if (space == BABYLON.Space.LOCAL) {
  66072. this.getLocalMatrix().decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  66073. }
  66074. else {
  66075. var mat = Bone._tmpMats[0];
  66076. var amat = this.getAbsoluteTransform();
  66077. if (mesh) {
  66078. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  66079. }
  66080. else {
  66081. mat.copyFrom(amat);
  66082. }
  66083. mat.m[0] *= this._scalingDeterminant;
  66084. mat.m[1] *= this._scalingDeterminant;
  66085. mat.m[2] *= this._scalingDeterminant;
  66086. mat.decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  66087. }
  66088. };
  66089. /**
  66090. * Get the rotation matrix of the bone in local or world space.
  66091. * @param space The space that the rotation should be in.
  66092. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  66093. * @returns The rotation matrix
  66094. */
  66095. Bone.prototype.getRotationMatrix = function (space, mesh) {
  66096. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  66097. var result = BABYLON.Matrix.Identity();
  66098. this.getRotationMatrixToRef(space, mesh, result);
  66099. return result;
  66100. };
  66101. /**
  66102. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space.
  66103. * @param space The space that the rotation should be in.
  66104. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  66105. * @param result The quaternion that the rotation should be copied to.
  66106. */
  66107. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  66108. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  66109. if (space == BABYLON.Space.LOCAL) {
  66110. this.getLocalMatrix().getRotationMatrixToRef(result);
  66111. }
  66112. else {
  66113. var mat = Bone._tmpMats[0];
  66114. var amat = this.getAbsoluteTransform();
  66115. if (mesh) {
  66116. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  66117. }
  66118. else {
  66119. mat.copyFrom(amat);
  66120. }
  66121. mat.m[0] *= this._scalingDeterminant;
  66122. mat.m[1] *= this._scalingDeterminant;
  66123. mat.m[2] *= this._scalingDeterminant;
  66124. mat.getRotationMatrixToRef(result);
  66125. }
  66126. };
  66127. /**
  66128. * Get the world position of a point that is in the local space of the bone.
  66129. * @param position The local position
  66130. * @param mesh The mesh that this bone is attached to.
  66131. * @returns The world position
  66132. */
  66133. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  66134. if (mesh === void 0) { mesh = null; }
  66135. var result = BABYLON.Vector3.Zero();
  66136. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  66137. return result;
  66138. };
  66139. /**
  66140. * Get the world position of a point that is in the local space of the bone and copy it to the result param.
  66141. * @param position The local position
  66142. * @param mesh The mesh that this bone is attached to.
  66143. * @param result The vector3 that the world position should be copied to.
  66144. */
  66145. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  66146. if (mesh === void 0) { mesh = null; }
  66147. var wm = null;
  66148. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  66149. if (mesh) {
  66150. wm = mesh.getWorldMatrix();
  66151. }
  66152. this._skeleton.computeAbsoluteTransforms();
  66153. var tmat = Bone._tmpMats[0];
  66154. if (mesh && wm) {
  66155. tmat.copyFrom(this.getAbsoluteTransform());
  66156. tmat.multiplyToRef(wm, tmat);
  66157. }
  66158. else {
  66159. tmat = this.getAbsoluteTransform();
  66160. }
  66161. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  66162. };
  66163. /**
  66164. * Get the local position of a point that is in world space.
  66165. * @param position The world position
  66166. * @param mesh The mesh that this bone is attached to.
  66167. * @returns The local position
  66168. */
  66169. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  66170. if (mesh === void 0) { mesh = null; }
  66171. var result = BABYLON.Vector3.Zero();
  66172. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  66173. return result;
  66174. };
  66175. /**
  66176. * Get the local position of a point that is in world space and copy it to the result param.
  66177. * @param position The world position
  66178. * @param mesh The mesh that this bone is attached to.
  66179. * @param result The vector3 that the local position should be copied to.
  66180. */
  66181. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  66182. if (mesh === void 0) { mesh = null; }
  66183. var wm = null;
  66184. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  66185. if (mesh) {
  66186. wm = mesh.getWorldMatrix();
  66187. }
  66188. this._skeleton.computeAbsoluteTransforms();
  66189. var tmat = Bone._tmpMats[0];
  66190. tmat.copyFrom(this.getAbsoluteTransform());
  66191. if (mesh && wm) {
  66192. tmat.multiplyToRef(wm, tmat);
  66193. }
  66194. tmat.invert();
  66195. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  66196. };
  66197. Bone._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  66198. Bone._tmpQuat = BABYLON.Quaternion.Identity();
  66199. Bone._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  66200. return Bone;
  66201. }(BABYLON.Node));
  66202. BABYLON.Bone = Bone;
  66203. })(BABYLON || (BABYLON = {}));
  66204. //# sourceMappingURL=babylon.bone.js.map
  66205. var BABYLON;
  66206. (function (BABYLON) {
  66207. var BoneIKController = /** @class */ (function () {
  66208. function BoneIKController(mesh, bone, options) {
  66209. this.targetPosition = BABYLON.Vector3.Zero();
  66210. this.poleTargetPosition = BABYLON.Vector3.Zero();
  66211. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  66212. this.poleAngle = 0;
  66213. this.slerpAmount = 1;
  66214. this._bone1Quat = BABYLON.Quaternion.Identity();
  66215. this._bone1Mat = BABYLON.Matrix.Identity();
  66216. this._bone2Ang = Math.PI;
  66217. this._maxAngle = Math.PI;
  66218. this._rightHandedSystem = false;
  66219. this._bendAxis = BABYLON.Vector3.Right();
  66220. this._slerping = false;
  66221. this._adjustRoll = 0;
  66222. this._bone2 = bone;
  66223. this._bone1 = bone.getParent();
  66224. if (!this._bone1) {
  66225. return;
  66226. }
  66227. this.mesh = mesh;
  66228. var bonePos = bone.getPosition();
  66229. if (bone.getAbsoluteTransform().determinant() > 0) {
  66230. this._rightHandedSystem = true;
  66231. this._bendAxis.x = 0;
  66232. this._bendAxis.y = 0;
  66233. this._bendAxis.z = -1;
  66234. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  66235. this._adjustRoll = Math.PI * .5;
  66236. this._bendAxis.z = 1;
  66237. }
  66238. }
  66239. if (this._bone1.length) {
  66240. var boneScale1 = this._bone1.getScale();
  66241. var boneScale2 = this._bone2.getScale();
  66242. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  66243. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  66244. }
  66245. else if (this._bone1.children[0]) {
  66246. mesh.computeWorldMatrix(true);
  66247. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  66248. var pos2 = this._bone2.getAbsolutePosition(mesh);
  66249. var pos3 = this._bone1.getAbsolutePosition(mesh);
  66250. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  66251. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  66252. }
  66253. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  66254. this.maxAngle = Math.PI;
  66255. if (options) {
  66256. if (options.targetMesh) {
  66257. this.targetMesh = options.targetMesh;
  66258. this.targetMesh.computeWorldMatrix(true);
  66259. }
  66260. if (options.poleTargetMesh) {
  66261. this.poleTargetMesh = options.poleTargetMesh;
  66262. this.poleTargetMesh.computeWorldMatrix(true);
  66263. }
  66264. else if (options.poleTargetBone) {
  66265. this.poleTargetBone = options.poleTargetBone;
  66266. }
  66267. else if (this._bone1.getParent()) {
  66268. this.poleTargetBone = this._bone1.getParent();
  66269. }
  66270. if (options.poleTargetLocalOffset) {
  66271. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  66272. }
  66273. if (options.poleAngle) {
  66274. this.poleAngle = options.poleAngle;
  66275. }
  66276. if (options.bendAxis) {
  66277. this._bendAxis.copyFrom(options.bendAxis);
  66278. }
  66279. if (options.maxAngle) {
  66280. this.maxAngle = options.maxAngle;
  66281. }
  66282. if (options.slerpAmount) {
  66283. this.slerpAmount = options.slerpAmount;
  66284. }
  66285. }
  66286. }
  66287. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  66288. get: function () {
  66289. return this._maxAngle;
  66290. },
  66291. set: function (value) {
  66292. this._setMaxAngle(value);
  66293. },
  66294. enumerable: true,
  66295. configurable: true
  66296. });
  66297. BoneIKController.prototype._setMaxAngle = function (ang) {
  66298. if (ang < 0) {
  66299. ang = 0;
  66300. }
  66301. if (ang > Math.PI || ang == undefined) {
  66302. ang = Math.PI;
  66303. }
  66304. this._maxAngle = ang;
  66305. var a = this._bone1Length;
  66306. var b = this._bone2Length;
  66307. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  66308. };
  66309. BoneIKController.prototype.update = function () {
  66310. var bone1 = this._bone1;
  66311. if (!bone1) {
  66312. return;
  66313. }
  66314. var target = this.targetPosition;
  66315. var poleTarget = this.poleTargetPosition;
  66316. var mat1 = BoneIKController._tmpMats[0];
  66317. var mat2 = BoneIKController._tmpMats[1];
  66318. if (this.targetMesh) {
  66319. target.copyFrom(this.targetMesh.getAbsolutePosition());
  66320. }
  66321. if (this.poleTargetBone) {
  66322. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  66323. }
  66324. else if (this.poleTargetMesh) {
  66325. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  66326. }
  66327. var bonePos = BoneIKController._tmpVecs[0];
  66328. var zaxis = BoneIKController._tmpVecs[1];
  66329. var xaxis = BoneIKController._tmpVecs[2];
  66330. var yaxis = BoneIKController._tmpVecs[3];
  66331. var upAxis = BoneIKController._tmpVecs[4];
  66332. var _tmpQuat = BoneIKController._tmpQuat;
  66333. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  66334. poleTarget.subtractToRef(bonePos, upAxis);
  66335. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  66336. upAxis.y = 1;
  66337. }
  66338. else {
  66339. upAxis.normalize();
  66340. }
  66341. target.subtractToRef(bonePos, yaxis);
  66342. yaxis.normalize();
  66343. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  66344. zaxis.normalize();
  66345. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  66346. xaxis.normalize();
  66347. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  66348. var a = this._bone1Length;
  66349. var b = this._bone2Length;
  66350. var c = BABYLON.Vector3.Distance(bonePos, target);
  66351. if (this._maxReach > 0) {
  66352. c = Math.min(this._maxReach, c);
  66353. }
  66354. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  66355. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  66356. if (acosa > 1) {
  66357. acosa = 1;
  66358. }
  66359. if (acosb > 1) {
  66360. acosb = 1;
  66361. }
  66362. if (acosa < -1) {
  66363. acosa = -1;
  66364. }
  66365. if (acosb < -1) {
  66366. acosb = -1;
  66367. }
  66368. var angA = Math.acos(acosa);
  66369. var angB = Math.acos(acosb);
  66370. var angC = -angA - angB;
  66371. if (this._rightHandedSystem) {
  66372. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  66373. mat2.multiplyToRef(mat1, mat1);
  66374. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  66375. mat2.multiplyToRef(mat1, mat1);
  66376. }
  66377. else {
  66378. var _tmpVec = BoneIKController._tmpVecs[5];
  66379. _tmpVec.copyFrom(this._bendAxis);
  66380. _tmpVec.x *= -1;
  66381. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  66382. mat2.multiplyToRef(mat1, mat1);
  66383. }
  66384. if (this.poleAngle) {
  66385. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  66386. mat1.multiplyToRef(mat2, mat1);
  66387. }
  66388. if (this._bone1) {
  66389. if (this.slerpAmount < 1) {
  66390. if (!this._slerping) {
  66391. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  66392. }
  66393. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  66394. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  66395. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  66396. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  66397. this._slerping = true;
  66398. }
  66399. else {
  66400. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  66401. this._bone1Mat.copyFrom(mat1);
  66402. this._slerping = false;
  66403. }
  66404. }
  66405. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  66406. this._bone2Ang = angC;
  66407. };
  66408. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  66409. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  66410. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  66411. return BoneIKController;
  66412. }());
  66413. BABYLON.BoneIKController = BoneIKController;
  66414. })(BABYLON || (BABYLON = {}));
  66415. //# sourceMappingURL=babylon.boneIKController.js.map
  66416. var BABYLON;
  66417. (function (BABYLON) {
  66418. var BoneLookController = /** @class */ (function () {
  66419. /**
  66420. * Create a BoneLookController
  66421. * @param mesh the mesh that the bone belongs to
  66422. * @param bone the bone that will be looking to the target
  66423. * @param target the target Vector3 to look at
  66424. * @param settings optional settings:
  66425. * - maxYaw: the maximum angle the bone will yaw to
  66426. * - minYaw: the minimum angle the bone will yaw to
  66427. * - maxPitch: the maximum angle the bone will pitch to
  66428. * - minPitch: the minimum angle the bone will yaw to
  66429. * - slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  66430. * - upAxis: the up axis of the coordinate system
  66431. * - upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  66432. * - yawAxis: set yawAxis if the bone does not yaw on the y axis
  66433. * - pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  66434. * - adjustYaw: used to make an adjustment to the yaw of the bone
  66435. * - adjustPitch: used to make an adjustment to the pitch of the bone
  66436. * - adjustRoll: used to make an adjustment to the roll of the bone
  66437. **/
  66438. function BoneLookController(mesh, bone, target, options) {
  66439. /**
  66440. * The up axis of the coordinate system that is used when the bone is rotated.
  66441. */
  66442. this.upAxis = BABYLON.Vector3.Up();
  66443. /**
  66444. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  66445. */
  66446. this.upAxisSpace = BABYLON.Space.LOCAL;
  66447. /**
  66448. * Used to make an adjustment to the yaw of the bone.
  66449. */
  66450. this.adjustYaw = 0;
  66451. /**
  66452. * Used to make an adjustment to the pitch of the bone.
  66453. */
  66454. this.adjustPitch = 0;
  66455. /**
  66456. * Used to make an adjustment to the roll of the bone.
  66457. */
  66458. this.adjustRoll = 0;
  66459. /**
  66460. * 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).
  66461. */
  66462. this.slerpAmount = 1;
  66463. this._boneQuat = BABYLON.Quaternion.Identity();
  66464. this._slerping = false;
  66465. this._firstFrameSkipped = false;
  66466. this._fowardAxis = BABYLON.Vector3.Forward();
  66467. this.mesh = mesh;
  66468. this.bone = bone;
  66469. this.target = target;
  66470. if (options) {
  66471. if (options.adjustYaw) {
  66472. this.adjustYaw = options.adjustYaw;
  66473. }
  66474. if (options.adjustPitch) {
  66475. this.adjustPitch = options.adjustPitch;
  66476. }
  66477. if (options.adjustRoll) {
  66478. this.adjustRoll = options.adjustRoll;
  66479. }
  66480. if (options.maxYaw != null) {
  66481. this.maxYaw = options.maxYaw;
  66482. }
  66483. else {
  66484. this.maxYaw = Math.PI;
  66485. }
  66486. if (options.minYaw != null) {
  66487. this.minYaw = options.minYaw;
  66488. }
  66489. else {
  66490. this.minYaw = -Math.PI;
  66491. }
  66492. if (options.maxPitch != null) {
  66493. this.maxPitch = options.maxPitch;
  66494. }
  66495. else {
  66496. this.maxPitch = Math.PI;
  66497. }
  66498. if (options.minPitch != null) {
  66499. this.minPitch = options.minPitch;
  66500. }
  66501. else {
  66502. this.minPitch = -Math.PI;
  66503. }
  66504. if (options.slerpAmount != null) {
  66505. this.slerpAmount = options.slerpAmount;
  66506. }
  66507. if (options.upAxis != null) {
  66508. this.upAxis = options.upAxis;
  66509. }
  66510. if (options.upAxisSpace != null) {
  66511. this.upAxisSpace = options.upAxisSpace;
  66512. }
  66513. if (options.yawAxis != null || options.pitchAxis != null) {
  66514. var newYawAxis = BABYLON.Axis.Y;
  66515. var newPitchAxis = BABYLON.Axis.X;
  66516. if (options.yawAxis != null) {
  66517. newYawAxis = options.yawAxis.clone();
  66518. newYawAxis.normalize();
  66519. }
  66520. if (options.pitchAxis != null) {
  66521. newPitchAxis = options.pitchAxis.clone();
  66522. newPitchAxis.normalize();
  66523. }
  66524. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  66525. this._transformYawPitch = BABYLON.Matrix.Identity();
  66526. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  66527. this._transformYawPitchInv = this._transformYawPitch.clone();
  66528. this._transformYawPitch.invert();
  66529. }
  66530. }
  66531. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  66532. this.upAxisSpace = BABYLON.Space.LOCAL;
  66533. }
  66534. }
  66535. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  66536. /**
  66537. * Get/set the minimum yaw angle that the bone can look to.
  66538. */
  66539. get: function () {
  66540. return this._minYaw;
  66541. },
  66542. set: function (value) {
  66543. this._minYaw = value;
  66544. this._minYawSin = Math.sin(value);
  66545. this._minYawCos = Math.cos(value);
  66546. if (this._maxYaw != null) {
  66547. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  66548. this._yawRange = this._maxYaw - this._minYaw;
  66549. }
  66550. },
  66551. enumerable: true,
  66552. configurable: true
  66553. });
  66554. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  66555. /**
  66556. * Get/set the maximum yaw angle that the bone can look to.
  66557. */
  66558. get: function () {
  66559. return this._maxYaw;
  66560. },
  66561. set: function (value) {
  66562. this._maxYaw = value;
  66563. this._maxYawSin = Math.sin(value);
  66564. this._maxYawCos = Math.cos(value);
  66565. if (this._minYaw != null) {
  66566. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  66567. this._yawRange = this._maxYaw - this._minYaw;
  66568. }
  66569. },
  66570. enumerable: true,
  66571. configurable: true
  66572. });
  66573. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  66574. /**
  66575. * Get/set the minimum pitch angle that the bone can look to.
  66576. */
  66577. get: function () {
  66578. return this._minPitch;
  66579. },
  66580. set: function (value) {
  66581. this._minPitch = value;
  66582. this._minPitchTan = Math.tan(value);
  66583. },
  66584. enumerable: true,
  66585. configurable: true
  66586. });
  66587. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  66588. /**
  66589. * Get/set the maximum pitch angle that the bone can look to.
  66590. */
  66591. get: function () {
  66592. return this._maxPitch;
  66593. },
  66594. set: function (value) {
  66595. this._maxPitch = value;
  66596. this._maxPitchTan = Math.tan(value);
  66597. },
  66598. enumerable: true,
  66599. configurable: true
  66600. });
  66601. /**
  66602. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender()).
  66603. */
  66604. BoneLookController.prototype.update = function () {
  66605. //skip the first frame when slerping so that the mesh rotation is correct
  66606. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  66607. this._firstFrameSkipped = true;
  66608. return;
  66609. }
  66610. var bone = this.bone;
  66611. var bonePos = BoneLookController._tmpVecs[0];
  66612. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  66613. var target = this.target;
  66614. var _tmpMat1 = BoneLookController._tmpMats[0];
  66615. var _tmpMat2 = BoneLookController._tmpMats[1];
  66616. var mesh = this.mesh;
  66617. var parentBone = bone.getParent();
  66618. var upAxis = BoneLookController._tmpVecs[1];
  66619. upAxis.copyFrom(this.upAxis);
  66620. if (this.upAxisSpace == BABYLON.Space.BONE && parentBone) {
  66621. if (this._transformYawPitch) {
  66622. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  66623. }
  66624. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  66625. }
  66626. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  66627. mesh.getDirectionToRef(upAxis, upAxis);
  66628. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  66629. upAxis.normalize();
  66630. }
  66631. }
  66632. var checkYaw = false;
  66633. var checkPitch = false;
  66634. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  66635. checkYaw = true;
  66636. }
  66637. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  66638. checkPitch = true;
  66639. }
  66640. if (checkYaw || checkPitch) {
  66641. var spaceMat = BoneLookController._tmpMats[2];
  66642. var spaceMatInv = BoneLookController._tmpMats[3];
  66643. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1 && parentBone) {
  66644. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  66645. }
  66646. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  66647. spaceMat.copyFrom(mesh.getWorldMatrix());
  66648. }
  66649. else {
  66650. var forwardAxis = BoneLookController._tmpVecs[2];
  66651. forwardAxis.copyFrom(this._fowardAxis);
  66652. if (this._transformYawPitch) {
  66653. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  66654. }
  66655. if (parentBone) {
  66656. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  66657. }
  66658. else {
  66659. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  66660. }
  66661. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  66662. rightAxis.normalize();
  66663. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  66664. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  66665. }
  66666. spaceMat.invertToRef(spaceMatInv);
  66667. var xzlen = null;
  66668. if (checkPitch) {
  66669. var localTarget = BoneLookController._tmpVecs[3];
  66670. target.subtractToRef(bonePos, localTarget);
  66671. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  66672. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  66673. var pitch = Math.atan2(localTarget.y, xzlen);
  66674. var newPitch = pitch;
  66675. if (pitch > this._maxPitch) {
  66676. localTarget.y = this._maxPitchTan * xzlen;
  66677. newPitch = this._maxPitch;
  66678. }
  66679. else if (pitch < this._minPitch) {
  66680. localTarget.y = this._minPitchTan * xzlen;
  66681. newPitch = this._minPitch;
  66682. }
  66683. if (pitch != newPitch) {
  66684. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  66685. localTarget.addInPlace(bonePos);
  66686. target = localTarget;
  66687. }
  66688. }
  66689. if (checkYaw) {
  66690. var localTarget = BoneLookController._tmpVecs[4];
  66691. target.subtractToRef(bonePos, localTarget);
  66692. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  66693. var yaw = Math.atan2(localTarget.x, localTarget.z);
  66694. var newYaw = yaw;
  66695. if (yaw > this._maxYaw || yaw < this._minYaw) {
  66696. if (xzlen == null) {
  66697. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  66698. }
  66699. if (this._yawRange > Math.PI) {
  66700. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  66701. localTarget.z = this._maxYawCos * xzlen;
  66702. localTarget.x = this._maxYawSin * xzlen;
  66703. newYaw = this._maxYaw;
  66704. }
  66705. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  66706. localTarget.z = this._minYawCos * xzlen;
  66707. localTarget.x = this._minYawSin * xzlen;
  66708. newYaw = this._minYaw;
  66709. }
  66710. }
  66711. else {
  66712. if (yaw > this._maxYaw) {
  66713. localTarget.z = this._maxYawCos * xzlen;
  66714. localTarget.x = this._maxYawSin * xzlen;
  66715. newYaw = this._maxYaw;
  66716. }
  66717. else if (yaw < this._minYaw) {
  66718. localTarget.z = this._minYawCos * xzlen;
  66719. localTarget.x = this._minYawSin * xzlen;
  66720. newYaw = this._minYaw;
  66721. }
  66722. }
  66723. }
  66724. if (this._slerping && this._yawRange > Math.PI) {
  66725. //are we going to be crossing into the min/max region?
  66726. var boneFwd = BoneLookController._tmpVecs[8];
  66727. boneFwd.copyFrom(BABYLON.Axis.Z);
  66728. if (this._transformYawPitch) {
  66729. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  66730. }
  66731. var boneRotMat = BoneLookController._tmpMats[4];
  66732. this._boneQuat.toRotationMatrix(boneRotMat);
  66733. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  66734. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  66735. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  66736. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  66737. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  66738. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  66739. if (angBtwTar > angBtwMidYaw) {
  66740. if (xzlen == null) {
  66741. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  66742. }
  66743. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  66744. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  66745. if (angBtwMin < angBtwMax) {
  66746. newYaw = boneYaw + Math.PI * .75;
  66747. localTarget.z = Math.cos(newYaw) * xzlen;
  66748. localTarget.x = Math.sin(newYaw) * xzlen;
  66749. }
  66750. else {
  66751. newYaw = boneYaw - Math.PI * .75;
  66752. localTarget.z = Math.cos(newYaw) * xzlen;
  66753. localTarget.x = Math.sin(newYaw) * xzlen;
  66754. }
  66755. }
  66756. }
  66757. if (yaw != newYaw) {
  66758. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  66759. localTarget.addInPlace(bonePos);
  66760. target = localTarget;
  66761. }
  66762. }
  66763. }
  66764. var zaxis = BoneLookController._tmpVecs[5];
  66765. var xaxis = BoneLookController._tmpVecs[6];
  66766. var yaxis = BoneLookController._tmpVecs[7];
  66767. var _tmpQuat = BoneLookController._tmpQuat;
  66768. target.subtractToRef(bonePos, zaxis);
  66769. zaxis.normalize();
  66770. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  66771. xaxis.normalize();
  66772. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  66773. yaxis.normalize();
  66774. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  66775. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  66776. return;
  66777. }
  66778. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  66779. return;
  66780. }
  66781. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  66782. return;
  66783. }
  66784. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  66785. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  66786. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  66787. }
  66788. if (this.slerpAmount < 1) {
  66789. if (!this._slerping) {
  66790. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  66791. }
  66792. if (this._transformYawPitch) {
  66793. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  66794. }
  66795. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  66796. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  66797. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  66798. this._slerping = true;
  66799. }
  66800. else {
  66801. if (this._transformYawPitch) {
  66802. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  66803. }
  66804. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  66805. this._slerping = false;
  66806. }
  66807. };
  66808. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  66809. var angDiff = ang2 - ang1;
  66810. angDiff %= Math.PI * 2;
  66811. if (angDiff > Math.PI) {
  66812. angDiff -= Math.PI * 2;
  66813. }
  66814. else if (angDiff < -Math.PI) {
  66815. angDiff += Math.PI * 2;
  66816. }
  66817. return angDiff;
  66818. };
  66819. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  66820. ang1 %= (2 * Math.PI);
  66821. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  66822. ang2 %= (2 * Math.PI);
  66823. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  66824. var ab = 0;
  66825. if (ang1 < ang2) {
  66826. ab = ang2 - ang1;
  66827. }
  66828. else {
  66829. ab = ang1 - ang2;
  66830. }
  66831. if (ab > Math.PI) {
  66832. ab = Math.PI * 2 - ab;
  66833. }
  66834. return ab;
  66835. };
  66836. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  66837. ang %= (2 * Math.PI);
  66838. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  66839. ang1 %= (2 * Math.PI);
  66840. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  66841. ang2 %= (2 * Math.PI);
  66842. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  66843. if (ang1 < ang2) {
  66844. if (ang > ang1 && ang < ang2) {
  66845. return true;
  66846. }
  66847. }
  66848. else {
  66849. if (ang > ang2 && ang < ang1) {
  66850. return true;
  66851. }
  66852. }
  66853. return false;
  66854. };
  66855. 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()];
  66856. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  66857. BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  66858. return BoneLookController;
  66859. }());
  66860. BABYLON.BoneLookController = BoneLookController;
  66861. })(BABYLON || (BABYLON = {}));
  66862. //# sourceMappingURL=babylon.boneLookController.js.map
  66863. var BABYLON;
  66864. (function (BABYLON) {
  66865. var Skeleton = /** @class */ (function () {
  66866. function Skeleton(name, id, scene) {
  66867. this.name = name;
  66868. this.id = id;
  66869. this.bones = new Array();
  66870. this.needInitialSkinMatrix = false;
  66871. this._isDirty = true;
  66872. this._meshesWithPoseMatrix = new Array();
  66873. this._identity = BABYLON.Matrix.Identity();
  66874. this._ranges = {};
  66875. this._lastAbsoluteTransformsUpdateId = -1;
  66876. // Events
  66877. /**
  66878. * An event triggered before computing the skeleton's matrices
  66879. * @type {BABYLON.Observable}
  66880. */
  66881. this.onBeforeComputeObservable = new BABYLON.Observable();
  66882. this.bones = [];
  66883. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  66884. scene.skeletons.push(this);
  66885. //make sure it will recalculate the matrix next time prepare is called.
  66886. this._isDirty = true;
  66887. }
  66888. // Members
  66889. Skeleton.prototype.getTransformMatrices = function (mesh) {
  66890. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  66891. return mesh._bonesTransformMatrices;
  66892. }
  66893. if (!this._transformMatrices) {
  66894. this.prepare();
  66895. }
  66896. return this._transformMatrices;
  66897. };
  66898. Skeleton.prototype.getScene = function () {
  66899. return this._scene;
  66900. };
  66901. // Methods
  66902. /**
  66903. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  66904. */
  66905. Skeleton.prototype.toString = function (fullDetails) {
  66906. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  66907. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  66908. if (fullDetails) {
  66909. ret += ", Ranges: {";
  66910. var first = true;
  66911. for (var name_1 in this._ranges) {
  66912. if (first) {
  66913. ret += ", ";
  66914. first = false;
  66915. }
  66916. ret += name_1;
  66917. }
  66918. ret += "}";
  66919. }
  66920. return ret;
  66921. };
  66922. /**
  66923. * Get bone's index searching by name
  66924. * @param {string} name is bone's name to search for
  66925. * @return {number} Indice of the bone. Returns -1 if not found
  66926. */
  66927. Skeleton.prototype.getBoneIndexByName = function (name) {
  66928. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  66929. if (this.bones[boneIndex].name === name) {
  66930. return boneIndex;
  66931. }
  66932. }
  66933. return -1;
  66934. };
  66935. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  66936. // check name not already in use
  66937. if (!this._ranges[name]) {
  66938. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  66939. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  66940. if (this.bones[i].animations[0]) {
  66941. this.bones[i].animations[0].createRange(name, from, to);
  66942. }
  66943. }
  66944. }
  66945. };
  66946. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  66947. if (deleteFrames === void 0) { deleteFrames = true; }
  66948. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  66949. if (this.bones[i].animations[0]) {
  66950. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  66951. }
  66952. }
  66953. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  66954. };
  66955. Skeleton.prototype.getAnimationRange = function (name) {
  66956. return this._ranges[name];
  66957. };
  66958. /**
  66959. * Returns as an Array, all AnimationRanges defined on this skeleton
  66960. */
  66961. Skeleton.prototype.getAnimationRanges = function () {
  66962. var animationRanges = [];
  66963. var name;
  66964. var i = 0;
  66965. for (name in this._ranges) {
  66966. animationRanges[i] = this._ranges[name];
  66967. i++;
  66968. }
  66969. return animationRanges;
  66970. };
  66971. /**
  66972. * note: This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  66973. */
  66974. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  66975. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  66976. if (this._ranges[name] || !source.getAnimationRange(name)) {
  66977. return false;
  66978. }
  66979. var ret = true;
  66980. var frameOffset = this._getHighestAnimationFrame() + 1;
  66981. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  66982. var boneDict = {};
  66983. var sourceBones = source.bones;
  66984. var nBones;
  66985. var i;
  66986. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  66987. boneDict[sourceBones[i].name] = sourceBones[i];
  66988. }
  66989. if (this.bones.length !== sourceBones.length) {
  66990. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  66991. ret = false;
  66992. }
  66993. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  66994. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  66995. var boneName = this.bones[i].name;
  66996. var sourceBone = boneDict[boneName];
  66997. if (sourceBone) {
  66998. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  66999. }
  67000. else {
  67001. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  67002. ret = false;
  67003. }
  67004. }
  67005. // do not call createAnimationRange(), since it also is done to bones, which was already done
  67006. var range = source.getAnimationRange(name);
  67007. if (range) {
  67008. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  67009. }
  67010. return ret;
  67011. };
  67012. Skeleton.prototype.returnToRest = function () {
  67013. for (var index = 0; index < this.bones.length; index++) {
  67014. this.bones[index].returnToRest();
  67015. }
  67016. };
  67017. Skeleton.prototype._getHighestAnimationFrame = function () {
  67018. var ret = 0;
  67019. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  67020. if (this.bones[i].animations[0]) {
  67021. var highest = this.bones[i].animations[0].getHighestFrame();
  67022. if (ret < highest) {
  67023. ret = highest;
  67024. }
  67025. }
  67026. }
  67027. return ret;
  67028. };
  67029. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  67030. var range = this.getAnimationRange(name);
  67031. if (!range) {
  67032. return null;
  67033. }
  67034. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  67035. };
  67036. Skeleton.prototype._markAsDirty = function () {
  67037. this._isDirty = true;
  67038. };
  67039. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  67040. this._meshesWithPoseMatrix.push(mesh);
  67041. };
  67042. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  67043. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  67044. if (index > -1) {
  67045. this._meshesWithPoseMatrix.splice(index, 1);
  67046. }
  67047. };
  67048. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  67049. this.onBeforeComputeObservable.notifyObservers(this);
  67050. for (var index = 0; index < this.bones.length; index++) {
  67051. var bone = this.bones[index];
  67052. var parentBone = bone.getParent();
  67053. if (parentBone) {
  67054. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  67055. }
  67056. else {
  67057. if (initialSkinMatrix) {
  67058. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  67059. }
  67060. else {
  67061. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  67062. }
  67063. }
  67064. if (bone._index !== -1) {
  67065. var mappedIndex = bone._index === null ? index : bone._index;
  67066. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, mappedIndex * 16);
  67067. }
  67068. }
  67069. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  67070. };
  67071. Skeleton.prototype.prepare = function () {
  67072. if (!this._isDirty) {
  67073. return;
  67074. }
  67075. if (this.needInitialSkinMatrix) {
  67076. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  67077. var mesh = this._meshesWithPoseMatrix[index];
  67078. var poseMatrix = mesh.getPoseMatrix();
  67079. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  67080. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  67081. }
  67082. if (this._synchronizedWithMesh !== mesh) {
  67083. this._synchronizedWithMesh = mesh;
  67084. // Prepare bones
  67085. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  67086. var bone = this.bones[boneIndex];
  67087. if (!bone.getParent()) {
  67088. var matrix = bone.getBaseMatrix();
  67089. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  67090. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  67091. }
  67092. }
  67093. }
  67094. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  67095. }
  67096. }
  67097. else {
  67098. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  67099. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  67100. }
  67101. this._computeTransformMatrices(this._transformMatrices, null);
  67102. }
  67103. this._isDirty = false;
  67104. this._scene._activeBones.addCount(this.bones.length, false);
  67105. };
  67106. Skeleton.prototype.getAnimatables = function () {
  67107. if (!this._animatables || this._animatables.length !== this.bones.length) {
  67108. this._animatables = [];
  67109. for (var index = 0; index < this.bones.length; index++) {
  67110. this._animatables.push(this.bones[index]);
  67111. }
  67112. }
  67113. return this._animatables;
  67114. };
  67115. Skeleton.prototype.clone = function (name, id) {
  67116. var result = new Skeleton(name, id || name, this._scene);
  67117. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  67118. for (var index = 0; index < this.bones.length; index++) {
  67119. var source = this.bones[index];
  67120. var parentBone = null;
  67121. var parent_1 = source.getParent();
  67122. if (parent_1) {
  67123. var parentIndex = this.bones.indexOf(parent_1);
  67124. parentBone = result.bones[parentIndex];
  67125. }
  67126. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  67127. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  67128. }
  67129. if (this._ranges) {
  67130. result._ranges = {};
  67131. for (var rangeName in this._ranges) {
  67132. var range = this._ranges[rangeName];
  67133. if (range) {
  67134. result._ranges[rangeName] = range.clone();
  67135. }
  67136. }
  67137. }
  67138. this._isDirty = true;
  67139. return result;
  67140. };
  67141. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  67142. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  67143. this.bones.forEach(function (bone) {
  67144. bone.animations.forEach(function (animation) {
  67145. animation.enableBlending = true;
  67146. animation.blendingSpeed = blendingSpeed;
  67147. });
  67148. });
  67149. };
  67150. Skeleton.prototype.dispose = function () {
  67151. this._meshesWithPoseMatrix = [];
  67152. // Animations
  67153. this.getScene().stopAnimation(this);
  67154. // Remove from scene
  67155. this.getScene().removeSkeleton(this);
  67156. };
  67157. Skeleton.prototype.serialize = function () {
  67158. var serializationObject = {};
  67159. serializationObject.name = this.name;
  67160. serializationObject.id = this.id;
  67161. serializationObject.dimensionsAtRest = this.dimensionsAtRest;
  67162. serializationObject.bones = [];
  67163. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  67164. for (var index = 0; index < this.bones.length; index++) {
  67165. var bone = this.bones[index];
  67166. var parent_2 = bone.getParent();
  67167. var serializedBone = {
  67168. parentBoneIndex: parent_2 ? this.bones.indexOf(parent_2) : -1,
  67169. name: bone.name,
  67170. matrix: bone.getBaseMatrix().toArray(),
  67171. rest: bone.getRestPose().toArray()
  67172. };
  67173. serializationObject.bones.push(serializedBone);
  67174. if (bone.length) {
  67175. serializedBone.length = bone.length;
  67176. }
  67177. if (bone.animations && bone.animations.length > 0) {
  67178. serializedBone.animation = bone.animations[0].serialize();
  67179. }
  67180. serializationObject.ranges = [];
  67181. for (var name in this._ranges) {
  67182. var source = this._ranges[name];
  67183. if (!source) {
  67184. continue;
  67185. }
  67186. var range = {};
  67187. range.name = name;
  67188. range.from = source.from;
  67189. range.to = source.to;
  67190. serializationObject.ranges.push(range);
  67191. }
  67192. }
  67193. return serializationObject;
  67194. };
  67195. Skeleton.Parse = function (parsedSkeleton, scene) {
  67196. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  67197. if (parsedSkeleton.dimensionsAtRest) {
  67198. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  67199. }
  67200. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  67201. var index;
  67202. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  67203. var parsedBone = parsedSkeleton.bones[index];
  67204. var parentBone = null;
  67205. if (parsedBone.parentBoneIndex > -1) {
  67206. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  67207. }
  67208. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  67209. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  67210. if (parsedBone.length) {
  67211. bone.length = parsedBone.length;
  67212. }
  67213. if (parsedBone.animation) {
  67214. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  67215. }
  67216. }
  67217. // placed after bones, so createAnimationRange can cascade down
  67218. if (parsedSkeleton.ranges) {
  67219. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  67220. var data = parsedSkeleton.ranges[index];
  67221. skeleton.createAnimationRange(data.name, data.from, data.to);
  67222. }
  67223. }
  67224. return skeleton;
  67225. };
  67226. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  67227. if (forceUpdate === void 0) { forceUpdate = false; }
  67228. var renderId = this._scene.getRenderId();
  67229. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  67230. this.bones[0].computeAbsoluteTransforms();
  67231. this._lastAbsoluteTransformsUpdateId = renderId;
  67232. }
  67233. };
  67234. Skeleton.prototype.getPoseMatrix = function () {
  67235. var poseMatrix = null;
  67236. if (this._meshesWithPoseMatrix.length > 0) {
  67237. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  67238. }
  67239. return poseMatrix;
  67240. };
  67241. Skeleton.prototype.sortBones = function () {
  67242. var bones = new Array();
  67243. var visited = new Array(this.bones.length);
  67244. for (var index = 0; index < this.bones.length; index++) {
  67245. this._sortBones(index, bones, visited);
  67246. }
  67247. this.bones = bones;
  67248. };
  67249. Skeleton.prototype._sortBones = function (index, bones, visited) {
  67250. if (visited[index]) {
  67251. return;
  67252. }
  67253. visited[index] = true;
  67254. var bone = this.bones[index];
  67255. if (bone._index === undefined) {
  67256. bone._index = index;
  67257. }
  67258. var parentBone = bone.getParent();
  67259. if (parentBone) {
  67260. this._sortBones(this.bones.indexOf(parentBone), bones, visited);
  67261. }
  67262. bones.push(bone);
  67263. };
  67264. return Skeleton;
  67265. }());
  67266. BABYLON.Skeleton = Skeleton;
  67267. })(BABYLON || (BABYLON = {}));
  67268. //# sourceMappingURL=babylon.skeleton.js.map
  67269. var BABYLON;
  67270. (function (BABYLON) {
  67271. var SphericalPolynomial = /** @class */ (function () {
  67272. function SphericalPolynomial() {
  67273. this.x = BABYLON.Vector3.Zero();
  67274. this.y = BABYLON.Vector3.Zero();
  67275. this.z = BABYLON.Vector3.Zero();
  67276. this.xx = BABYLON.Vector3.Zero();
  67277. this.yy = BABYLON.Vector3.Zero();
  67278. this.zz = BABYLON.Vector3.Zero();
  67279. this.xy = BABYLON.Vector3.Zero();
  67280. this.yz = BABYLON.Vector3.Zero();
  67281. this.zx = BABYLON.Vector3.Zero();
  67282. }
  67283. SphericalPolynomial.prototype.addAmbient = function (color) {
  67284. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  67285. this.xx = this.xx.add(colorVector);
  67286. this.yy = this.yy.add(colorVector);
  67287. this.zz = this.zz.add(colorVector);
  67288. };
  67289. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  67290. var result = new SphericalPolynomial();
  67291. result.x = harmonics.L11.scale(1.02333);
  67292. result.y = harmonics.L1_1.scale(1.02333);
  67293. result.z = harmonics.L10.scale(1.02333);
  67294. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  67295. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  67296. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  67297. result.yz = harmonics.L2_1.scale(0.858086);
  67298. result.zx = harmonics.L21.scale(0.858086);
  67299. result.xy = harmonics.L2_2.scale(0.858086);
  67300. result.scale(1.0 / Math.PI);
  67301. return result;
  67302. };
  67303. SphericalPolynomial.prototype.scale = function (scale) {
  67304. this.x = this.x.scale(scale);
  67305. this.y = this.y.scale(scale);
  67306. this.z = this.z.scale(scale);
  67307. this.xx = this.xx.scale(scale);
  67308. this.yy = this.yy.scale(scale);
  67309. this.zz = this.zz.scale(scale);
  67310. this.yz = this.yz.scale(scale);
  67311. this.zx = this.zx.scale(scale);
  67312. this.xy = this.xy.scale(scale);
  67313. };
  67314. return SphericalPolynomial;
  67315. }());
  67316. BABYLON.SphericalPolynomial = SphericalPolynomial;
  67317. var SphericalHarmonics = /** @class */ (function () {
  67318. function SphericalHarmonics() {
  67319. this.L00 = BABYLON.Vector3.Zero();
  67320. this.L1_1 = BABYLON.Vector3.Zero();
  67321. this.L10 = BABYLON.Vector3.Zero();
  67322. this.L11 = BABYLON.Vector3.Zero();
  67323. this.L2_2 = BABYLON.Vector3.Zero();
  67324. this.L2_1 = BABYLON.Vector3.Zero();
  67325. this.L20 = BABYLON.Vector3.Zero();
  67326. this.L21 = BABYLON.Vector3.Zero();
  67327. this.L22 = BABYLON.Vector3.Zero();
  67328. }
  67329. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  67330. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  67331. var c = colorVector.scale(deltaSolidAngle);
  67332. this.L00 = this.L00.add(c.scale(0.282095));
  67333. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  67334. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  67335. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  67336. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  67337. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  67338. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  67339. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  67340. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  67341. };
  67342. SphericalHarmonics.prototype.scale = function (scale) {
  67343. this.L00 = this.L00.scale(scale);
  67344. this.L1_1 = this.L1_1.scale(scale);
  67345. this.L10 = this.L10.scale(scale);
  67346. this.L11 = this.L11.scale(scale);
  67347. this.L2_2 = this.L2_2.scale(scale);
  67348. this.L2_1 = this.L2_1.scale(scale);
  67349. this.L20 = this.L20.scale(scale);
  67350. this.L21 = this.L21.scale(scale);
  67351. this.L22 = this.L22.scale(scale);
  67352. };
  67353. SphericalHarmonics.prototype.convertIncidentRadianceToIrradiance = function () {
  67354. // Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere.
  67355. //
  67356. // E_lm = A_l * L_lm
  67357. //
  67358. // In spherical harmonics this convolution amounts to scaling factors for each frequency band.
  67359. // This corresponds to equation 5 in "An Efficient Representation for Irradiance Environment Maps", where
  67360. // the scaling factors are given in equation 9.
  67361. // Constant (Band 0)
  67362. this.L00 = this.L00.scale(3.141593);
  67363. // Linear (Band 1)
  67364. this.L1_1 = this.L1_1.scale(2.094395);
  67365. this.L10 = this.L10.scale(2.094395);
  67366. this.L11 = this.L11.scale(2.094395);
  67367. // Quadratic (Band 2)
  67368. this.L2_2 = this.L2_2.scale(0.785398);
  67369. this.L2_1 = this.L2_1.scale(0.785398);
  67370. this.L20 = this.L20.scale(0.785398);
  67371. this.L21 = this.L21.scale(0.785398);
  67372. this.L22 = this.L22.scale(0.785398);
  67373. };
  67374. SphericalHarmonics.prototype.convertIrradianceToLambertianRadiance = function () {
  67375. // Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  67376. // L = (1/pi) * E * rho
  67377. //
  67378. // This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  67379. this.scale(1.0 / Math.PI);
  67380. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  67381. // (The pixel shader must apply albedo after texture fetches, etc).
  67382. };
  67383. SphericalHarmonics.getsphericalHarmonicsFromPolynomial = function (polynomial) {
  67384. var result = new SphericalHarmonics();
  67385. result.L00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126));
  67386. result.L1_1 = polynomial.y.scale(0.977204);
  67387. result.L10 = polynomial.z.scale(0.977204);
  67388. result.L11 = polynomial.x.scale(0.977204);
  67389. result.L2_2 = polynomial.xy.scale(1.16538);
  67390. result.L2_1 = polynomial.yz.scale(1.16538);
  67391. result.L20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834));
  67392. result.L21 = polynomial.zx.scale(1.16538);
  67393. result.L22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538));
  67394. result.scale(Math.PI);
  67395. return result;
  67396. };
  67397. return SphericalHarmonics;
  67398. }());
  67399. BABYLON.SphericalHarmonics = SphericalHarmonics;
  67400. })(BABYLON || (BABYLON = {}));
  67401. //# sourceMappingURL=babylon.sphericalPolynomial.js.map
  67402. var BABYLON;
  67403. (function (BABYLON) {
  67404. var FileFaceOrientation = /** @class */ (function () {
  67405. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  67406. this.name = name;
  67407. this.worldAxisForNormal = worldAxisForNormal;
  67408. this.worldAxisForFileX = worldAxisForFileX;
  67409. this.worldAxisForFileY = worldAxisForFileY;
  67410. }
  67411. return FileFaceOrientation;
  67412. }());
  67413. ;
  67414. /**
  67415. * Helper class dealing with the extraction of spherical polynomial dataArray
  67416. * from a cube map.
  67417. */
  67418. var CubeMapToSphericalPolynomialTools = /** @class */ (function () {
  67419. function CubeMapToSphericalPolynomialTools() {
  67420. }
  67421. /**
  67422. * Converts a texture to the according Spherical Polynomial data.
  67423. * This extracts the first 3 orders only as they are the only one used in the lighting.
  67424. *
  67425. * @param texture The texture to extract the information from.
  67426. * @return The Spherical Polynomial data.
  67427. */
  67428. CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial = function (texture) {
  67429. if (!texture.isCube) {
  67430. // Only supports cube Textures currently.
  67431. return null;
  67432. }
  67433. var size = texture.getSize().width;
  67434. var right = texture.readPixels(0);
  67435. var left = texture.readPixels(1);
  67436. var up;
  67437. var down;
  67438. if (texture.isRenderTarget) {
  67439. up = texture.readPixels(3);
  67440. down = texture.readPixels(2);
  67441. }
  67442. else {
  67443. up = texture.readPixels(2);
  67444. down = texture.readPixels(3);
  67445. }
  67446. var front = texture.readPixels(4);
  67447. var back = texture.readPixels(5);
  67448. var gammaSpace = texture.gammaSpace;
  67449. // Always read as RGBA.
  67450. var format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  67451. var type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  67452. if (texture.textureType && texture.textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  67453. type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  67454. }
  67455. var cubeInfo = {
  67456. size: size,
  67457. right: right,
  67458. left: left,
  67459. up: up,
  67460. down: down,
  67461. front: front,
  67462. back: back,
  67463. format: format,
  67464. type: type,
  67465. gammaSpace: gammaSpace,
  67466. };
  67467. return this.ConvertCubeMapToSphericalPolynomial(cubeInfo);
  67468. };
  67469. /**
  67470. * Converts a cubemap to the according Spherical Polynomial data.
  67471. * This extracts the first 3 orders only as they are the only one used in the lighting.
  67472. *
  67473. * @param cubeInfo The Cube map to extract the information from.
  67474. * @return The Spherical Polynomial data.
  67475. */
  67476. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  67477. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  67478. var totalSolidAngle = 0.0;
  67479. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  67480. var du = 2.0 / cubeInfo.size;
  67481. var dv = du;
  67482. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  67483. var minUV = du * 0.5 - 1.0;
  67484. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  67485. var fileFace = this.FileFaces[faceIndex];
  67486. var dataArray = cubeInfo[fileFace.name];
  67487. var v = minUV;
  67488. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  67489. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  67490. // Because SP is still linear, so summation is fine in that basis.
  67491. var stride = cubeInfo.format === BABYLON.Engine.TEXTUREFORMAT_RGBA ? 4 : 3;
  67492. for (var y = 0; y < cubeInfo.size; y++) {
  67493. var u = minUV;
  67494. for (var x = 0; x < cubeInfo.size; x++) {
  67495. // World direction (not normalised)
  67496. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  67497. worldDirection.normalize();
  67498. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  67499. var r = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 0];
  67500. var g = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 1];
  67501. var b = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 2];
  67502. // Handle Integer types.
  67503. if (cubeInfo.type === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  67504. r /= 255;
  67505. g /= 255;
  67506. b /= 255;
  67507. }
  67508. // Handle Gamma space textures.
  67509. if (cubeInfo.gammaSpace) {
  67510. r = Math.pow(BABYLON.Scalar.Clamp(r), BABYLON.ToLinearSpace);
  67511. g = Math.pow(BABYLON.Scalar.Clamp(g), BABYLON.ToLinearSpace);
  67512. b = Math.pow(BABYLON.Scalar.Clamp(b), BABYLON.ToLinearSpace);
  67513. }
  67514. var color = new BABYLON.Color3(r, g, b);
  67515. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  67516. totalSolidAngle += deltaSolidAngle;
  67517. u += du;
  67518. }
  67519. v += dv;
  67520. }
  67521. }
  67522. // Solid angle for entire sphere is 4*pi
  67523. var sphereSolidAngle = 4.0 * Math.PI;
  67524. // Adjust the solid angle to allow for how many faces we processed.
  67525. var facesProcessed = 6.0;
  67526. var expectedSolidAngle = sphereSolidAngle * facesProcessed / 6.0;
  67527. // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle.
  67528. // This is needed because the numerical integration over the cube uses a
  67529. // small angle approximation of solid angle for each texel (see deltaSolidAngle),
  67530. // and also to compensate for accumulative error due to float precision in the summation.
  67531. var correctionFactor = expectedSolidAngle / totalSolidAngle;
  67532. sphericalHarmonics.scale(correctionFactor);
  67533. sphericalHarmonics.convertIncidentRadianceToIrradiance();
  67534. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  67535. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  67536. };
  67537. CubeMapToSphericalPolynomialTools.FileFaces = [
  67538. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  67539. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  67540. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  67541. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  67542. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  67543. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  67544. ];
  67545. return CubeMapToSphericalPolynomialTools;
  67546. }());
  67547. BABYLON.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  67548. })(BABYLON || (BABYLON = {}));
  67549. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  67550. var BABYLON;
  67551. (function (BABYLON) {
  67552. /**
  67553. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  67554. */
  67555. var PanoramaToCubeMapTools = /** @class */ (function () {
  67556. function PanoramaToCubeMapTools() {
  67557. }
  67558. /**
  67559. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  67560. *
  67561. * @param float32Array The source data.
  67562. * @param inputWidth The width of the input panorama.
  67563. * @param inputhHeight The height of the input panorama.
  67564. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  67565. * @return The cubemap data
  67566. */
  67567. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  67568. if (!float32Array) {
  67569. throw "ConvertPanoramaToCubemap: input cannot be null";
  67570. }
  67571. if (float32Array.length != inputWidth * inputHeight * 3) {
  67572. throw "ConvertPanoramaToCubemap: input size is wrong";
  67573. }
  67574. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  67575. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  67576. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  67577. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  67578. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  67579. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  67580. return {
  67581. front: textureFront,
  67582. back: textureBack,
  67583. left: textureLeft,
  67584. right: textureRight,
  67585. up: textureUp,
  67586. down: textureDown,
  67587. size: size,
  67588. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  67589. format: BABYLON.Engine.TEXTUREFORMAT_RGB,
  67590. gammaSpace: false,
  67591. };
  67592. };
  67593. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  67594. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  67595. var textureArray = new Float32Array(buffer);
  67596. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  67597. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  67598. var dy = 1 / texSize;
  67599. var fy = 0;
  67600. for (var y = 0; y < texSize; y++) {
  67601. var xv1 = faceData[0];
  67602. var xv2 = faceData[2];
  67603. for (var x = 0; x < texSize; x++) {
  67604. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  67605. v.normalize();
  67606. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  67607. // 3 channels per pixels
  67608. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  67609. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  67610. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  67611. xv1 = xv1.add(rotDX1);
  67612. xv2 = xv2.add(rotDX2);
  67613. }
  67614. fy += dy;
  67615. }
  67616. return textureArray;
  67617. };
  67618. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  67619. var theta = Math.atan2(vDir.z, vDir.x);
  67620. var phi = Math.acos(vDir.y);
  67621. while (theta < -Math.PI)
  67622. theta += 2 * Math.PI;
  67623. while (theta > Math.PI)
  67624. theta -= 2 * Math.PI;
  67625. var dx = theta / Math.PI;
  67626. var dy = phi / Math.PI;
  67627. // recenter.
  67628. dx = dx * 0.5 + 0.5;
  67629. var px = Math.round(dx * inputWidth);
  67630. if (px < 0)
  67631. px = 0;
  67632. else if (px >= inputWidth)
  67633. px = inputWidth - 1;
  67634. var py = Math.round(dy * inputHeight);
  67635. if (py < 0)
  67636. py = 0;
  67637. else if (py >= inputHeight)
  67638. py = inputHeight - 1;
  67639. var inputY = (inputHeight - py - 1);
  67640. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  67641. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  67642. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  67643. return {
  67644. r: r,
  67645. g: g,
  67646. b: b
  67647. };
  67648. };
  67649. PanoramaToCubeMapTools.FACE_FRONT = [
  67650. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  67651. new BABYLON.Vector3(1.0, -1.0, -1.0),
  67652. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  67653. new BABYLON.Vector3(1.0, 1.0, -1.0)
  67654. ];
  67655. PanoramaToCubeMapTools.FACE_BACK = [
  67656. new BABYLON.Vector3(1.0, -1.0, 1.0),
  67657. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  67658. new BABYLON.Vector3(1.0, 1.0, 1.0),
  67659. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  67660. ];
  67661. PanoramaToCubeMapTools.FACE_RIGHT = [
  67662. new BABYLON.Vector3(1.0, -1.0, -1.0),
  67663. new BABYLON.Vector3(1.0, -1.0, 1.0),
  67664. new BABYLON.Vector3(1.0, 1.0, -1.0),
  67665. new BABYLON.Vector3(1.0, 1.0, 1.0)
  67666. ];
  67667. PanoramaToCubeMapTools.FACE_LEFT = [
  67668. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  67669. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  67670. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  67671. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  67672. ];
  67673. PanoramaToCubeMapTools.FACE_DOWN = [
  67674. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  67675. new BABYLON.Vector3(1.0, 1.0, -1.0),
  67676. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  67677. new BABYLON.Vector3(1.0, 1.0, 1.0)
  67678. ];
  67679. PanoramaToCubeMapTools.FACE_UP = [
  67680. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  67681. new BABYLON.Vector3(1.0, -1.0, 1.0),
  67682. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  67683. new BABYLON.Vector3(1.0, -1.0, -1.0)
  67684. ];
  67685. return PanoramaToCubeMapTools;
  67686. }());
  67687. BABYLON.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  67688. })(BABYLON || (BABYLON = {}));
  67689. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  67690. var BABYLON;
  67691. (function (BABYLON) {
  67692. ;
  67693. /**
  67694. * This groups tools to convert HDR texture to native colors array.
  67695. */
  67696. var HDRTools = /** @class */ (function () {
  67697. function HDRTools() {
  67698. }
  67699. HDRTools.Ldexp = function (mantissa, exponent) {
  67700. if (exponent > 1023) {
  67701. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  67702. }
  67703. if (exponent < -1074) {
  67704. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  67705. }
  67706. return mantissa * Math.pow(2, exponent);
  67707. };
  67708. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  67709. if (exponent > 0) {
  67710. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  67711. float32array[index + 0] = red * exponent;
  67712. float32array[index + 1] = green * exponent;
  67713. float32array[index + 2] = blue * exponent;
  67714. }
  67715. else {
  67716. float32array[index + 0] = 0;
  67717. float32array[index + 1] = 0;
  67718. float32array[index + 2] = 0;
  67719. }
  67720. };
  67721. HDRTools.readStringLine = function (uint8array, startIndex) {
  67722. var line = "";
  67723. var character = "";
  67724. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  67725. character = String.fromCharCode(uint8array[i]);
  67726. if (character == "\n") {
  67727. break;
  67728. }
  67729. line += character;
  67730. }
  67731. return line;
  67732. };
  67733. /**
  67734. * Reads header information from an RGBE texture stored in a native array.
  67735. * More information on this format are available here:
  67736. * https://en.wikipedia.org/wiki/RGBE_image_format
  67737. *
  67738. * @param uint8array The binary file stored in native array.
  67739. * @return The header information.
  67740. */
  67741. HDRTools.RGBE_ReadHeader = function (uint8array) {
  67742. var height = 0;
  67743. var width = 0;
  67744. var line = this.readStringLine(uint8array, 0);
  67745. if (line[0] != '#' || line[1] != '?') {
  67746. throw "Bad HDR Format.";
  67747. }
  67748. var endOfHeader = false;
  67749. var findFormat = false;
  67750. var lineIndex = 0;
  67751. do {
  67752. lineIndex += (line.length + 1);
  67753. line = this.readStringLine(uint8array, lineIndex);
  67754. if (line == "FORMAT=32-bit_rle_rgbe") {
  67755. findFormat = true;
  67756. }
  67757. else if (line.length == 0) {
  67758. endOfHeader = true;
  67759. }
  67760. } while (!endOfHeader);
  67761. if (!findFormat) {
  67762. throw "HDR Bad header format, unsupported FORMAT";
  67763. }
  67764. lineIndex += (line.length + 1);
  67765. line = this.readStringLine(uint8array, lineIndex);
  67766. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  67767. var match = sizeRegexp.exec(line);
  67768. // TODO. Support +Y and -X if needed.
  67769. if (!match || match.length < 3) {
  67770. throw "HDR Bad header format, no size";
  67771. }
  67772. width = parseInt(match[2]);
  67773. height = parseInt(match[1]);
  67774. if (width < 8 || width > 0x7fff) {
  67775. throw "HDR Bad header format, unsupported size";
  67776. }
  67777. lineIndex += (line.length + 1);
  67778. return {
  67779. height: height,
  67780. width: width,
  67781. dataPosition: lineIndex
  67782. };
  67783. };
  67784. /**
  67785. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  67786. * This RGBE texture needs to store the information as a panorama.
  67787. *
  67788. * More information on this format are available here:
  67789. * https://en.wikipedia.org/wiki/RGBE_image_format
  67790. *
  67791. * @param buffer The binary file stored in an array buffer.
  67792. * @param size The expected size of the extracted cubemap.
  67793. * @return The Cube Map information.
  67794. */
  67795. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  67796. var uint8array = new Uint8Array(buffer);
  67797. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  67798. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  67799. var cubeMapData = BABYLON.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  67800. return cubeMapData;
  67801. };
  67802. /**
  67803. * Returns the pixels data extracted from an RGBE texture.
  67804. * This pixels will be stored left to right up to down in the R G B order in one array.
  67805. *
  67806. * More information on this format are available here:
  67807. * https://en.wikipedia.org/wiki/RGBE_image_format
  67808. *
  67809. * @param uint8array The binary file stored in an array buffer.
  67810. * @param hdrInfo The header information of the file.
  67811. * @return The pixels data in RGB right to left up to down order.
  67812. */
  67813. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  67814. // Keep for multi format supports.
  67815. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  67816. };
  67817. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  67818. var num_scanlines = hdrInfo.height;
  67819. var scanline_width = hdrInfo.width;
  67820. var a, b, c, d, count;
  67821. var dataIndex = hdrInfo.dataPosition;
  67822. var index = 0, endIndex = 0, i = 0;
  67823. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  67824. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  67825. // 3 channels of 4 bytes per pixel in float.
  67826. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  67827. var resultArray = new Float32Array(resultBuffer);
  67828. // read in each successive scanline
  67829. while (num_scanlines > 0) {
  67830. a = uint8array[dataIndex++];
  67831. b = uint8array[dataIndex++];
  67832. c = uint8array[dataIndex++];
  67833. d = uint8array[dataIndex++];
  67834. if (a != 2 || b != 2 || (c & 0x80)) {
  67835. // this file is not run length encoded
  67836. throw "HDR Bad header format, not RLE";
  67837. }
  67838. if (((c << 8) | d) != scanline_width) {
  67839. throw "HDR Bad header format, wrong scan line width";
  67840. }
  67841. index = 0;
  67842. // read each of the four channels for the scanline into the buffer
  67843. for (i = 0; i < 4; i++) {
  67844. endIndex = (i + 1) * scanline_width;
  67845. while (index < endIndex) {
  67846. a = uint8array[dataIndex++];
  67847. b = uint8array[dataIndex++];
  67848. if (a > 128) {
  67849. // a run of the same value
  67850. count = a - 128;
  67851. if ((count == 0) || (count > endIndex - index)) {
  67852. throw "HDR Bad Format, bad scanline data (run)";
  67853. }
  67854. while (count-- > 0) {
  67855. scanLineArray[index++] = b;
  67856. }
  67857. }
  67858. else {
  67859. // a non-run
  67860. count = a;
  67861. if ((count == 0) || (count > endIndex - index)) {
  67862. throw "HDR Bad Format, bad scanline data (non-run)";
  67863. }
  67864. scanLineArray[index++] = b;
  67865. if (--count > 0) {
  67866. for (var j = 0; j < count; j++) {
  67867. scanLineArray[index++] = uint8array[dataIndex++];
  67868. }
  67869. }
  67870. }
  67871. }
  67872. }
  67873. // now convert data from buffer into floats
  67874. for (i = 0; i < scanline_width; i++) {
  67875. a = scanLineArray[i];
  67876. b = scanLineArray[i + scanline_width];
  67877. c = scanLineArray[i + 2 * scanline_width];
  67878. d = scanLineArray[i + 3 * scanline_width];
  67879. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  67880. }
  67881. num_scanlines--;
  67882. }
  67883. return resultArray;
  67884. };
  67885. return HDRTools;
  67886. }());
  67887. BABYLON.HDRTools = HDRTools;
  67888. })(BABYLON || (BABYLON = {}));
  67889. //# sourceMappingURL=babylon.hdr.js.map
  67890. var BABYLON;
  67891. (function (BABYLON) {
  67892. /**
  67893. * This represents a texture coming from an HDR input.
  67894. *
  67895. * The only supported format is currently panorama picture stored in RGBE format.
  67896. * Example of such files can be found on HDRLib: http://hdrlib.com/
  67897. */
  67898. var HDRCubeTexture = /** @class */ (function (_super) {
  67899. __extends(HDRCubeTexture, _super);
  67900. /**
  67901. * Instantiates an HDRTexture from the following parameters.
  67902. *
  67903. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  67904. * @param scene The scene the texture will be used in
  67905. * @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.
  67906. * @param noMipmap Forces to not generate the mipmap if true
  67907. * @param generateHarmonics Specifies whether you want to extract the polynomial harmonics during the generation process
  67908. * @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)
  67909. * @param usePMREMGenerator Specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time.
  67910. */
  67911. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator, onLoad, onError) {
  67912. if (noMipmap === void 0) { noMipmap = false; }
  67913. if (generateHarmonics === void 0) { generateHarmonics = true; }
  67914. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  67915. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  67916. if (onLoad === void 0) { onLoad = null; }
  67917. if (onError === void 0) { onError = null; }
  67918. var _this = _super.call(this, scene) || this;
  67919. _this._useInGammaSpace = false;
  67920. _this._generateHarmonics = true;
  67921. _this._isBABYLONPreprocessed = false;
  67922. _this._onLoad = null;
  67923. _this._onError = null;
  67924. /**
  67925. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  67926. */
  67927. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  67928. /**
  67929. * Specifies wether the texture has been generated through the PMREMGenerator tool.
  67930. * This is usefull at run time to apply the good shader.
  67931. */
  67932. _this.isPMREM = false;
  67933. _this._isBlocking = true;
  67934. if (!url) {
  67935. return _this;
  67936. }
  67937. _this.name = url;
  67938. _this.url = url;
  67939. _this.hasAlpha = false;
  67940. _this.isCube = true;
  67941. _this._textureMatrix = BABYLON.Matrix.Identity();
  67942. _this._onLoad = onLoad;
  67943. _this._onError = onError;
  67944. _this.gammaSpace = false;
  67945. var caps = scene.getEngine().getCaps();
  67946. if (size) {
  67947. _this._isBABYLONPreprocessed = false;
  67948. _this._noMipmap = noMipmap;
  67949. _this._size = size;
  67950. _this._useInGammaSpace = useInGammaSpace;
  67951. _this._usePMREMGenerator = usePMREMGenerator &&
  67952. caps.textureLOD &&
  67953. caps.textureFloat &&
  67954. !_this._useInGammaSpace;
  67955. }
  67956. else {
  67957. _this._isBABYLONPreprocessed = true;
  67958. _this._noMipmap = false;
  67959. _this._useInGammaSpace = false;
  67960. _this._usePMREMGenerator = caps.textureLOD && caps.textureFloat &&
  67961. !_this._useInGammaSpace;
  67962. }
  67963. _this.isPMREM = _this._usePMREMGenerator;
  67964. _this._texture = _this._getFromCache(url, _this._noMipmap);
  67965. if (!_this._texture) {
  67966. if (!scene.useDelayedTextureLoading) {
  67967. _this.loadTexture();
  67968. }
  67969. else {
  67970. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  67971. }
  67972. }
  67973. return _this;
  67974. }
  67975. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  67976. /**
  67977. * Gets wether or not the texture is blocking during loading.
  67978. */
  67979. get: function () {
  67980. return this._isBlocking;
  67981. },
  67982. /**
  67983. * Sets wether or not the texture is blocking during loading.
  67984. */
  67985. set: function (value) {
  67986. this._isBlocking = value;
  67987. },
  67988. enumerable: true,
  67989. configurable: true
  67990. });
  67991. /**
  67992. * Occurs when the file is a preprocessed .babylon.hdr file.
  67993. */
  67994. HDRCubeTexture.prototype.loadBabylonTexture = function () {
  67995. var _this = this;
  67996. var mipLevels = 0;
  67997. var floatArrayView = null;
  67998. var scene = this.getScene();
  67999. var mipmapGenerator = (!this._useInGammaSpace && scene && scene.getEngine().getCaps().textureFloat) ? function (data) {
  68000. var mips = new Array();
  68001. if (!floatArrayView) {
  68002. return mips;
  68003. }
  68004. var startIndex = 30;
  68005. for (var level = 0; level < mipLevels; level++) {
  68006. mips.push([]);
  68007. // Fill each pixel of the mip level.
  68008. var faceSize = Math.pow(_this._size >> level, 2) * 3;
  68009. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  68010. var faceData = floatArrayView.subarray(startIndex, startIndex + faceSize);
  68011. mips[level].push(faceData);
  68012. startIndex += faceSize;
  68013. }
  68014. }
  68015. return mips;
  68016. } : null;
  68017. var callback = function (buffer) {
  68018. var scene = _this.getScene();
  68019. if (!scene) {
  68020. return null;
  68021. }
  68022. // Create Native Array Views
  68023. var intArrayView = new Int32Array(buffer);
  68024. floatArrayView = new Float32Array(buffer);
  68025. // Fill header.
  68026. var version = intArrayView[0]; // Version 1. (MAy be use in case of format changes for backward compaibility)
  68027. _this._size = intArrayView[1]; // CubeMap max mip face size.
  68028. // Update Texture Information.
  68029. if (!_this._texture) {
  68030. return null;
  68031. }
  68032. _this._texture.updateSize(_this._size, _this._size);
  68033. // Fill polynomial information.
  68034. var sphericalPolynomial = new BABYLON.SphericalPolynomial();
  68035. sphericalPolynomial.x.copyFromFloats(floatArrayView[2], floatArrayView[3], floatArrayView[4]);
  68036. sphericalPolynomial.y.copyFromFloats(floatArrayView[5], floatArrayView[6], floatArrayView[7]);
  68037. sphericalPolynomial.z.copyFromFloats(floatArrayView[8], floatArrayView[9], floatArrayView[10]);
  68038. sphericalPolynomial.xx.copyFromFloats(floatArrayView[11], floatArrayView[12], floatArrayView[13]);
  68039. sphericalPolynomial.yy.copyFromFloats(floatArrayView[14], floatArrayView[15], floatArrayView[16]);
  68040. sphericalPolynomial.zz.copyFromFloats(floatArrayView[17], floatArrayView[18], floatArrayView[19]);
  68041. sphericalPolynomial.xy.copyFromFloats(floatArrayView[20], floatArrayView[21], floatArrayView[22]);
  68042. sphericalPolynomial.yz.copyFromFloats(floatArrayView[23], floatArrayView[24], floatArrayView[25]);
  68043. sphericalPolynomial.zx.copyFromFloats(floatArrayView[26], floatArrayView[27], floatArrayView[28]);
  68044. _this.sphericalPolynomial = sphericalPolynomial;
  68045. // Fill pixel data.
  68046. mipLevels = intArrayView[29]; // Number of mip levels.
  68047. var startIndex = 30;
  68048. var data = [];
  68049. var faceSize = Math.pow(_this._size, 2) * 3;
  68050. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  68051. data.push(floatArrayView.subarray(startIndex, startIndex + faceSize));
  68052. startIndex += faceSize;
  68053. }
  68054. var results = [];
  68055. var byteArray = null;
  68056. // Push each faces.
  68057. for (var k = 0; k < 6; k++) {
  68058. var dataFace = null;
  68059. // To be deprecated.
  68060. if (version === 1) {
  68061. var j = ([0, 2, 4, 1, 3, 5])[k]; // Transforms +X+Y+Z... to +X-X+Y-Y...
  68062. dataFace = data[j];
  68063. }
  68064. // If special cases.
  68065. if (!mipmapGenerator && dataFace) {
  68066. if (!scene.getEngine().getCaps().textureFloat) {
  68067. // 3 channels of 1 bytes per pixel in bytes.
  68068. var byteBuffer = new ArrayBuffer(faceSize);
  68069. byteArray = new Uint8Array(byteBuffer);
  68070. }
  68071. for (var i = 0; i < _this._size * _this._size; i++) {
  68072. // Put in gamma space if requested.
  68073. if (_this._useInGammaSpace) {
  68074. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  68075. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  68076. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  68077. }
  68078. // Convert to int texture for fallback.
  68079. if (byteArray) {
  68080. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  68081. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  68082. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  68083. // May use luminance instead if the result is not accurate.
  68084. var max = Math.max(Math.max(r, g), b);
  68085. if (max > 255) {
  68086. var scale = 255 / max;
  68087. r *= scale;
  68088. g *= scale;
  68089. b *= scale;
  68090. }
  68091. byteArray[(i * 3) + 0] = r;
  68092. byteArray[(i * 3) + 1] = g;
  68093. byteArray[(i * 3) + 2] = b;
  68094. }
  68095. }
  68096. }
  68097. // Fill the array accordingly.
  68098. if (byteArray) {
  68099. results.push(byteArray);
  68100. }
  68101. else {
  68102. results.push(dataFace);
  68103. }
  68104. }
  68105. return results;
  68106. };
  68107. if (scene) {
  68108. 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);
  68109. }
  68110. };
  68111. /**
  68112. * Occurs when the file is raw .hdr file.
  68113. */
  68114. HDRCubeTexture.prototype.loadHDRTexture = function () {
  68115. var _this = this;
  68116. var callback = function (buffer) {
  68117. var scene = _this.getScene();
  68118. if (!scene) {
  68119. return null;
  68120. }
  68121. // Extract the raw linear data.
  68122. var data = BABYLON.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  68123. // Generate harmonics if needed.
  68124. if (_this._generateHarmonics) {
  68125. var sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  68126. _this.sphericalPolynomial = sphericalPolynomial;
  68127. }
  68128. var results = [];
  68129. var byteArray = null;
  68130. // Push each faces.
  68131. for (var j = 0; j < 6; j++) {
  68132. // Create uintarray fallback.
  68133. if (!scene.getEngine().getCaps().textureFloat) {
  68134. // 3 channels of 1 bytes per pixel in bytes.
  68135. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  68136. byteArray = new Uint8Array(byteBuffer);
  68137. }
  68138. var dataFace = (data[HDRCubeTexture._facesMapping[j]]);
  68139. // If special cases.
  68140. if (_this._useInGammaSpace || byteArray) {
  68141. for (var i = 0; i < _this._size * _this._size; i++) {
  68142. // Put in gamma space if requested.
  68143. if (_this._useInGammaSpace) {
  68144. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  68145. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  68146. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  68147. }
  68148. // Convert to int texture for fallback.
  68149. if (byteArray) {
  68150. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  68151. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  68152. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  68153. // May use luminance instead if the result is not accurate.
  68154. var max = Math.max(Math.max(r, g), b);
  68155. if (max > 255) {
  68156. var scale = 255 / max;
  68157. r *= scale;
  68158. g *= scale;
  68159. b *= scale;
  68160. }
  68161. byteArray[(i * 3) + 0] = r;
  68162. byteArray[(i * 3) + 1] = g;
  68163. byteArray[(i * 3) + 2] = b;
  68164. }
  68165. }
  68166. }
  68167. if (byteArray) {
  68168. results.push(byteArray);
  68169. }
  68170. else {
  68171. results.push(dataFace);
  68172. }
  68173. }
  68174. return results;
  68175. };
  68176. var mipmapGenerator = null;
  68177. // TODO. Implement In code PMREM Generator following the LYS toolset generation.
  68178. // if (!this._noMipmap &&
  68179. // this._usePMREMGenerator) {
  68180. // mipmapGenerator = (data: ArrayBufferView[]) => {
  68181. // // Custom setup of the generator matching with the PBR shader values.
  68182. // var generator = new BABYLON.PMREMGenerator(data,
  68183. // this._size,
  68184. // this._size,
  68185. // 0,
  68186. // 3,
  68187. // this.getScene().getEngine().getCaps().textureFloat,
  68188. // 2048,
  68189. // 0.25,
  68190. // false,
  68191. // true);
  68192. // return generator.filterCubeMap();
  68193. // };
  68194. // }
  68195. var scene = this.getScene();
  68196. if (scene) {
  68197. 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);
  68198. }
  68199. };
  68200. /**
  68201. * Starts the loading process of the texture.
  68202. */
  68203. HDRCubeTexture.prototype.loadTexture = function () {
  68204. if (this._isBABYLONPreprocessed) {
  68205. this.loadBabylonTexture();
  68206. }
  68207. else {
  68208. this.loadHDRTexture();
  68209. }
  68210. };
  68211. HDRCubeTexture.prototype.clone = function () {
  68212. var scene = this.getScene();
  68213. if (!scene) {
  68214. return this;
  68215. }
  68216. var size = (this._isBABYLONPreprocessed ? null : this._size);
  68217. var newTexture = new HDRCubeTexture(this.url, scene, size, this._noMipmap, this._generateHarmonics, this._useInGammaSpace, this._usePMREMGenerator);
  68218. // Base texture
  68219. newTexture.level = this.level;
  68220. newTexture.wrapU = this.wrapU;
  68221. newTexture.wrapV = this.wrapV;
  68222. newTexture.coordinatesIndex = this.coordinatesIndex;
  68223. newTexture.coordinatesMode = this.coordinatesMode;
  68224. return newTexture;
  68225. };
  68226. // Methods
  68227. HDRCubeTexture.prototype.delayLoad = function () {
  68228. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  68229. return;
  68230. }
  68231. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  68232. this._texture = this._getFromCache(this.url, this._noMipmap);
  68233. if (!this._texture) {
  68234. this.loadTexture();
  68235. }
  68236. };
  68237. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  68238. return this._textureMatrix;
  68239. };
  68240. HDRCubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  68241. this._textureMatrix = value;
  68242. };
  68243. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  68244. var texture = null;
  68245. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  68246. var size = parsedTexture.isBABYLONPreprocessed ? null : parsedTexture.size;
  68247. texture = new HDRCubeTexture(rootUrl + parsedTexture.name, scene, size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace, parsedTexture.usePMREMGenerator);
  68248. texture.name = parsedTexture.name;
  68249. texture.hasAlpha = parsedTexture.hasAlpha;
  68250. texture.level = parsedTexture.level;
  68251. texture.coordinatesMode = parsedTexture.coordinatesMode;
  68252. texture.isBlocking = parsedTexture.isBlocking;
  68253. }
  68254. return texture;
  68255. };
  68256. HDRCubeTexture.prototype.serialize = function () {
  68257. if (!this.name) {
  68258. return null;
  68259. }
  68260. var serializationObject = {};
  68261. serializationObject.name = this.name;
  68262. serializationObject.hasAlpha = this.hasAlpha;
  68263. serializationObject.isCube = true;
  68264. serializationObject.level = this.level;
  68265. serializationObject.size = this._size;
  68266. serializationObject.coordinatesMode = this.coordinatesMode;
  68267. serializationObject.useInGammaSpace = this._useInGammaSpace;
  68268. serializationObject.generateHarmonics = this._generateHarmonics;
  68269. serializationObject.usePMREMGenerator = this._usePMREMGenerator;
  68270. serializationObject.isBABYLONPreprocessed = this._isBABYLONPreprocessed;
  68271. serializationObject.customType = "BABYLON.HDRCubeTexture";
  68272. serializationObject.noMipmap = this._noMipmap;
  68273. serializationObject.isBlocking = this._isBlocking;
  68274. return serializationObject;
  68275. };
  68276. /**
  68277. * Saves as a file the data contained in the texture in a binary format.
  68278. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  68279. * as the spherical used in the lighting.
  68280. * @param url The HDR file url.
  68281. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  68282. * @param onError Method called if any error happens during download.
  68283. * @return The packed binary data.
  68284. */
  68285. HDRCubeTexture.generateBabylonHDROnDisk = function (url, size, onError) {
  68286. if (onError === void 0) { onError = null; }
  68287. var callback = function (buffer) {
  68288. var data = new Blob([buffer], { type: 'application/octet-stream' });
  68289. // Returns a URL you can use as a href.
  68290. var objUrl = window.URL.createObjectURL(data);
  68291. // Simulates a link to it and click to dowload.
  68292. var a = document.createElement("a");
  68293. document.body.appendChild(a);
  68294. a.style.display = "none";
  68295. a.href = objUrl;
  68296. a.download = "envmap.babylon.hdr";
  68297. a.click();
  68298. };
  68299. HDRCubeTexture.generateBabylonHDR(url, size, callback, onError);
  68300. };
  68301. /**
  68302. * Serializes the data contained in the texture in a binary format.
  68303. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  68304. * as the spherical used in the lighting.
  68305. * @param url The HDR file url.
  68306. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  68307. * @param onError Method called if any error happens during download.
  68308. * @return The packed binary data.
  68309. */
  68310. HDRCubeTexture.generateBabylonHDR = function (url, size, callback, onError) {
  68311. if (onError === void 0) { onError = null; }
  68312. // Needs the url tho create the texture.
  68313. if (!url) {
  68314. return;
  68315. }
  68316. // Check Power of two size.
  68317. if (!BABYLON.Tools.IsExponentOfTwo(size)) {
  68318. return;
  68319. }
  68320. // Coming Back in 3.x.
  68321. BABYLON.Tools.Error("Generation of Babylon HDR is coming back in 3.2.");
  68322. };
  68323. HDRCubeTexture._facesMapping = [
  68324. "right",
  68325. "left",
  68326. "up",
  68327. "down",
  68328. "front",
  68329. "back"
  68330. ];
  68331. return HDRCubeTexture;
  68332. }(BABYLON.BaseTexture));
  68333. BABYLON.HDRCubeTexture = HDRCubeTexture;
  68334. })(BABYLON || (BABYLON = {}));
  68335. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  68336. // All the credit goes to this project and the guy who's behind it https://github.com/mapbox/earcut
  68337. // Huge respect for a such great lib.
  68338. // Earcut license:
  68339. // Copyright (c) 2016, Mapbox
  68340. //
  68341. // Permission to use, copy, modify, and/or distribute this software for any purpose
  68342. // with or without fee is hereby granted, provided that the above copyright notice
  68343. // and this permission notice appear in all copies.
  68344. //
  68345. // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
  68346. // REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
  68347. // FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
  68348. // INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
  68349. // OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
  68350. // TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
  68351. // THIS SOFTWARE.
  68352. var Earcut;
  68353. (function (Earcut) {
  68354. /**
  68355. * The fastest and smallest JavaScript polygon triangulation library for your WebGL apps
  68356. * @param data is a flat array of vertice coordinates like [x0, y0, x1, y1, x2, y2, ...].
  68357. * @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).
  68358. * @param dim is the number of coordinates per vertice in the input array (2 by default).
  68359. */
  68360. function earcut(data, holeIndices, dim) {
  68361. dim = dim || 2;
  68362. var hasHoles = holeIndices && holeIndices.length, outerLen = hasHoles ? holeIndices[0] * dim : data.length, outerNode = linkedList(data, 0, outerLen, dim, true), triangles = new Array();
  68363. if (!outerNode)
  68364. return triangles;
  68365. var minX = 0, minY = 0, maxX, maxY, x, y, size = 0;
  68366. if (hasHoles)
  68367. outerNode = eliminateHoles(data, holeIndices, outerNode, dim);
  68368. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  68369. if (data.length > 80 * dim) {
  68370. minX = maxX = data[0];
  68371. minY = maxY = data[1];
  68372. for (var i = dim; i < outerLen; i += dim) {
  68373. x = data[i];
  68374. y = data[i + 1];
  68375. if (x < minX)
  68376. minX = x;
  68377. if (y < minY)
  68378. minY = y;
  68379. if (x > maxX)
  68380. maxX = x;
  68381. if (y > maxY)
  68382. maxY = y;
  68383. }
  68384. // minX, minY and size are later used to transform coords into integers for z-order calculation
  68385. size = Math.max(maxX - minX, maxY - minY);
  68386. }
  68387. earcutLinked(outerNode, triangles, dim, minX, minY, size, 0);
  68388. return triangles;
  68389. }
  68390. Earcut.earcut = earcut;
  68391. var Node = /** @class */ (function () {
  68392. function Node(i, x, y) {
  68393. this.i = i;
  68394. this.x = x;
  68395. this.y = y;
  68396. this.prev = null;
  68397. this.next = null;
  68398. this.z = null;
  68399. this.prevZ = null;
  68400. this.nextZ = null;
  68401. this.steiner = false;
  68402. }
  68403. return Node;
  68404. }());
  68405. // create a circular doubly linked list from polygon points in the specified winding order
  68406. function linkedList(data, start, end, dim, clockwise) {
  68407. var i, last = null;
  68408. if (clockwise === (signedArea(data, start, end, dim) > 0)) {
  68409. for (i = start; i < end; i += dim)
  68410. last = insertNode(i, data[i], data[i + 1], last);
  68411. }
  68412. else {
  68413. for (i = end - dim; i >= start; i -= dim)
  68414. last = insertNode(i, data[i], data[i + 1], last);
  68415. }
  68416. if (last && equals(last, last.next)) {
  68417. removeNode(last);
  68418. last = last.next;
  68419. }
  68420. return last;
  68421. }
  68422. // eliminate colinear or duplicate points
  68423. function filterPoints(start, end) {
  68424. if (!start)
  68425. return start;
  68426. if (!end)
  68427. end = start;
  68428. var p = start, again;
  68429. do {
  68430. again = false;
  68431. if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
  68432. removeNode(p);
  68433. p = end = p.prev;
  68434. if (p === p.next)
  68435. return undefined;
  68436. again = true;
  68437. }
  68438. else {
  68439. p = p.next;
  68440. }
  68441. } while (again || p !== end);
  68442. return end;
  68443. }
  68444. // main ear slicing loop which triangulates a polygon (given as a linked list)
  68445. function earcutLinked(ear, triangles, dim, minX, minY, size, pass) {
  68446. if (!ear)
  68447. return;
  68448. // interlink polygon nodes in z-order
  68449. if (!pass && size)
  68450. indexCurve(ear, minX, minY, size);
  68451. var stop = ear, prev, next;
  68452. // iterate through ears, slicing them one by one
  68453. while (ear.prev !== ear.next) {
  68454. prev = ear.prev;
  68455. next = ear.next;
  68456. if (size ? isEarHashed(ear, minX, minY, size) : isEar(ear)) {
  68457. // cut off the triangle
  68458. triangles.push(prev.i / dim);
  68459. triangles.push(ear.i / dim);
  68460. triangles.push(next.i / dim);
  68461. removeNode(ear);
  68462. // skipping the next vertice leads to less sliver triangles
  68463. ear = next.next;
  68464. stop = next.next;
  68465. continue;
  68466. }
  68467. ear = next;
  68468. // if we looped through the whole remaining polygon and can't find any more ears
  68469. if (ear === stop) {
  68470. // try filtering points and slicing again
  68471. if (!pass) {
  68472. earcutLinked(filterPoints(ear, undefined), triangles, dim, minX, minY, size, 1);
  68473. // if this didn't work, try curing all small self-intersections locally
  68474. }
  68475. else if (pass === 1) {
  68476. ear = cureLocalIntersections(ear, triangles, dim);
  68477. earcutLinked(ear, triangles, dim, minX, minY, size, 2);
  68478. // as a last resort, try splitting the remaining polygon into two
  68479. }
  68480. else if (pass === 2) {
  68481. splitEarcut(ear, triangles, dim, minX, minY, size);
  68482. }
  68483. break;
  68484. }
  68485. }
  68486. }
  68487. // check whether a polygon node forms a valid ear with adjacent nodes
  68488. function isEar(ear) {
  68489. var a = ear.prev, b = ear, c = ear.next;
  68490. if (area(a, b, c) >= 0)
  68491. return false; // reflex, can't be an ear
  68492. // now make sure we don't have other points inside the potential ear
  68493. var p = ear.next.next;
  68494. while (p !== ear.prev) {
  68495. if (pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  68496. area(p.prev, p, p.next) >= 0)
  68497. return false;
  68498. p = p.next;
  68499. }
  68500. return true;
  68501. }
  68502. function isEarHashed(ear, minX, minY, size) {
  68503. var a = ear.prev, b = ear, c = ear.next;
  68504. if (area(a, b, c) >= 0)
  68505. return false; // reflex, can't be an ear
  68506. // triangle bbox; min & max are calculated like this for speed
  68507. 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);
  68508. // z-order range for the current triangle bbox;
  68509. var minZ = zOrder(minTX, minTY, minX, minY, size), maxZ = zOrder(maxTX, maxTY, minX, minY, size);
  68510. // first look for points inside the triangle in increasing z-order
  68511. var p = ear.nextZ;
  68512. while (p && p.z <= maxZ) {
  68513. if (p !== ear.prev &&
  68514. p !== ear.next &&
  68515. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  68516. area(p.prev, p, p.next) >= 0)
  68517. return false;
  68518. p = p.nextZ;
  68519. }
  68520. // then look for points in decreasing z-order
  68521. p = ear.prevZ;
  68522. while (p && p.z >= minZ) {
  68523. if (p !== ear.prev &&
  68524. p !== ear.next &&
  68525. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  68526. area(p.prev, p, p.next) >= 0)
  68527. return false;
  68528. p = p.prevZ;
  68529. }
  68530. return true;
  68531. }
  68532. // go through all polygon nodes and cure small local self-intersections
  68533. function cureLocalIntersections(start, triangles, dim) {
  68534. var p = start;
  68535. do {
  68536. var a = p.prev, b = p.next.next;
  68537. if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
  68538. triangles.push(a.i / dim);
  68539. triangles.push(p.i / dim);
  68540. triangles.push(b.i / dim);
  68541. // remove two nodes involved
  68542. removeNode(p);
  68543. removeNode(p.next);
  68544. p = start = b;
  68545. }
  68546. p = p.next;
  68547. } while (p !== start);
  68548. return p;
  68549. }
  68550. // try splitting polygon into two and triangulate them independently
  68551. function splitEarcut(start, triangles, dim, minX, minY, size) {
  68552. // look for a valid diagonal that divides the polygon into two
  68553. var a = start;
  68554. do {
  68555. var b = a.next.next;
  68556. while (b !== a.prev) {
  68557. if (a.i !== b.i && isValidDiagonal(a, b)) {
  68558. // split the polygon in two by the diagonal
  68559. var c = splitPolygon(a, b);
  68560. // filter colinear points around the cuts
  68561. a = filterPoints(a, a.next);
  68562. c = filterPoints(c, c.next);
  68563. // run earcut on each half
  68564. earcutLinked(a, triangles, dim, minX, minY, size, undefined);
  68565. earcutLinked(c, triangles, dim, minX, minY, size, undefined);
  68566. return;
  68567. }
  68568. b = b.next;
  68569. }
  68570. a = a.next;
  68571. } while (a !== start);
  68572. }
  68573. // link every hole into the outer loop, producing a single-ring polygon without holes
  68574. function eliminateHoles(data, holeIndices, outerNode, dim) {
  68575. var queue = [], i, len, start, end, list;
  68576. for (i = 0, len = holeIndices.length; i < len; i++) {
  68577. start = holeIndices[i] * dim;
  68578. end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  68579. list = linkedList(data, start, end, dim, false);
  68580. if (list === list.next)
  68581. list.steiner = true;
  68582. queue.push(getLeftmost(list));
  68583. }
  68584. queue.sort(compareX);
  68585. // process holes from left to right
  68586. for (i = 0; i < queue.length; i++) {
  68587. eliminateHole(queue[i], outerNode);
  68588. outerNode = filterPoints(outerNode, outerNode.next);
  68589. }
  68590. return outerNode;
  68591. }
  68592. function compareX(a, b) {
  68593. return a.x - b.x;
  68594. }
  68595. // find a bridge between vertices that connects hole with an outer ring and and link it
  68596. function eliminateHole(hole, outerNode) {
  68597. outerNode = findHoleBridge(hole, outerNode);
  68598. if (outerNode) {
  68599. var b = splitPolygon(outerNode, hole);
  68600. filterPoints(b, b.next);
  68601. }
  68602. }
  68603. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  68604. function findHoleBridge(hole, outerNode) {
  68605. var p = outerNode, hx = hole.x, hy = hole.y, qx = -Infinity, m;
  68606. // find a segment intersected by a ray from the hole's leftmost point to the left;
  68607. // segment's endpoint with lesser x will be potential connection point
  68608. do {
  68609. if (hy <= p.y && hy >= p.next.y) {
  68610. var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
  68611. if (x <= hx && x > qx) {
  68612. qx = x;
  68613. if (x === hx) {
  68614. if (hy === p.y)
  68615. return p;
  68616. if (hy === p.next.y)
  68617. return p.next;
  68618. }
  68619. m = p.x < p.next.x ? p : p.next;
  68620. }
  68621. }
  68622. p = p.next;
  68623. } while (p !== outerNode);
  68624. if (!m)
  68625. return null;
  68626. if (hx === qx)
  68627. return m.prev; // hole touches outer segment; pick lower endpoint
  68628. // look for points inside the triangle of hole point, segment intersection and endpoint;
  68629. // if there are no points found, we have a valid connection;
  68630. // otherwise choose the point of the minimum angle with the ray as connection point
  68631. var stop = m, mx = m.x, my = m.y, tanMin = Infinity, tan;
  68632. p = m.next;
  68633. while (p !== stop) {
  68634. if (hx >= p.x &&
  68635. p.x >= mx &&
  68636. pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) {
  68637. tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
  68638. if ((tan < tanMin || (tan === tanMin && p.x > m.x)) && locallyInside(p, hole)) {
  68639. m = p;
  68640. tanMin = tan;
  68641. }
  68642. }
  68643. p = p.next;
  68644. }
  68645. return m;
  68646. }
  68647. // interlink polygon nodes in z-order
  68648. function indexCurve(start, minX, minY, size) {
  68649. var p = start;
  68650. do {
  68651. if (p.z === null)
  68652. p.z = zOrder(p.x, p.y, minX, minY, size);
  68653. p.prevZ = p.prev;
  68654. p.nextZ = p.next;
  68655. p = p.next;
  68656. } while (p !== start);
  68657. p.prevZ.nextZ = null;
  68658. p.prevZ = null;
  68659. sortLinked(p);
  68660. }
  68661. // Simon Tatham's linked list merge sort algorithm
  68662. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  68663. function sortLinked(list) {
  68664. var i, p, q, e, tail, numMerges, pSize, qSize, inSize = 1;
  68665. do {
  68666. p = list;
  68667. list = null;
  68668. tail = null;
  68669. numMerges = 0;
  68670. while (p) {
  68671. numMerges++;
  68672. q = p;
  68673. pSize = 0;
  68674. for (i = 0; i < inSize; i++) {
  68675. pSize++;
  68676. q = q.nextZ;
  68677. if (!q)
  68678. break;
  68679. }
  68680. qSize = inSize;
  68681. while (pSize > 0 || (qSize > 0 && q)) {
  68682. if (pSize === 0) {
  68683. e = q;
  68684. q = q.nextZ;
  68685. qSize--;
  68686. }
  68687. else if (qSize === 0 || !q) {
  68688. e = p;
  68689. p = p.nextZ;
  68690. pSize--;
  68691. }
  68692. else if (p.z <= q.z) {
  68693. e = p;
  68694. p = p.nextZ;
  68695. pSize--;
  68696. }
  68697. else {
  68698. e = q;
  68699. q = q.nextZ;
  68700. qSize--;
  68701. }
  68702. if (tail)
  68703. tail.nextZ = e;
  68704. else
  68705. list = e;
  68706. e.prevZ = tail;
  68707. tail = e;
  68708. }
  68709. p = q;
  68710. }
  68711. tail.nextZ = null;
  68712. inSize *= 2;
  68713. } while (numMerges > 1);
  68714. return list;
  68715. }
  68716. // z-order of a point given coords and size of the data bounding box
  68717. function zOrder(x, y, minX, minY, size) {
  68718. // coords are transformed into non-negative 15-bit integer range
  68719. x = 32767 * (x - minX) / size;
  68720. y = 32767 * (y - minY) / size;
  68721. x = (x | (x << 8)) & 0x00FF00FF;
  68722. x = (x | (x << 4)) & 0x0F0F0F0F;
  68723. x = (x | (x << 2)) & 0x33333333;
  68724. x = (x | (x << 1)) & 0x55555555;
  68725. y = (y | (y << 8)) & 0x00FF00FF;
  68726. y = (y | (y << 4)) & 0x0F0F0F0F;
  68727. y = (y | (y << 2)) & 0x33333333;
  68728. y = (y | (y << 1)) & 0x55555555;
  68729. return x | (y << 1);
  68730. }
  68731. // find the leftmost node of a polygon ring
  68732. function getLeftmost(start) {
  68733. var p = start, leftmost = start;
  68734. do {
  68735. if (p.x < leftmost.x)
  68736. leftmost = p;
  68737. p = p.next;
  68738. } while (p !== start);
  68739. return leftmost;
  68740. }
  68741. // check if a point lies within a convex triangle
  68742. function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
  68743. return (cx - px) * (ay - py) - (ax - px) * (cy - py) >= 0 &&
  68744. (ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 &&
  68745. (bx - px) * (cy - py) - (cx - px) * (by - py) >= 0;
  68746. }
  68747. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  68748. function isValidDiagonal(a, b) {
  68749. return a.next.i !== b.i &&
  68750. a.prev.i !== b.i &&
  68751. !intersectsPolygon(a, b) &&
  68752. locallyInside(a, b) &&
  68753. locallyInside(b, a) &&
  68754. middleInside(a, b);
  68755. }
  68756. // signed area of a triangle
  68757. function area(p, q, r) {
  68758. return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
  68759. }
  68760. // check if two points are equal
  68761. function equals(p1, p2) {
  68762. return p1.x === p2.x && p1.y === p2.y;
  68763. }
  68764. // check if two segments intersect
  68765. function intersects(p1, q1, p2, q2) {
  68766. if ((equals(p1, q1) && equals(p2, q2)) ||
  68767. (equals(p1, q2) && equals(p2, q1)))
  68768. return true;
  68769. return area(p1, q1, p2) > 0 !== area(p1, q1, q2) > 0 &&
  68770. area(p2, q2, p1) > 0 !== area(p2, q2, q1) > 0;
  68771. }
  68772. // check if a polygon diagonal intersects any polygon segments
  68773. function intersectsPolygon(a, b) {
  68774. var p = a;
  68775. do {
  68776. if (p.i !== a.i &&
  68777. p.next.i !== a.i &&
  68778. p.i !== b.i &&
  68779. p.next.i !== b.i &&
  68780. intersects(p, p.next, a, b))
  68781. return true;
  68782. p = p.next;
  68783. } while (p !== a);
  68784. return false;
  68785. }
  68786. // check if a polygon diagonal is locally inside the polygon
  68787. function locallyInside(a, b) {
  68788. return area(a.prev, a, a.next) < 0
  68789. ? area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0
  68790. : area(a, b, a.prev) < 0 || area(a, a.next, b) < 0;
  68791. }
  68792. // check if the middle point of a polygon diagonal is inside the polygon
  68793. function middleInside(a, b) {
  68794. var p = a, inside = false, px = (a.x + b.x) / 2, py = (a.y + b.y) / 2;
  68795. do {
  68796. if (((p.y > py) !== (p.next.y > py)) && (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x))
  68797. inside = !inside;
  68798. p = p.next;
  68799. } while (p !== a);
  68800. return inside;
  68801. }
  68802. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  68803. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  68804. function splitPolygon(a, b) {
  68805. 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;
  68806. a.next = b;
  68807. b.prev = a;
  68808. a2.next = an;
  68809. an.prev = a2;
  68810. b2.next = a2;
  68811. a2.prev = b2;
  68812. bp.next = b2;
  68813. b2.prev = bp;
  68814. return b2;
  68815. }
  68816. // create a node and optionally link it with previous one (in a circular doubly linked list)
  68817. function insertNode(i, x, y, last) {
  68818. var p = new Node(i, x, y);
  68819. if (!last) {
  68820. p.prev = p;
  68821. p.next = p;
  68822. }
  68823. else {
  68824. p.next = last.next;
  68825. p.prev = last;
  68826. last.next.prev = p;
  68827. last.next = p;
  68828. }
  68829. return p;
  68830. }
  68831. function removeNode(p) {
  68832. p.next.prev = p.prev;
  68833. p.prev.next = p.next;
  68834. if (p.prevZ)
  68835. p.prevZ.nextZ = p.nextZ;
  68836. if (p.nextZ)
  68837. p.nextZ.prevZ = p.prevZ;
  68838. }
  68839. /**
  68840. * return a percentage difference between the polygon area and its triangulation area;
  68841. * used to verify correctness of triangulation
  68842. */
  68843. function deviation(data, holeIndices, dim, triangles) {
  68844. var hasHoles = holeIndices && holeIndices.length;
  68845. var outerLen = hasHoles ? holeIndices[0] * dim : data.length;
  68846. var polygonArea = Math.abs(signedArea(data, 0, outerLen, dim));
  68847. if (hasHoles) {
  68848. for (var i = 0, len = holeIndices.length; i < len; i++) {
  68849. var start = holeIndices[i] * dim;
  68850. var end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  68851. polygonArea -= Math.abs(signedArea(data, start, end, dim));
  68852. }
  68853. }
  68854. var trianglesArea = 0;
  68855. for (i = 0; i < triangles.length; i += 3) {
  68856. var a = triangles[i] * dim;
  68857. var b = triangles[i + 1] * dim;
  68858. var c = triangles[i + 2] * dim;
  68859. trianglesArea += Math.abs((data[a] - data[c]) * (data[b + 1] - data[a + 1]) -
  68860. (data[a] - data[b]) * (data[c + 1] - data[a + 1]));
  68861. }
  68862. return polygonArea === 0 && trianglesArea === 0 ? 0 : Math.abs((trianglesArea - polygonArea) / polygonArea);
  68863. }
  68864. Earcut.deviation = deviation;
  68865. ;
  68866. function signedArea(data, start, end, dim) {
  68867. var sum = 0;
  68868. for (var i = start, j = end - dim; i < end; i += dim) {
  68869. sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
  68870. j = i;
  68871. }
  68872. return sum;
  68873. }
  68874. /**
  68875. * turn a polygon in a multi-dimensional array form (e.g. as in GeoJSON) into a form Earcut accepts
  68876. */
  68877. function flatten(data) {
  68878. var dim = data[0][0].length, result = { vertices: new Array(), holes: new Array(), dimensions: dim }, holeIndex = 0;
  68879. for (var i = 0; i < data.length; i++) {
  68880. for (var j = 0; j < data[i].length; j++) {
  68881. for (var d = 0; d < dim; d++)
  68882. result.vertices.push(data[i][j][d]);
  68883. }
  68884. if (i > 0) {
  68885. holeIndex += data[i - 1].length;
  68886. result.holes.push(holeIndex);
  68887. }
  68888. }
  68889. return result;
  68890. }
  68891. Earcut.flatten = flatten;
  68892. ;
  68893. })(Earcut || (Earcut = {}));
  68894. //# sourceMappingURL=babylon.earcut.js.map
  68895. var BABYLON;
  68896. (function (BABYLON) {
  68897. var IndexedVector2 = /** @class */ (function (_super) {
  68898. __extends(IndexedVector2, _super);
  68899. function IndexedVector2(original, index) {
  68900. var _this = _super.call(this, original.x, original.y) || this;
  68901. _this.index = index;
  68902. return _this;
  68903. }
  68904. return IndexedVector2;
  68905. }(BABYLON.Vector2));
  68906. var PolygonPoints = /** @class */ (function () {
  68907. function PolygonPoints() {
  68908. this.elements = new Array();
  68909. }
  68910. PolygonPoints.prototype.add = function (originalPoints) {
  68911. var _this = this;
  68912. var result = new Array();
  68913. originalPoints.forEach(function (point) {
  68914. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  68915. var newPoint = new IndexedVector2(point, _this.elements.length);
  68916. result.push(newPoint);
  68917. _this.elements.push(newPoint);
  68918. }
  68919. });
  68920. return result;
  68921. };
  68922. PolygonPoints.prototype.computeBounds = function () {
  68923. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  68924. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  68925. this.elements.forEach(function (point) {
  68926. // x
  68927. if (point.x < lmin.x) {
  68928. lmin.x = point.x;
  68929. }
  68930. else if (point.x > lmax.x) {
  68931. lmax.x = point.x;
  68932. }
  68933. // y
  68934. if (point.y < lmin.y) {
  68935. lmin.y = point.y;
  68936. }
  68937. else if (point.y > lmax.y) {
  68938. lmax.y = point.y;
  68939. }
  68940. });
  68941. return {
  68942. min: lmin,
  68943. max: lmax,
  68944. width: lmax.x - lmin.x,
  68945. height: lmax.y - lmin.y
  68946. };
  68947. };
  68948. return PolygonPoints;
  68949. }());
  68950. var Polygon = /** @class */ (function () {
  68951. function Polygon() {
  68952. }
  68953. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  68954. return [
  68955. new BABYLON.Vector2(xmin, ymin),
  68956. new BABYLON.Vector2(xmax, ymin),
  68957. new BABYLON.Vector2(xmax, ymax),
  68958. new BABYLON.Vector2(xmin, ymax)
  68959. ];
  68960. };
  68961. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  68962. if (cx === void 0) { cx = 0; }
  68963. if (cy === void 0) { cy = 0; }
  68964. if (numberOfSides === void 0) { numberOfSides = 32; }
  68965. var result = new Array();
  68966. var angle = 0;
  68967. var increment = (Math.PI * 2) / numberOfSides;
  68968. for (var i = 0; i < numberOfSides; i++) {
  68969. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  68970. angle -= increment;
  68971. }
  68972. return result;
  68973. };
  68974. Polygon.Parse = function (input) {
  68975. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  68976. var i, result = [];
  68977. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  68978. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  68979. }
  68980. return result;
  68981. };
  68982. Polygon.StartingAt = function (x, y) {
  68983. return BABYLON.Path2.StartingAt(x, y);
  68984. };
  68985. return Polygon;
  68986. }());
  68987. BABYLON.Polygon = Polygon;
  68988. var PolygonMeshBuilder = /** @class */ (function () {
  68989. function PolygonMeshBuilder(name, contours, scene) {
  68990. this._points = new PolygonPoints();
  68991. this._outlinepoints = new PolygonPoints();
  68992. this._holes = new Array();
  68993. this._epoints = new Array();
  68994. this._eholes = new Array();
  68995. this._name = name;
  68996. this._scene = scene;
  68997. var points;
  68998. if (contours instanceof BABYLON.Path2) {
  68999. points = contours.getPoints();
  69000. }
  69001. else {
  69002. points = contours;
  69003. }
  69004. this._addToepoint(points);
  69005. this._points.add(points);
  69006. this._outlinepoints.add(points);
  69007. }
  69008. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  69009. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  69010. var p = points_1[_i];
  69011. this._epoints.push(p.x, p.y);
  69012. }
  69013. };
  69014. PolygonMeshBuilder.prototype.addHole = function (hole) {
  69015. this._points.add(hole);
  69016. var holepoints = new PolygonPoints();
  69017. holepoints.add(hole);
  69018. this._holes.push(holepoints);
  69019. this._eholes.push(this._epoints.length / 2);
  69020. this._addToepoint(hole);
  69021. return this;
  69022. };
  69023. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  69024. var _this = this;
  69025. if (updatable === void 0) { updatable = false; }
  69026. if (depth === void 0) { depth = 0; }
  69027. var result = new BABYLON.Mesh(this._name, this._scene);
  69028. var normals = new Array();
  69029. var positions = new Array();
  69030. var uvs = new Array();
  69031. var bounds = this._points.computeBounds();
  69032. this._points.elements.forEach(function (p) {
  69033. normals.push(0, 1.0, 0);
  69034. positions.push(p.x, 0, p.y);
  69035. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  69036. });
  69037. var indices = new Array();
  69038. var res = Earcut.earcut(this._epoints, this._eholes, 2);
  69039. for (var i = 0; i < res.length; i++) {
  69040. indices.push(res[i]);
  69041. }
  69042. if (depth > 0) {
  69043. var positionscount = (positions.length / 3); //get the current pointcount
  69044. this._points.elements.forEach(function (p) {
  69045. normals.push(0, -1.0, 0);
  69046. positions.push(p.x, -depth, p.y);
  69047. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  69048. });
  69049. var totalCount = indices.length;
  69050. for (var i = 0; i < totalCount; i += 3) {
  69051. var i0 = indices[i + 0];
  69052. var i1 = indices[i + 1];
  69053. var i2 = indices[i + 2];
  69054. indices.push(i2 + positionscount);
  69055. indices.push(i1 + positionscount);
  69056. indices.push(i0 + positionscount);
  69057. }
  69058. //Add the sides
  69059. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  69060. this._holes.forEach(function (hole) {
  69061. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  69062. });
  69063. }
  69064. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  69065. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  69066. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  69067. result.setIndices(indices);
  69068. return result;
  69069. };
  69070. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  69071. var StartIndex = positions.length / 3;
  69072. var ulength = 0;
  69073. for (var i = 0; i < points.elements.length; i++) {
  69074. var p = points.elements[i];
  69075. var p1;
  69076. if ((i + 1) > points.elements.length - 1) {
  69077. p1 = points.elements[0];
  69078. }
  69079. else {
  69080. p1 = points.elements[i + 1];
  69081. }
  69082. positions.push(p.x, 0, p.y);
  69083. positions.push(p.x, -depth, p.y);
  69084. positions.push(p1.x, 0, p1.y);
  69085. positions.push(p1.x, -depth, p1.y);
  69086. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  69087. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  69088. var v3 = v2.subtract(v1);
  69089. var v4 = new BABYLON.Vector3(0, 1, 0);
  69090. var vn = BABYLON.Vector3.Cross(v3, v4);
  69091. vn = vn.normalize();
  69092. uvs.push(ulength / bounds.width, 0);
  69093. uvs.push(ulength / bounds.width, 1);
  69094. ulength += v3.length();
  69095. uvs.push((ulength / bounds.width), 0);
  69096. uvs.push((ulength / bounds.width), 1);
  69097. if (!flip) {
  69098. normals.push(-vn.x, -vn.y, -vn.z);
  69099. normals.push(-vn.x, -vn.y, -vn.z);
  69100. normals.push(-vn.x, -vn.y, -vn.z);
  69101. normals.push(-vn.x, -vn.y, -vn.z);
  69102. indices.push(StartIndex);
  69103. indices.push(StartIndex + 1);
  69104. indices.push(StartIndex + 2);
  69105. indices.push(StartIndex + 1);
  69106. indices.push(StartIndex + 3);
  69107. indices.push(StartIndex + 2);
  69108. }
  69109. else {
  69110. normals.push(vn.x, vn.y, vn.z);
  69111. normals.push(vn.x, vn.y, vn.z);
  69112. normals.push(vn.x, vn.y, vn.z);
  69113. normals.push(vn.x, vn.y, vn.z);
  69114. indices.push(StartIndex);
  69115. indices.push(StartIndex + 2);
  69116. indices.push(StartIndex + 1);
  69117. indices.push(StartIndex + 1);
  69118. indices.push(StartIndex + 2);
  69119. indices.push(StartIndex + 3);
  69120. }
  69121. StartIndex += 4;
  69122. }
  69123. ;
  69124. };
  69125. return PolygonMeshBuilder;
  69126. }());
  69127. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  69128. })(BABYLON || (BABYLON = {}));
  69129. //# sourceMappingURL=babylon.polygonMesh.js.map
  69130. var BABYLON;
  69131. (function (BABYLON) {
  69132. // Unique ID when we import meshes from Babylon to CSG
  69133. var currentCSGMeshId = 0;
  69134. // # class Vertex
  69135. // Represents a vertex of a polygon. Use your own vertex class instead of this
  69136. // one to provide additional features like texture coordinates and vertex
  69137. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  69138. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  69139. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  69140. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  69141. // is not used anywhere else.
  69142. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  69143. var Vertex = /** @class */ (function () {
  69144. function Vertex(pos, normal, uv) {
  69145. this.pos = pos;
  69146. this.normal = normal;
  69147. this.uv = uv;
  69148. }
  69149. Vertex.prototype.clone = function () {
  69150. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  69151. };
  69152. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  69153. // orientation of a polygon is flipped.
  69154. Vertex.prototype.flip = function () {
  69155. this.normal = this.normal.scale(-1);
  69156. };
  69157. // Create a new vertex between this vertex and `other` by linearly
  69158. // interpolating all properties using a parameter of `t`. Subclasses should
  69159. // override this to interpolate additional properties.
  69160. Vertex.prototype.interpolate = function (other, t) {
  69161. 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));
  69162. };
  69163. return Vertex;
  69164. }());
  69165. // # class Plane
  69166. // Represents a plane in 3D space.
  69167. var Plane = /** @class */ (function () {
  69168. function Plane(normal, w) {
  69169. this.normal = normal;
  69170. this.w = w;
  69171. }
  69172. Plane.FromPoints = function (a, b, c) {
  69173. var v0 = c.subtract(a);
  69174. var v1 = b.subtract(a);
  69175. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  69176. return null;
  69177. }
  69178. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  69179. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  69180. };
  69181. Plane.prototype.clone = function () {
  69182. return new Plane(this.normal.clone(), this.w);
  69183. };
  69184. Plane.prototype.flip = function () {
  69185. this.normal.scaleInPlace(-1);
  69186. this.w = -this.w;
  69187. };
  69188. // Split `polygon` by this plane if needed, then put the polygon or polygon
  69189. // fragments in the appropriate lists. Coplanar polygons go into either
  69190. // `coplanarFront` or `coplanarBack` depending on their orientation with
  69191. // respect to this plane. Polygons in front or in back of this plane go into
  69192. // either `front` or `back`.
  69193. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  69194. var COPLANAR = 0;
  69195. var FRONT = 1;
  69196. var BACK = 2;
  69197. var SPANNING = 3;
  69198. // Classify each point as well as the entire polygon into one of the above
  69199. // four classes.
  69200. var polygonType = 0;
  69201. var types = [];
  69202. var i;
  69203. var t;
  69204. for (i = 0; i < polygon.vertices.length; i++) {
  69205. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  69206. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  69207. polygonType |= type;
  69208. types.push(type);
  69209. }
  69210. // Put the polygon in the correct list, splitting it when necessary.
  69211. switch (polygonType) {
  69212. case COPLANAR:
  69213. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  69214. break;
  69215. case FRONT:
  69216. front.push(polygon);
  69217. break;
  69218. case BACK:
  69219. back.push(polygon);
  69220. break;
  69221. case SPANNING:
  69222. var f = [], b = [];
  69223. for (i = 0; i < polygon.vertices.length; i++) {
  69224. var j = (i + 1) % polygon.vertices.length;
  69225. var ti = types[i], tj = types[j];
  69226. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  69227. if (ti !== BACK)
  69228. f.push(vi);
  69229. if (ti !== FRONT)
  69230. b.push(ti !== BACK ? vi.clone() : vi);
  69231. if ((ti | tj) === SPANNING) {
  69232. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  69233. var v = vi.interpolate(vj, t);
  69234. f.push(v);
  69235. b.push(v.clone());
  69236. }
  69237. }
  69238. var poly;
  69239. if (f.length >= 3) {
  69240. poly = new Polygon(f, polygon.shared);
  69241. if (poly.plane)
  69242. front.push(poly);
  69243. }
  69244. if (b.length >= 3) {
  69245. poly = new Polygon(b, polygon.shared);
  69246. if (poly.plane)
  69247. back.push(poly);
  69248. }
  69249. break;
  69250. }
  69251. };
  69252. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  69253. // point is on the plane.
  69254. Plane.EPSILON = 1e-5;
  69255. return Plane;
  69256. }());
  69257. // # class Polygon
  69258. // Represents a convex polygon. The vertices used to initialize a polygon must
  69259. // be coplanar and form a convex loop.
  69260. //
  69261. // Each convex polygon has a `shared` property, which is shared between all
  69262. // polygons that are clones of each other or were split from the same polygon.
  69263. // This can be used to define per-polygon properties (such as surface color).
  69264. var Polygon = /** @class */ (function () {
  69265. function Polygon(vertices, shared) {
  69266. this.vertices = vertices;
  69267. this.shared = shared;
  69268. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  69269. }
  69270. Polygon.prototype.clone = function () {
  69271. var vertices = this.vertices.map(function (v) { return v.clone(); });
  69272. return new Polygon(vertices, this.shared);
  69273. };
  69274. Polygon.prototype.flip = function () {
  69275. this.vertices.reverse().map(function (v) { v.flip(); });
  69276. this.plane.flip();
  69277. };
  69278. return Polygon;
  69279. }());
  69280. // # class Node
  69281. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  69282. // by picking a polygon to split along. That polygon (and all other coplanar
  69283. // polygons) are added directly to that node and the other polygons are added to
  69284. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  69285. // no distinction between internal and leaf nodes.
  69286. var Node = /** @class */ (function () {
  69287. function Node(polygons) {
  69288. this.plane = null;
  69289. this.front = null;
  69290. this.back = null;
  69291. this.polygons = new Array();
  69292. if (polygons) {
  69293. this.build(polygons);
  69294. }
  69295. }
  69296. Node.prototype.clone = function () {
  69297. var node = new Node();
  69298. node.plane = this.plane && this.plane.clone();
  69299. node.front = this.front && this.front.clone();
  69300. node.back = this.back && this.back.clone();
  69301. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  69302. return node;
  69303. };
  69304. // Convert solid space to empty space and empty space to solid space.
  69305. Node.prototype.invert = function () {
  69306. for (var i = 0; i < this.polygons.length; i++) {
  69307. this.polygons[i].flip();
  69308. }
  69309. if (this.plane) {
  69310. this.plane.flip();
  69311. }
  69312. if (this.front) {
  69313. this.front.invert();
  69314. }
  69315. if (this.back) {
  69316. this.back.invert();
  69317. }
  69318. var temp = this.front;
  69319. this.front = this.back;
  69320. this.back = temp;
  69321. };
  69322. // Recursively remove all polygons in `polygons` that are inside this BSP
  69323. // tree.
  69324. Node.prototype.clipPolygons = function (polygons) {
  69325. if (!this.plane)
  69326. return polygons.slice();
  69327. var front = new Array(), back = new Array();
  69328. for (var i = 0; i < polygons.length; i++) {
  69329. this.plane.splitPolygon(polygons[i], front, back, front, back);
  69330. }
  69331. if (this.front) {
  69332. front = this.front.clipPolygons(front);
  69333. }
  69334. if (this.back) {
  69335. back = this.back.clipPolygons(back);
  69336. }
  69337. else {
  69338. back = [];
  69339. }
  69340. return front.concat(back);
  69341. };
  69342. // Remove all polygons in this BSP tree that are inside the other BSP tree
  69343. // `bsp`.
  69344. Node.prototype.clipTo = function (bsp) {
  69345. this.polygons = bsp.clipPolygons(this.polygons);
  69346. if (this.front)
  69347. this.front.clipTo(bsp);
  69348. if (this.back)
  69349. this.back.clipTo(bsp);
  69350. };
  69351. // Return a list of all polygons in this BSP tree.
  69352. Node.prototype.allPolygons = function () {
  69353. var polygons = this.polygons.slice();
  69354. if (this.front)
  69355. polygons = polygons.concat(this.front.allPolygons());
  69356. if (this.back)
  69357. polygons = polygons.concat(this.back.allPolygons());
  69358. return polygons;
  69359. };
  69360. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  69361. // new polygons are filtered down to the bottom of the tree and become new
  69362. // nodes there. Each set of polygons is partitioned using the first polygon
  69363. // (no heuristic is used to pick a good split).
  69364. Node.prototype.build = function (polygons) {
  69365. if (!polygons.length)
  69366. return;
  69367. if (!this.plane)
  69368. this.plane = polygons[0].plane.clone();
  69369. var front = new Array(), back = new Array();
  69370. for (var i = 0; i < polygons.length; i++) {
  69371. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  69372. }
  69373. if (front.length) {
  69374. if (!this.front)
  69375. this.front = new Node();
  69376. this.front.build(front);
  69377. }
  69378. if (back.length) {
  69379. if (!this.back)
  69380. this.back = new Node();
  69381. this.back.build(back);
  69382. }
  69383. };
  69384. return Node;
  69385. }());
  69386. var CSG = /** @class */ (function () {
  69387. function CSG() {
  69388. this.polygons = new Array();
  69389. }
  69390. // Convert BABYLON.Mesh to BABYLON.CSG
  69391. CSG.FromMesh = function (mesh) {
  69392. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  69393. var matrix, meshPosition, meshRotation, meshRotationQuaternion = null, meshScaling;
  69394. if (mesh instanceof BABYLON.Mesh) {
  69395. mesh.computeWorldMatrix(true);
  69396. matrix = mesh.getWorldMatrix();
  69397. meshPosition = mesh.position.clone();
  69398. meshRotation = mesh.rotation.clone();
  69399. if (mesh.rotationQuaternion) {
  69400. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  69401. }
  69402. meshScaling = mesh.scaling.clone();
  69403. }
  69404. else {
  69405. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  69406. }
  69407. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  69408. var subMeshes = mesh.subMeshes;
  69409. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  69410. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  69411. vertices = [];
  69412. for (var j = 0; j < 3; j++) {
  69413. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  69414. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  69415. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  69416. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  69417. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  69418. vertex = new Vertex(position, normal, uv);
  69419. vertices.push(vertex);
  69420. }
  69421. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  69422. // To handle the case of degenerated triangle
  69423. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  69424. if (polygon.plane)
  69425. polygons.push(polygon);
  69426. }
  69427. }
  69428. var csg = CSG.FromPolygons(polygons);
  69429. csg.matrix = matrix;
  69430. csg.position = meshPosition;
  69431. csg.rotation = meshRotation;
  69432. csg.scaling = meshScaling;
  69433. csg.rotationQuaternion = meshRotationQuaternion;
  69434. currentCSGMeshId++;
  69435. return csg;
  69436. };
  69437. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  69438. CSG.FromPolygons = function (polygons) {
  69439. var csg = new CSG();
  69440. csg.polygons = polygons;
  69441. return csg;
  69442. };
  69443. CSG.prototype.clone = function () {
  69444. var csg = new CSG();
  69445. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  69446. csg.copyTransformAttributes(this);
  69447. return csg;
  69448. };
  69449. CSG.prototype.union = function (csg) {
  69450. var a = new Node(this.clone().polygons);
  69451. var b = new Node(csg.clone().polygons);
  69452. a.clipTo(b);
  69453. b.clipTo(a);
  69454. b.invert();
  69455. b.clipTo(a);
  69456. b.invert();
  69457. a.build(b.allPolygons());
  69458. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  69459. };
  69460. CSG.prototype.unionInPlace = function (csg) {
  69461. var a = new Node(this.polygons);
  69462. var b = new Node(csg.polygons);
  69463. a.clipTo(b);
  69464. b.clipTo(a);
  69465. b.invert();
  69466. b.clipTo(a);
  69467. b.invert();
  69468. a.build(b.allPolygons());
  69469. this.polygons = a.allPolygons();
  69470. };
  69471. CSG.prototype.subtract = function (csg) {
  69472. var a = new Node(this.clone().polygons);
  69473. var b = new Node(csg.clone().polygons);
  69474. a.invert();
  69475. a.clipTo(b);
  69476. b.clipTo(a);
  69477. b.invert();
  69478. b.clipTo(a);
  69479. b.invert();
  69480. a.build(b.allPolygons());
  69481. a.invert();
  69482. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  69483. };
  69484. CSG.prototype.subtractInPlace = function (csg) {
  69485. var a = new Node(this.polygons);
  69486. var b = new Node(csg.polygons);
  69487. a.invert();
  69488. a.clipTo(b);
  69489. b.clipTo(a);
  69490. b.invert();
  69491. b.clipTo(a);
  69492. b.invert();
  69493. a.build(b.allPolygons());
  69494. a.invert();
  69495. this.polygons = a.allPolygons();
  69496. };
  69497. CSG.prototype.intersect = function (csg) {
  69498. var a = new Node(this.clone().polygons);
  69499. var b = new Node(csg.clone().polygons);
  69500. a.invert();
  69501. b.clipTo(a);
  69502. b.invert();
  69503. a.clipTo(b);
  69504. b.clipTo(a);
  69505. a.build(b.allPolygons());
  69506. a.invert();
  69507. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  69508. };
  69509. CSG.prototype.intersectInPlace = function (csg) {
  69510. var a = new Node(this.polygons);
  69511. var b = new Node(csg.polygons);
  69512. a.invert();
  69513. b.clipTo(a);
  69514. b.invert();
  69515. a.clipTo(b);
  69516. b.clipTo(a);
  69517. a.build(b.allPolygons());
  69518. a.invert();
  69519. this.polygons = a.allPolygons();
  69520. };
  69521. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  69522. // not modified.
  69523. CSG.prototype.inverse = function () {
  69524. var csg = this.clone();
  69525. csg.inverseInPlace();
  69526. return csg;
  69527. };
  69528. CSG.prototype.inverseInPlace = function () {
  69529. this.polygons.map(function (p) { p.flip(); });
  69530. };
  69531. // This is used to keep meshes transformations so they can be restored
  69532. // when we build back a Babylon Mesh
  69533. // NB : All CSG operations are performed in world coordinates
  69534. CSG.prototype.copyTransformAttributes = function (csg) {
  69535. this.matrix = csg.matrix;
  69536. this.position = csg.position;
  69537. this.rotation = csg.rotation;
  69538. this.scaling = csg.scaling;
  69539. this.rotationQuaternion = csg.rotationQuaternion;
  69540. return this;
  69541. };
  69542. // Build Raw mesh from CSG
  69543. // Coordinates here are in world space
  69544. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  69545. var matrix = this.matrix.clone();
  69546. matrix.invert();
  69547. 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;
  69548. if (keepSubMeshes) {
  69549. // Sort Polygons, since subMeshes are indices range
  69550. polygons.sort(function (a, b) {
  69551. if (a.shared.meshId === b.shared.meshId) {
  69552. return a.shared.subMeshId - b.shared.subMeshId;
  69553. }
  69554. else {
  69555. return a.shared.meshId - b.shared.meshId;
  69556. }
  69557. });
  69558. }
  69559. for (var i = 0, il = polygons.length; i < il; i++) {
  69560. polygon = polygons[i];
  69561. // Building SubMeshes
  69562. if (!subMesh_dict[polygon.shared.meshId]) {
  69563. subMesh_dict[polygon.shared.meshId] = {};
  69564. }
  69565. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  69566. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  69567. indexStart: +Infinity,
  69568. indexEnd: -Infinity,
  69569. materialIndex: polygon.shared.materialIndex
  69570. };
  69571. }
  69572. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  69573. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  69574. polygonIndices[0] = 0;
  69575. polygonIndices[1] = j - 1;
  69576. polygonIndices[2] = j;
  69577. for (var k = 0; k < 3; k++) {
  69578. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  69579. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  69580. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  69581. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  69582. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  69583. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  69584. // Check if 2 points can be merged
  69585. if (!(typeof vertex_idx !== 'undefined' &&
  69586. normals[vertex_idx * 3] === localNormal.x &&
  69587. normals[vertex_idx * 3 + 1] === localNormal.y &&
  69588. normals[vertex_idx * 3 + 2] === localNormal.z &&
  69589. uvs[vertex_idx * 2] === uv.x &&
  69590. uvs[vertex_idx * 2 + 1] === uv.y)) {
  69591. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  69592. uvs.push(uv.x, uv.y);
  69593. normals.push(normal.x, normal.y, normal.z);
  69594. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  69595. }
  69596. indices.push(vertex_idx);
  69597. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  69598. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  69599. currentIndex++;
  69600. }
  69601. }
  69602. }
  69603. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  69604. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  69605. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  69606. mesh.setIndices(indices, null);
  69607. if (keepSubMeshes) {
  69608. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  69609. var materialIndexOffset = 0, materialMaxIndex;
  69610. mesh.subMeshes = new Array();
  69611. for (var m in subMesh_dict) {
  69612. materialMaxIndex = -1;
  69613. for (var sm in subMesh_dict[m]) {
  69614. subMesh_obj = subMesh_dict[m][sm];
  69615. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  69616. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  69617. }
  69618. materialIndexOffset += ++materialMaxIndex;
  69619. }
  69620. }
  69621. return mesh;
  69622. };
  69623. // Build Mesh from CSG taking material and transforms into account
  69624. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  69625. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  69626. mesh.material = material;
  69627. mesh.position.copyFrom(this.position);
  69628. mesh.rotation.copyFrom(this.rotation);
  69629. if (this.rotationQuaternion) {
  69630. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  69631. }
  69632. mesh.scaling.copyFrom(this.scaling);
  69633. mesh.computeWorldMatrix(true);
  69634. return mesh;
  69635. };
  69636. return CSG;
  69637. }());
  69638. BABYLON.CSG = CSG;
  69639. })(BABYLON || (BABYLON = {}));
  69640. //# sourceMappingURL=babylon.csg.js.map
  69641. var BABYLON;
  69642. (function (BABYLON) {
  69643. var LensFlare = /** @class */ (function () {
  69644. function LensFlare(size, position, color, imgUrl, system) {
  69645. this.size = size;
  69646. this.position = position;
  69647. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  69648. this.color = color || new BABYLON.Color3(1, 1, 1);
  69649. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  69650. this._system = system;
  69651. system.lensFlares.push(this);
  69652. }
  69653. LensFlare.AddFlare = function (size, position, color, imgUrl, system) {
  69654. return new LensFlare(size, position, color, imgUrl, system);
  69655. };
  69656. LensFlare.prototype.dispose = function () {
  69657. if (this.texture) {
  69658. this.texture.dispose();
  69659. }
  69660. // Remove from scene
  69661. var index = this._system.lensFlares.indexOf(this);
  69662. this._system.lensFlares.splice(index, 1);
  69663. };
  69664. ;
  69665. return LensFlare;
  69666. }());
  69667. BABYLON.LensFlare = LensFlare;
  69668. })(BABYLON || (BABYLON = {}));
  69669. //# sourceMappingURL=babylon.lensFlare.js.map
  69670. var BABYLON;
  69671. (function (BABYLON) {
  69672. var LensFlareSystem = /** @class */ (function () {
  69673. function LensFlareSystem(name, emitter, scene) {
  69674. this.name = name;
  69675. this.lensFlares = new Array();
  69676. this.borderLimit = 300;
  69677. this.viewportBorder = 0;
  69678. this.layerMask = 0x0FFFFFFF;
  69679. this._vertexBuffers = {};
  69680. this._isEnabled = true;
  69681. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  69682. this._emitter = emitter;
  69683. this.id = name;
  69684. scene.lensFlareSystems.push(this);
  69685. this.meshesSelectionPredicate = function (m) { return (scene.activeCamera && m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0)); };
  69686. var engine = scene.getEngine();
  69687. // VBO
  69688. var vertices = [];
  69689. vertices.push(1, 1);
  69690. vertices.push(-1, 1);
  69691. vertices.push(-1, -1);
  69692. vertices.push(1, -1);
  69693. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  69694. // Indices
  69695. var indices = [];
  69696. indices.push(0);
  69697. indices.push(1);
  69698. indices.push(2);
  69699. indices.push(0);
  69700. indices.push(2);
  69701. indices.push(3);
  69702. this._indexBuffer = engine.createIndexBuffer(indices);
  69703. // Effects
  69704. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  69705. }
  69706. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  69707. get: function () {
  69708. return this._isEnabled;
  69709. },
  69710. set: function (value) {
  69711. this._isEnabled = value;
  69712. },
  69713. enumerable: true,
  69714. configurable: true
  69715. });
  69716. LensFlareSystem.prototype.getScene = function () {
  69717. return this._scene;
  69718. };
  69719. LensFlareSystem.prototype.getEmitter = function () {
  69720. return this._emitter;
  69721. };
  69722. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  69723. this._emitter = newEmitter;
  69724. };
  69725. LensFlareSystem.prototype.getEmitterPosition = function () {
  69726. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  69727. };
  69728. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  69729. var position = this.getEmitterPosition();
  69730. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  69731. this._positionX = position.x;
  69732. this._positionY = position.y;
  69733. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  69734. if (this.viewportBorder > 0) {
  69735. globalViewport.x -= this.viewportBorder;
  69736. globalViewport.y -= this.viewportBorder;
  69737. globalViewport.width += this.viewportBorder * 2;
  69738. globalViewport.height += this.viewportBorder * 2;
  69739. position.x += this.viewportBorder;
  69740. position.y += this.viewportBorder;
  69741. this._positionX += this.viewportBorder;
  69742. this._positionY += this.viewportBorder;
  69743. }
  69744. if (position.z > 0) {
  69745. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  69746. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  69747. return true;
  69748. }
  69749. return true;
  69750. }
  69751. return false;
  69752. };
  69753. LensFlareSystem.prototype._isVisible = function () {
  69754. if (!this._isEnabled || !this._scene.activeCamera) {
  69755. return false;
  69756. }
  69757. var emitterPosition = this.getEmitterPosition();
  69758. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  69759. var distance = direction.length();
  69760. direction.normalize();
  69761. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  69762. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  69763. return !pickInfo || !pickInfo.hit || pickInfo.distance > distance;
  69764. };
  69765. LensFlareSystem.prototype.render = function () {
  69766. if (!this._effect.isReady() || !this._scene.activeCamera)
  69767. return false;
  69768. var engine = this._scene.getEngine();
  69769. var viewport = this._scene.activeCamera.viewport;
  69770. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  69771. // Position
  69772. if (!this.computeEffectivePosition(globalViewport)) {
  69773. return false;
  69774. }
  69775. // Visibility
  69776. if (!this._isVisible()) {
  69777. return false;
  69778. }
  69779. // Intensity
  69780. var awayX;
  69781. var awayY;
  69782. if (this._positionX < this.borderLimit + globalViewport.x) {
  69783. awayX = this.borderLimit + globalViewport.x - this._positionX;
  69784. }
  69785. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  69786. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  69787. }
  69788. else {
  69789. awayX = 0;
  69790. }
  69791. if (this._positionY < this.borderLimit + globalViewport.y) {
  69792. awayY = this.borderLimit + globalViewport.y - this._positionY;
  69793. }
  69794. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  69795. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  69796. }
  69797. else {
  69798. awayY = 0;
  69799. }
  69800. var away = (awayX > awayY) ? awayX : awayY;
  69801. away -= this.viewportBorder;
  69802. if (away > this.borderLimit) {
  69803. away = this.borderLimit;
  69804. }
  69805. var intensity = 1.0 - (away / this.borderLimit);
  69806. if (intensity < 0) {
  69807. return false;
  69808. }
  69809. if (intensity > 1.0) {
  69810. intensity = 1.0;
  69811. }
  69812. if (this.viewportBorder > 0) {
  69813. globalViewport.x += this.viewportBorder;
  69814. globalViewport.y += this.viewportBorder;
  69815. globalViewport.width -= this.viewportBorder * 2;
  69816. globalViewport.height -= this.viewportBorder * 2;
  69817. this._positionX -= this.viewportBorder;
  69818. this._positionY -= this.viewportBorder;
  69819. }
  69820. // Position
  69821. var centerX = globalViewport.x + globalViewport.width / 2;
  69822. var centerY = globalViewport.y + globalViewport.height / 2;
  69823. var distX = centerX - this._positionX;
  69824. var distY = centerY - this._positionY;
  69825. // Effects
  69826. engine.enableEffect(this._effect);
  69827. engine.setState(false);
  69828. engine.setDepthBuffer(false);
  69829. // VBOs
  69830. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  69831. // Flares
  69832. for (var index = 0; index < this.lensFlares.length; index++) {
  69833. var flare = this.lensFlares[index];
  69834. engine.setAlphaMode(flare.alphaMode);
  69835. var x = centerX - (distX * flare.position);
  69836. var y = centerY - (distY * flare.position);
  69837. var cw = flare.size;
  69838. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  69839. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  69840. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  69841. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  69842. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  69843. // Texture
  69844. this._effect.setTexture("textureSampler", flare.texture);
  69845. // Color
  69846. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  69847. // Draw order
  69848. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  69849. }
  69850. engine.setDepthBuffer(true);
  69851. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  69852. return true;
  69853. };
  69854. LensFlareSystem.prototype.dispose = function () {
  69855. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  69856. if (vertexBuffer) {
  69857. vertexBuffer.dispose();
  69858. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  69859. }
  69860. if (this._indexBuffer) {
  69861. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  69862. this._indexBuffer = null;
  69863. }
  69864. while (this.lensFlares.length) {
  69865. this.lensFlares[0].dispose();
  69866. }
  69867. // Remove from scene
  69868. var index = this._scene.lensFlareSystems.indexOf(this);
  69869. this._scene.lensFlareSystems.splice(index, 1);
  69870. };
  69871. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  69872. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  69873. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  69874. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  69875. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  69876. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  69877. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  69878. var parsedFlare = parsedLensFlareSystem.flares[index];
  69879. BABYLON.LensFlare.AddFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem);
  69880. }
  69881. return lensFlareSystem;
  69882. };
  69883. LensFlareSystem.prototype.serialize = function () {
  69884. var serializationObject = {};
  69885. serializationObject.id = this.id;
  69886. serializationObject.name = this.name;
  69887. serializationObject.emitterId = this.getEmitter().id;
  69888. serializationObject.borderLimit = this.borderLimit;
  69889. serializationObject.flares = [];
  69890. for (var index = 0; index < this.lensFlares.length; index++) {
  69891. var flare = this.lensFlares[index];
  69892. serializationObject.flares.push({
  69893. size: flare.size,
  69894. position: flare.position,
  69895. color: flare.color.asArray(),
  69896. textureName: BABYLON.Tools.GetFilename(flare.texture ? flare.texture.name : "")
  69897. });
  69898. }
  69899. return serializationObject;
  69900. };
  69901. return LensFlareSystem;
  69902. }());
  69903. BABYLON.LensFlareSystem = LensFlareSystem;
  69904. })(BABYLON || (BABYLON = {}));
  69905. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  69906. var BABYLON;
  69907. (function (BABYLON) {
  69908. /**
  69909. * This is a holder class for the physics joint created by the physics plugin.
  69910. * It holds a set of functions to control the underlying joint.
  69911. */
  69912. var PhysicsJoint = /** @class */ (function () {
  69913. function PhysicsJoint(type, jointData) {
  69914. this.type = type;
  69915. this.jointData = jointData;
  69916. jointData.nativeParams = jointData.nativeParams || {};
  69917. }
  69918. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  69919. get: function () {
  69920. return this._physicsJoint;
  69921. },
  69922. set: function (newJoint) {
  69923. if (this._physicsJoint) {
  69924. //remove from the wolrd
  69925. }
  69926. this._physicsJoint = newJoint;
  69927. },
  69928. enumerable: true,
  69929. configurable: true
  69930. });
  69931. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  69932. set: function (physicsPlugin) {
  69933. this._physicsPlugin = physicsPlugin;
  69934. },
  69935. enumerable: true,
  69936. configurable: true
  69937. });
  69938. /**
  69939. * Execute a function that is physics-plugin specific.
  69940. * @param {Function} func the function that will be executed.
  69941. * It accepts two parameters: the physics world and the physics joint.
  69942. */
  69943. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  69944. func(this._physicsPlugin.world, this._physicsJoint);
  69945. };
  69946. //TODO check if the native joints are the same
  69947. //Joint Types
  69948. PhysicsJoint.DistanceJoint = 0;
  69949. PhysicsJoint.HingeJoint = 1;
  69950. PhysicsJoint.BallAndSocketJoint = 2;
  69951. PhysicsJoint.WheelJoint = 3;
  69952. PhysicsJoint.SliderJoint = 4;
  69953. //OIMO
  69954. PhysicsJoint.PrismaticJoint = 5;
  69955. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  69956. PhysicsJoint.UniversalJoint = 6;
  69957. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  69958. //Cannon
  69959. //Similar to a Ball-Joint. Different in params
  69960. PhysicsJoint.PointToPointJoint = 8;
  69961. //Cannon only at the moment
  69962. PhysicsJoint.SpringJoint = 9;
  69963. PhysicsJoint.LockJoint = 10;
  69964. return PhysicsJoint;
  69965. }());
  69966. BABYLON.PhysicsJoint = PhysicsJoint;
  69967. /**
  69968. * A class representing a physics distance joint.
  69969. */
  69970. var DistanceJoint = /** @class */ (function (_super) {
  69971. __extends(DistanceJoint, _super);
  69972. function DistanceJoint(jointData) {
  69973. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  69974. }
  69975. /**
  69976. * Update the predefined distance.
  69977. */
  69978. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  69979. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  69980. };
  69981. return DistanceJoint;
  69982. }(PhysicsJoint));
  69983. BABYLON.DistanceJoint = DistanceJoint;
  69984. var MotorEnabledJoint = /** @class */ (function (_super) {
  69985. __extends(MotorEnabledJoint, _super);
  69986. function MotorEnabledJoint(type, jointData) {
  69987. return _super.call(this, type, jointData) || this;
  69988. }
  69989. /**
  69990. * Set the motor values.
  69991. * Attention, this function is plugin specific. Engines won't react 100% the same.
  69992. * @param {number} force the force to apply
  69993. * @param {number} maxForce max force for this motor.
  69994. */
  69995. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  69996. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  69997. };
  69998. /**
  69999. * Set the motor's limits.
  70000. * Attention, this function is plugin specific. Engines won't react 100% the same.
  70001. */
  70002. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  70003. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  70004. };
  70005. return MotorEnabledJoint;
  70006. }(PhysicsJoint));
  70007. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  70008. /**
  70009. * This class represents a single hinge physics joint
  70010. */
  70011. var HingeJoint = /** @class */ (function (_super) {
  70012. __extends(HingeJoint, _super);
  70013. function HingeJoint(jointData) {
  70014. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  70015. }
  70016. /**
  70017. * Set the motor values.
  70018. * Attention, this function is plugin specific. Engines won't react 100% the same.
  70019. * @param {number} force the force to apply
  70020. * @param {number} maxForce max force for this motor.
  70021. */
  70022. HingeJoint.prototype.setMotor = function (force, maxForce) {
  70023. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  70024. };
  70025. /**
  70026. * Set the motor's limits.
  70027. * Attention, this function is plugin specific. Engines won't react 100% the same.
  70028. */
  70029. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  70030. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  70031. };
  70032. return HingeJoint;
  70033. }(MotorEnabledJoint));
  70034. BABYLON.HingeJoint = HingeJoint;
  70035. /**
  70036. * This class represents a dual hinge physics joint (same as wheel joint)
  70037. */
  70038. var Hinge2Joint = /** @class */ (function (_super) {
  70039. __extends(Hinge2Joint, _super);
  70040. function Hinge2Joint(jointData) {
  70041. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  70042. }
  70043. /**
  70044. * Set the motor values.
  70045. * Attention, this function is plugin specific. Engines won't react 100% the same.
  70046. * @param {number} force the force to apply
  70047. * @param {number} maxForce max force for this motor.
  70048. * @param {motorIndex} the motor's index, 0 or 1.
  70049. */
  70050. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  70051. if (motorIndex === void 0) { motorIndex = 0; }
  70052. this._physicsPlugin.setMotor(this, force || 0, maxForce, motorIndex);
  70053. };
  70054. /**
  70055. * Set the motor limits.
  70056. * Attention, this function is plugin specific. Engines won't react 100% the same.
  70057. * @param {number} upperLimit the upper limit
  70058. * @param {number} lowerLimit lower limit
  70059. * @param {motorIndex} the motor's index, 0 or 1.
  70060. */
  70061. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  70062. if (motorIndex === void 0) { motorIndex = 0; }
  70063. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  70064. };
  70065. return Hinge2Joint;
  70066. }(MotorEnabledJoint));
  70067. BABYLON.Hinge2Joint = Hinge2Joint;
  70068. })(BABYLON || (BABYLON = {}));
  70069. //# sourceMappingURL=babylon.physicsJoint.js.map
  70070. var BABYLON;
  70071. (function (BABYLON) {
  70072. var PhysicsImpostor = /** @class */ (function () {
  70073. function PhysicsImpostor(object, type, _options, _scene) {
  70074. if (_options === void 0) { _options = { mass: 0 }; }
  70075. var _this = this;
  70076. this.object = object;
  70077. this.type = type;
  70078. this._options = _options;
  70079. this._scene = _scene;
  70080. this._bodyUpdateRequired = false;
  70081. this._onBeforePhysicsStepCallbacks = new Array();
  70082. this._onAfterPhysicsStepCallbacks = new Array();
  70083. this._onPhysicsCollideCallbacks = [];
  70084. this._deltaPosition = BABYLON.Vector3.Zero();
  70085. this._isDisposed = false;
  70086. //temp variables for parent rotation calculations
  70087. //private _mats: Array<Matrix> = [new Matrix(), new Matrix()];
  70088. this._tmpQuat = new BABYLON.Quaternion();
  70089. this._tmpQuat2 = new BABYLON.Quaternion();
  70090. /**
  70091. * this function is executed by the physics engine.
  70092. */
  70093. this.beforeStep = function () {
  70094. if (!_this._physicsEngine) {
  70095. return;
  70096. }
  70097. _this.object.translate(_this._deltaPosition, -1);
  70098. _this._deltaRotationConjugated && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this.object.rotationQuaternion);
  70099. _this.object.computeWorldMatrix(false);
  70100. if (_this.object.parent && _this.object.rotationQuaternion) {
  70101. _this.getParentsRotation();
  70102. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this._tmpQuat);
  70103. }
  70104. else {
  70105. _this._tmpQuat.copyFrom(_this.object.rotationQuaternion || new BABYLON.Quaternion());
  70106. }
  70107. if (!_this._options.disableBidirectionalTransformation) {
  70108. _this.object.rotationQuaternion && _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, /*bInfo.boundingBox.centerWorld*/ _this.object.getAbsolutePivotPoint(), _this._tmpQuat);
  70109. }
  70110. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  70111. func(_this);
  70112. });
  70113. };
  70114. /**
  70115. * this function is executed by the physics engine.
  70116. */
  70117. this.afterStep = function () {
  70118. if (!_this._physicsEngine) {
  70119. return;
  70120. }
  70121. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  70122. func(_this);
  70123. });
  70124. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  70125. // object has now its world rotation. needs to be converted to local.
  70126. if (_this.object.parent && _this.object.rotationQuaternion) {
  70127. _this.getParentsRotation();
  70128. _this._tmpQuat.conjugateInPlace();
  70129. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this.object.rotationQuaternion);
  70130. }
  70131. // take the position set and make it the absolute position of this object.
  70132. _this.object.setAbsolutePosition(_this.object.position);
  70133. _this._deltaRotation && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotation, _this.object.rotationQuaternion);
  70134. _this.object.translate(_this._deltaPosition, 1);
  70135. };
  70136. /**
  70137. * Legacy collision detection event support
  70138. */
  70139. this.onCollideEvent = null;
  70140. //event and body object due to cannon's event-based architecture.
  70141. this.onCollide = function (e) {
  70142. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent) {
  70143. return;
  70144. }
  70145. if (!_this._physicsEngine) {
  70146. return;
  70147. }
  70148. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  70149. if (otherImpostor) {
  70150. // Legacy collision detection event support
  70151. if (_this.onCollideEvent) {
  70152. _this.onCollideEvent(_this, otherImpostor);
  70153. }
  70154. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  70155. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  70156. }).forEach(function (obj) {
  70157. obj.callback(_this, otherImpostor);
  70158. });
  70159. }
  70160. };
  70161. //sanity check!
  70162. if (!this.object) {
  70163. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  70164. return;
  70165. }
  70166. //legacy support for old syntax.
  70167. if (!this._scene && object.getScene) {
  70168. this._scene = object.getScene();
  70169. }
  70170. if (!this._scene) {
  70171. return;
  70172. }
  70173. this._physicsEngine = this._scene.getPhysicsEngine();
  70174. if (!this._physicsEngine) {
  70175. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  70176. }
  70177. else {
  70178. //set the object's quaternion, if not set
  70179. if (!this.object.rotationQuaternion) {
  70180. if (this.object.rotation) {
  70181. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  70182. }
  70183. else {
  70184. this.object.rotationQuaternion = new BABYLON.Quaternion();
  70185. }
  70186. }
  70187. //default options params
  70188. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  70189. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  70190. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  70191. this._joints = [];
  70192. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  70193. if (!this.object.parent || this._options.ignoreParent) {
  70194. this._init();
  70195. }
  70196. else if (this.object.parent.physicsImpostor) {
  70197. BABYLON.Tools.Warn("You must affect impostors to children before affecting impostor to parent.");
  70198. }
  70199. }
  70200. }
  70201. Object.defineProperty(PhysicsImpostor.prototype, "isDisposed", {
  70202. get: function () {
  70203. return this._isDisposed;
  70204. },
  70205. enumerable: true,
  70206. configurable: true
  70207. });
  70208. Object.defineProperty(PhysicsImpostor.prototype, "mass", {
  70209. get: function () {
  70210. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyMass(this) : 0;
  70211. },
  70212. set: function (value) {
  70213. this.setMass(value);
  70214. },
  70215. enumerable: true,
  70216. configurable: true
  70217. });
  70218. Object.defineProperty(PhysicsImpostor.prototype, "friction", {
  70219. get: function () {
  70220. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyFriction(this) : 0;
  70221. },
  70222. set: function (value) {
  70223. if (!this._physicsEngine) {
  70224. return;
  70225. }
  70226. this._physicsEngine.getPhysicsPlugin().setBodyFriction(this, value);
  70227. },
  70228. enumerable: true,
  70229. configurable: true
  70230. });
  70231. Object.defineProperty(PhysicsImpostor.prototype, "restitution", {
  70232. get: function () {
  70233. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this) : 0;
  70234. },
  70235. set: function (value) {
  70236. if (!this._physicsEngine) {
  70237. return;
  70238. }
  70239. this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this, value);
  70240. },
  70241. enumerable: true,
  70242. configurable: true
  70243. });
  70244. /**
  70245. * This function will completly initialize this impostor.
  70246. * It will create a new body - but only if this mesh has no parent.
  70247. * If it has, this impostor will not be used other than to define the impostor
  70248. * of the child mesh.
  70249. */
  70250. PhysicsImpostor.prototype._init = function () {
  70251. if (!this._physicsEngine) {
  70252. return;
  70253. }
  70254. this._physicsEngine.removeImpostor(this);
  70255. this.physicsBody = null;
  70256. this._parent = this._parent || this._getPhysicsParent();
  70257. if (!this._isDisposed && (!this.parent || this._options.ignoreParent)) {
  70258. this._physicsEngine.addImpostor(this);
  70259. }
  70260. };
  70261. PhysicsImpostor.prototype._getPhysicsParent = function () {
  70262. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  70263. var parentMesh = this.object.parent;
  70264. return parentMesh.physicsImpostor;
  70265. }
  70266. return null;
  70267. };
  70268. /**
  70269. * Should a new body be generated.
  70270. */
  70271. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  70272. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  70273. };
  70274. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  70275. this.forceUpdate();
  70276. };
  70277. /**
  70278. * Force a regeneration of this or the parent's impostor's body.
  70279. * Use under cautious - This will remove all joints already implemented.
  70280. */
  70281. PhysicsImpostor.prototype.forceUpdate = function () {
  70282. this._init();
  70283. if (this.parent && !this._options.ignoreParent) {
  70284. this.parent.forceUpdate();
  70285. }
  70286. };
  70287. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  70288. /*public get mesh(): AbstractMesh {
  70289. return this._mesh;
  70290. }*/
  70291. /**
  70292. * Gets the body that holds this impostor. Either its own, or its parent.
  70293. */
  70294. get: function () {
  70295. return (this._parent && !this._options.ignoreParent) ? this._parent.physicsBody : this._physicsBody;
  70296. },
  70297. /**
  70298. * Set the physics body. Used mainly by the physics engine/plugin
  70299. */
  70300. set: function (physicsBody) {
  70301. if (this._physicsBody && this._physicsEngine) {
  70302. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  70303. }
  70304. this._physicsBody = physicsBody;
  70305. this.resetUpdateFlags();
  70306. },
  70307. enumerable: true,
  70308. configurable: true
  70309. });
  70310. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  70311. get: function () {
  70312. return !this._options.ignoreParent && this._parent ? this._parent : null;
  70313. },
  70314. set: function (value) {
  70315. this._parent = value;
  70316. },
  70317. enumerable: true,
  70318. configurable: true
  70319. });
  70320. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  70321. this._bodyUpdateRequired = false;
  70322. };
  70323. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  70324. if (this.object.getBoundingInfo) {
  70325. var q = this.object.rotationQuaternion;
  70326. //reset rotation
  70327. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  70328. //calculate the world matrix with no rotation
  70329. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  70330. var boundingInfo = this.object.getBoundingInfo();
  70331. var size = boundingInfo.boundingBox.extendSizeWorld.scale(2);
  70332. //bring back the rotation
  70333. this.object.rotationQuaternion = q;
  70334. //calculate the world matrix with the new rotation
  70335. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  70336. return size;
  70337. }
  70338. else {
  70339. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  70340. }
  70341. };
  70342. PhysicsImpostor.prototype.getObjectCenter = function () {
  70343. if (this.object.getBoundingInfo) {
  70344. var boundingInfo = this.object.getBoundingInfo();
  70345. return boundingInfo.boundingBox.centerWorld;
  70346. }
  70347. else {
  70348. return this.object.position;
  70349. }
  70350. };
  70351. /**
  70352. * Get a specific parametes from the options parameter.
  70353. */
  70354. PhysicsImpostor.prototype.getParam = function (paramName) {
  70355. return this._options[paramName];
  70356. };
  70357. /**
  70358. * Sets a specific parameter in the options given to the physics plugin
  70359. */
  70360. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  70361. this._options[paramName] = value;
  70362. this._bodyUpdateRequired = true;
  70363. };
  70364. /**
  70365. * Specifically change the body's mass option. Won't recreate the physics body object
  70366. */
  70367. PhysicsImpostor.prototype.setMass = function (mass) {
  70368. if (this.getParam("mass") !== mass) {
  70369. this.setParam("mass", mass);
  70370. }
  70371. if (this._physicsEngine) {
  70372. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  70373. }
  70374. };
  70375. PhysicsImpostor.prototype.getLinearVelocity = function () {
  70376. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this) : BABYLON.Vector3.Zero();
  70377. };
  70378. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  70379. if (this._physicsEngine) {
  70380. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  70381. }
  70382. };
  70383. PhysicsImpostor.prototype.getAngularVelocity = function () {
  70384. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this) : BABYLON.Vector3.Zero();
  70385. };
  70386. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  70387. if (this._physicsEngine) {
  70388. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  70389. }
  70390. };
  70391. /**
  70392. * Execute a function with the physics plugin native code.
  70393. * Provide a function the will have two variables - the world object and the physics body object.
  70394. */
  70395. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  70396. if (this._physicsEngine) {
  70397. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  70398. }
  70399. };
  70400. /**
  70401. * Register a function that will be executed before the physics world is stepping forward.
  70402. */
  70403. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  70404. this._onBeforePhysicsStepCallbacks.push(func);
  70405. };
  70406. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  70407. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  70408. if (index > -1) {
  70409. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  70410. }
  70411. else {
  70412. BABYLON.Tools.Warn("Function to remove was not found");
  70413. }
  70414. };
  70415. /**
  70416. * Register a function that will be executed after the physics step
  70417. */
  70418. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  70419. this._onAfterPhysicsStepCallbacks.push(func);
  70420. };
  70421. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  70422. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  70423. if (index > -1) {
  70424. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  70425. }
  70426. else {
  70427. BABYLON.Tools.Warn("Function to remove was not found");
  70428. }
  70429. };
  70430. /**
  70431. * register a function that will be executed when this impostor collides against a different body.
  70432. */
  70433. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  70434. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  70435. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  70436. };
  70437. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  70438. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  70439. var index = this._onPhysicsCollideCallbacks.indexOf({ callback: func, otherImpostors: collidedAgainstList });
  70440. if (index > -1) {
  70441. this._onPhysicsCollideCallbacks.splice(index, 1);
  70442. }
  70443. else {
  70444. BABYLON.Tools.Warn("Function to remove was not found");
  70445. }
  70446. };
  70447. PhysicsImpostor.prototype.getParentsRotation = function () {
  70448. var parent = this.object.parent;
  70449. this._tmpQuat.copyFromFloats(0, 0, 0, 1);
  70450. while (parent) {
  70451. if (parent.rotationQuaternion) {
  70452. this._tmpQuat2.copyFrom(parent.rotationQuaternion);
  70453. }
  70454. else {
  70455. BABYLON.Quaternion.RotationYawPitchRollToRef(parent.rotation.y, parent.rotation.x, parent.rotation.z, this._tmpQuat2);
  70456. }
  70457. this._tmpQuat.multiplyToRef(this._tmpQuat2, this._tmpQuat);
  70458. parent = parent.parent;
  70459. }
  70460. return this._tmpQuat;
  70461. };
  70462. /**
  70463. * Apply a force
  70464. */
  70465. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  70466. if (this._physicsEngine) {
  70467. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  70468. }
  70469. return this;
  70470. };
  70471. /**
  70472. * Apply an impulse
  70473. */
  70474. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  70475. if (this._physicsEngine) {
  70476. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  70477. }
  70478. return this;
  70479. };
  70480. /**
  70481. * A help function to create a joint.
  70482. */
  70483. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  70484. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  70485. this.addJoint(otherImpostor, joint);
  70486. return this;
  70487. };
  70488. /**
  70489. * Add a joint to this impostor with a different impostor.
  70490. */
  70491. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  70492. this._joints.push({
  70493. otherImpostor: otherImpostor,
  70494. joint: joint
  70495. });
  70496. if (this._physicsEngine) {
  70497. this._physicsEngine.addJoint(this, otherImpostor, joint);
  70498. }
  70499. return this;
  70500. };
  70501. /**
  70502. * Will keep this body still, in a sleep mode.
  70503. */
  70504. PhysicsImpostor.prototype.sleep = function () {
  70505. if (this._physicsEngine) {
  70506. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  70507. }
  70508. return this;
  70509. };
  70510. /**
  70511. * Wake the body up.
  70512. */
  70513. PhysicsImpostor.prototype.wakeUp = function () {
  70514. if (this._physicsEngine) {
  70515. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  70516. }
  70517. return this;
  70518. };
  70519. PhysicsImpostor.prototype.clone = function (newObject) {
  70520. if (!newObject)
  70521. return null;
  70522. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  70523. };
  70524. PhysicsImpostor.prototype.dispose = function () {
  70525. var _this = this;
  70526. //no dispose if no physics engine is available.
  70527. if (!this._physicsEngine) {
  70528. return;
  70529. }
  70530. this._joints.forEach(function (j) {
  70531. if (_this._physicsEngine) {
  70532. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  70533. }
  70534. });
  70535. //dispose the physics body
  70536. this._physicsEngine.removeImpostor(this);
  70537. if (this.parent) {
  70538. this.parent.forceUpdate();
  70539. }
  70540. else {
  70541. /*this._object.getChildMeshes().forEach(function(mesh) {
  70542. if (mesh.physicsImpostor) {
  70543. if (disposeChildren) {
  70544. mesh.physicsImpostor.dispose();
  70545. mesh.physicsImpostor = null;
  70546. }
  70547. }
  70548. })*/
  70549. }
  70550. this._isDisposed = true;
  70551. };
  70552. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  70553. this._deltaPosition.copyFrom(position);
  70554. };
  70555. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  70556. if (!this._deltaRotation) {
  70557. this._deltaRotation = new BABYLON.Quaternion();
  70558. }
  70559. this._deltaRotation.copyFrom(rotation);
  70560. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  70561. };
  70562. PhysicsImpostor.prototype.getBoxSizeToRef = function (result) {
  70563. if (this._physicsEngine) {
  70564. this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this, result);
  70565. }
  70566. return this;
  70567. };
  70568. PhysicsImpostor.prototype.getRadius = function () {
  70569. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getRadius(this) : 0;
  70570. };
  70571. /**
  70572. * Sync a bone with this impostor
  70573. * @param bone The bone to sync to the impostor.
  70574. * @param boneMesh The mesh that the bone is influencing.
  70575. * @param jointPivot The pivot of the joint / bone in local space.
  70576. * @param distToJoint Optional distance from the impostor to the joint.
  70577. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  70578. */
  70579. PhysicsImpostor.prototype.syncBoneWithImpostor = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation) {
  70580. var tempVec = PhysicsImpostor._tmpVecs[0];
  70581. var mesh = this.object;
  70582. if (mesh.rotationQuaternion) {
  70583. if (adjustRotation) {
  70584. var tempQuat = PhysicsImpostor._tmpQuat;
  70585. mesh.rotationQuaternion.multiplyToRef(adjustRotation, tempQuat);
  70586. bone.setRotationQuaternion(tempQuat, BABYLON.Space.WORLD, boneMesh);
  70587. }
  70588. else {
  70589. bone.setRotationQuaternion(mesh.rotationQuaternion, BABYLON.Space.WORLD, boneMesh);
  70590. }
  70591. }
  70592. tempVec.x = 0;
  70593. tempVec.y = 0;
  70594. tempVec.z = 0;
  70595. if (jointPivot) {
  70596. tempVec.x = jointPivot.x;
  70597. tempVec.y = jointPivot.y;
  70598. tempVec.z = jointPivot.z;
  70599. bone.getDirectionToRef(tempVec, boneMesh, tempVec);
  70600. if (distToJoint === undefined || distToJoint === null) {
  70601. distToJoint = jointPivot.length();
  70602. }
  70603. tempVec.x *= distToJoint;
  70604. tempVec.y *= distToJoint;
  70605. tempVec.z *= distToJoint;
  70606. }
  70607. if (bone.getParent()) {
  70608. tempVec.addInPlace(mesh.getAbsolutePosition());
  70609. bone.setAbsolutePosition(tempVec, boneMesh);
  70610. }
  70611. else {
  70612. boneMesh.setAbsolutePosition(mesh.getAbsolutePosition());
  70613. boneMesh.position.x -= tempVec.x;
  70614. boneMesh.position.y -= tempVec.y;
  70615. boneMesh.position.z -= tempVec.z;
  70616. }
  70617. };
  70618. /**
  70619. * Sync impostor to a bone
  70620. * @param bone The bone that the impostor will be synced to.
  70621. * @param boneMesh The mesh that the bone is influencing.
  70622. * @param jointPivot The pivot of the joint / bone in local space.
  70623. * @param distToJoint Optional distance from the impostor to the joint.
  70624. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  70625. * @param boneAxis Optional vector3 axis the bone is aligned with
  70626. */
  70627. PhysicsImpostor.prototype.syncImpostorWithBone = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation, boneAxis) {
  70628. var mesh = this.object;
  70629. if (mesh.rotationQuaternion) {
  70630. if (adjustRotation) {
  70631. var tempQuat = PhysicsImpostor._tmpQuat;
  70632. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, tempQuat);
  70633. tempQuat.multiplyToRef(adjustRotation, mesh.rotationQuaternion);
  70634. }
  70635. else {
  70636. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, mesh.rotationQuaternion);
  70637. }
  70638. }
  70639. var pos = PhysicsImpostor._tmpVecs[0];
  70640. var boneDir = PhysicsImpostor._tmpVecs[1];
  70641. if (!boneAxis) {
  70642. boneAxis = PhysicsImpostor._tmpVecs[2];
  70643. boneAxis.x = 0;
  70644. boneAxis.y = 1;
  70645. boneAxis.z = 0;
  70646. }
  70647. bone.getDirectionToRef(boneAxis, boneMesh, boneDir);
  70648. bone.getAbsolutePositionToRef(boneMesh, pos);
  70649. if ((distToJoint === undefined || distToJoint === null) && jointPivot) {
  70650. distToJoint = jointPivot.length();
  70651. }
  70652. if (distToJoint !== undefined && distToJoint !== null) {
  70653. pos.x += boneDir.x * distToJoint;
  70654. pos.y += boneDir.y * distToJoint;
  70655. pos.z += boneDir.z * distToJoint;
  70656. }
  70657. mesh.setAbsolutePosition(pos);
  70658. };
  70659. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  70660. PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();
  70661. PhysicsImpostor._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  70662. PhysicsImpostor._tmpQuat = BABYLON.Quaternion.Identity();
  70663. //Impostor types
  70664. PhysicsImpostor.NoImpostor = 0;
  70665. PhysicsImpostor.SphereImpostor = 1;
  70666. PhysicsImpostor.BoxImpostor = 2;
  70667. PhysicsImpostor.PlaneImpostor = 3;
  70668. PhysicsImpostor.MeshImpostor = 4;
  70669. PhysicsImpostor.CylinderImpostor = 7;
  70670. PhysicsImpostor.ParticleImpostor = 8;
  70671. PhysicsImpostor.HeightmapImpostor = 9;
  70672. return PhysicsImpostor;
  70673. }());
  70674. BABYLON.PhysicsImpostor = PhysicsImpostor;
  70675. })(BABYLON || (BABYLON = {}));
  70676. //# sourceMappingURL=babylon.physicsImpostor.js.map
  70677. var BABYLON;
  70678. (function (BABYLON) {
  70679. var PhysicsEngine = /** @class */ (function () {
  70680. function PhysicsEngine(gravity, _physicsPlugin) {
  70681. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  70682. this._physicsPlugin = _physicsPlugin;
  70683. //new methods and parameters
  70684. this._impostors = [];
  70685. this._joints = [];
  70686. if (!this._physicsPlugin.isSupported()) {
  70687. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  70688. + "Please make sure it is included.");
  70689. }
  70690. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  70691. this.setGravity(gravity);
  70692. this.setTimeStep();
  70693. }
  70694. PhysicsEngine.prototype.setGravity = function (gravity) {
  70695. this.gravity = gravity;
  70696. this._physicsPlugin.setGravity(this.gravity);
  70697. };
  70698. /**
  70699. * Set the time step of the physics engine.
  70700. * default is 1/60.
  70701. * To slow it down, enter 1/600 for example.
  70702. * To speed it up, 1/30
  70703. * @param {number} newTimeStep the new timestep to apply to this world.
  70704. */
  70705. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  70706. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  70707. this._physicsPlugin.setTimeStep(newTimeStep);
  70708. };
  70709. /**
  70710. * Get the time step of the physics engine.
  70711. */
  70712. PhysicsEngine.prototype.getTimeStep = function () {
  70713. return this._physicsPlugin.getTimeStep();
  70714. };
  70715. PhysicsEngine.prototype.dispose = function () {
  70716. this._impostors.forEach(function (impostor) {
  70717. impostor.dispose();
  70718. });
  70719. this._physicsPlugin.dispose();
  70720. };
  70721. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  70722. return this._physicsPlugin.name;
  70723. };
  70724. /**
  70725. * Adding a new impostor for the impostor tracking.
  70726. * This will be done by the impostor itself.
  70727. * @param {PhysicsImpostor} impostor the impostor to add
  70728. */
  70729. PhysicsEngine.prototype.addImpostor = function (impostor) {
  70730. impostor.uniqueId = this._impostors.push(impostor);
  70731. //if no parent, generate the body
  70732. if (!impostor.parent) {
  70733. this._physicsPlugin.generatePhysicsBody(impostor);
  70734. }
  70735. };
  70736. /**
  70737. * Remove an impostor from the engine.
  70738. * This impostor and its mesh will not longer be updated by the physics engine.
  70739. * @param {PhysicsImpostor} impostor the impostor to remove
  70740. */
  70741. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  70742. var index = this._impostors.indexOf(impostor);
  70743. if (index > -1) {
  70744. var removed = this._impostors.splice(index, 1);
  70745. //Is it needed?
  70746. if (removed.length) {
  70747. //this will also remove it from the world.
  70748. removed[0].physicsBody = null;
  70749. }
  70750. }
  70751. };
  70752. /**
  70753. * Add a joint to the physics engine
  70754. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  70755. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  70756. * @param {PhysicsJoint} the joint that will connect both impostors.
  70757. */
  70758. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  70759. var impostorJoint = {
  70760. mainImpostor: mainImpostor,
  70761. connectedImpostor: connectedImpostor,
  70762. joint: joint
  70763. };
  70764. joint.physicsPlugin = this._physicsPlugin;
  70765. this._joints.push(impostorJoint);
  70766. this._physicsPlugin.generateJoint(impostorJoint);
  70767. };
  70768. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  70769. var matchingJoints = this._joints.filter(function (impostorJoint) {
  70770. return (impostorJoint.connectedImpostor === connectedImpostor
  70771. && impostorJoint.joint === joint
  70772. && impostorJoint.mainImpostor === mainImpostor);
  70773. });
  70774. if (matchingJoints.length) {
  70775. this._physicsPlugin.removeJoint(matchingJoints[0]);
  70776. //TODO remove it from the list as well
  70777. }
  70778. };
  70779. /**
  70780. * Called by the scene. no need to call it.
  70781. */
  70782. PhysicsEngine.prototype._step = function (delta) {
  70783. var _this = this;
  70784. //check if any mesh has no body / requires an update
  70785. this._impostors.forEach(function (impostor) {
  70786. if (impostor.isBodyInitRequired()) {
  70787. _this._physicsPlugin.generatePhysicsBody(impostor);
  70788. }
  70789. });
  70790. if (delta > 0.1) {
  70791. delta = 0.1;
  70792. }
  70793. else if (delta <= 0) {
  70794. delta = 1.0 / 60.0;
  70795. }
  70796. this._physicsPlugin.executeStep(delta, this._impostors);
  70797. };
  70798. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  70799. return this._physicsPlugin;
  70800. };
  70801. PhysicsEngine.prototype.getImpostors = function () {
  70802. return this._impostors;
  70803. };
  70804. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  70805. for (var i = 0; i < this._impostors.length; ++i) {
  70806. if (this._impostors[i].object === object) {
  70807. return this._impostors[i];
  70808. }
  70809. }
  70810. return null;
  70811. };
  70812. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  70813. for (var i = 0; i < this._impostors.length; ++i) {
  70814. if (this._impostors[i].physicsBody === body) {
  70815. return this._impostors[i];
  70816. }
  70817. }
  70818. return null;
  70819. };
  70820. // Statics
  70821. PhysicsEngine.Epsilon = 0.001;
  70822. return PhysicsEngine;
  70823. }());
  70824. BABYLON.PhysicsEngine = PhysicsEngine;
  70825. })(BABYLON || (BABYLON = {}));
  70826. //# sourceMappingURL=babylon.physicsEngine.js.map
  70827. var BABYLON;
  70828. (function (BABYLON) {
  70829. var PhysicsHelper = /** @class */ (function () {
  70830. function PhysicsHelper(scene) {
  70831. this._scene = scene;
  70832. this._physicsEngine = this._scene.getPhysicsEngine();
  70833. if (!this._physicsEngine) {
  70834. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you can use the methods.');
  70835. }
  70836. }
  70837. /**
  70838. * @param {Vector3} origin the origin of the explosion
  70839. * @param {number} radius the explosion radius
  70840. * @param {number} strength the explosion strength
  70841. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  70842. */
  70843. PhysicsHelper.prototype.applyRadialExplosionImpulse = function (origin, radius, strength, falloff) {
  70844. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  70845. if (!this._physicsEngine) {
  70846. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call this method.');
  70847. return null;
  70848. }
  70849. var impostors = this._physicsEngine.getImpostors();
  70850. if (impostors.length === 0) {
  70851. return null;
  70852. }
  70853. var event = new PhysicsRadialExplosionEvent(this._scene);
  70854. impostors.forEach(function (impostor) {
  70855. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  70856. if (!impostorForceAndContactPoint) {
  70857. return;
  70858. }
  70859. impostor.applyImpulse(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  70860. });
  70861. event.dispose(false);
  70862. return event;
  70863. };
  70864. /**
  70865. * @param {Vector3} origin the origin of the explosion
  70866. * @param {number} radius the explosion radius
  70867. * @param {number} strength the explosion strength
  70868. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  70869. */
  70870. PhysicsHelper.prototype.applyRadialExplosionForce = function (origin, radius, strength, falloff) {
  70871. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  70872. if (!this._physicsEngine) {
  70873. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  70874. return null;
  70875. }
  70876. var impostors = this._physicsEngine.getImpostors();
  70877. if (impostors.length === 0) {
  70878. return null;
  70879. }
  70880. var event = new PhysicsRadialExplosionEvent(this._scene);
  70881. impostors.forEach(function (impostor) {
  70882. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  70883. if (!impostorForceAndContactPoint) {
  70884. return;
  70885. }
  70886. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  70887. });
  70888. event.dispose(false);
  70889. return event;
  70890. };
  70891. /**
  70892. * @param {Vector3} origin the origin of the explosion
  70893. * @param {number} radius the explosion radius
  70894. * @param {number} strength the explosion strength
  70895. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  70896. */
  70897. PhysicsHelper.prototype.gravitationalField = function (origin, radius, strength, falloff) {
  70898. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  70899. if (!this._physicsEngine) {
  70900. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  70901. return null;
  70902. }
  70903. var impostors = this._physicsEngine.getImpostors();
  70904. if (impostors.length === 0) {
  70905. return null;
  70906. }
  70907. var event = new PhysicsGravitationalFieldEvent(this, this._scene, origin, radius, strength, falloff);
  70908. event.dispose(false);
  70909. return event;
  70910. };
  70911. /**
  70912. * @param {Vector3} origin the origin of the updraft
  70913. * @param {number} radius the radius of the updraft
  70914. * @param {number} strength the strength of the updraft
  70915. * @param {number} height the height of the updraft
  70916. * @param {PhysicsUpdraftMode} updraftMode possible options: Center & Perpendicular. Defaults to Center
  70917. */
  70918. PhysicsHelper.prototype.updraft = function (origin, radius, strength, height, updraftMode) {
  70919. if (updraftMode === void 0) { updraftMode = PhysicsUpdraftMode.Center; }
  70920. if (!this._physicsEngine) {
  70921. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  70922. return null;
  70923. }
  70924. if (this._physicsEngine.getImpostors().length === 0) {
  70925. return null;
  70926. }
  70927. var event = new PhysicsUpdraftEvent(this._scene, origin, radius, strength, height, updraftMode);
  70928. event.dispose(false);
  70929. return event;
  70930. };
  70931. /**
  70932. * @param {Vector3} origin the of the vortex
  70933. * @param {number} radius the radius of the vortex
  70934. * @param {number} strength the strength of the vortex
  70935. * @param {number} height the height of the vortex
  70936. */
  70937. PhysicsHelper.prototype.vortex = function (origin, radius, strength, height) {
  70938. if (!this._physicsEngine) {
  70939. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  70940. return null;
  70941. }
  70942. if (this._physicsEngine.getImpostors().length === 0) {
  70943. return null;
  70944. }
  70945. var event = new PhysicsVortexEvent(this._scene, origin, radius, strength, height);
  70946. event.dispose(false);
  70947. return event;
  70948. };
  70949. return PhysicsHelper;
  70950. }());
  70951. BABYLON.PhysicsHelper = PhysicsHelper;
  70952. /***** Radial explosion *****/
  70953. var PhysicsRadialExplosionEvent = /** @class */ (function () {
  70954. function PhysicsRadialExplosionEvent(scene) {
  70955. this._sphereOptions = { segments: 32, diameter: 1 }; // TODO: make configurable
  70956. this._rays = [];
  70957. this._dataFetched = false; // check if the data has been fetched. If not, do cleanup
  70958. this._scene = scene;
  70959. }
  70960. /**
  70961. * Returns the data related to the radial explosion event (sphere & rays).
  70962. * @returns {PhysicsRadialExplosionEventData}
  70963. */
  70964. PhysicsRadialExplosionEvent.prototype.getData = function () {
  70965. this._dataFetched = true;
  70966. return {
  70967. sphere: this._sphere,
  70968. rays: this._rays,
  70969. };
  70970. };
  70971. /**
  70972. * Returns the force and contact point of the impostor or false, if the impostor is not affected by the force/impulse.
  70973. * @param impostor
  70974. * @param {Vector3} origin the origin of the explosion
  70975. * @param {number} radius the explosion radius
  70976. * @param {number} strength the explosion strength
  70977. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear
  70978. * @returns {Nullable<PhysicsForceAndContactPoint>}
  70979. */
  70980. PhysicsRadialExplosionEvent.prototype.getImpostorForceAndContactPoint = function (impostor, origin, radius, strength, falloff) {
  70981. if (impostor.mass === 0) {
  70982. return null;
  70983. }
  70984. if (!this._intersectsWithSphere(impostor, origin, radius)) {
  70985. return null;
  70986. }
  70987. if (impostor.object.getClassName() !== 'Mesh') {
  70988. return null;
  70989. }
  70990. var impostorObject = impostor.object;
  70991. var impostorObjectCenter = impostor.getObjectCenter();
  70992. var direction = impostorObjectCenter.subtract(origin);
  70993. var ray = new BABYLON.Ray(origin, direction, radius);
  70994. this._rays.push(ray);
  70995. var hit = ray.intersectsMesh(impostorObject);
  70996. var contactPoint = hit.pickedPoint;
  70997. if (!contactPoint) {
  70998. return null;
  70999. }
  71000. var distanceFromOrigin = BABYLON.Vector3.Distance(origin, contactPoint);
  71001. if (distanceFromOrigin > radius) {
  71002. return null;
  71003. }
  71004. var multiplier = falloff === PhysicsRadialImpulseFalloff.Constant
  71005. ? strength
  71006. : strength * (1 - (distanceFromOrigin / radius));
  71007. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  71008. return { force: force, contactPoint: contactPoint };
  71009. };
  71010. /**
  71011. * Disposes the sphere.
  71012. * @param {bolean} force
  71013. */
  71014. PhysicsRadialExplosionEvent.prototype.dispose = function (force) {
  71015. var _this = this;
  71016. if (force === void 0) { force = true; }
  71017. if (force) {
  71018. this._sphere.dispose();
  71019. }
  71020. else {
  71021. setTimeout(function () {
  71022. if (!_this._dataFetched) {
  71023. _this._sphere.dispose();
  71024. }
  71025. }, 0);
  71026. }
  71027. };
  71028. /*** Helpers ***/
  71029. PhysicsRadialExplosionEvent.prototype._prepareSphere = function () {
  71030. if (!this._sphere) {
  71031. this._sphere = BABYLON.MeshBuilder.CreateSphere("radialExplosionEventSphere", this._sphereOptions, this._scene);
  71032. this._sphere.isVisible = false;
  71033. }
  71034. };
  71035. PhysicsRadialExplosionEvent.prototype._intersectsWithSphere = function (impostor, origin, radius) {
  71036. var impostorObject = impostor.object;
  71037. this._prepareSphere();
  71038. this._sphere.position = origin;
  71039. this._sphere.scaling = new BABYLON.Vector3(radius * 2, radius * 2, radius * 2);
  71040. this._sphere._updateBoundingInfo();
  71041. this._sphere.computeWorldMatrix(true);
  71042. return this._sphere.intersectsMesh(impostorObject, true);
  71043. };
  71044. return PhysicsRadialExplosionEvent;
  71045. }());
  71046. BABYLON.PhysicsRadialExplosionEvent = PhysicsRadialExplosionEvent;
  71047. /***** Gravitational Field *****/
  71048. var PhysicsGravitationalFieldEvent = /** @class */ (function () {
  71049. function PhysicsGravitationalFieldEvent(physicsHelper, scene, origin, radius, strength, falloff) {
  71050. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  71051. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  71052. this._physicsHelper = physicsHelper;
  71053. this._scene = scene;
  71054. this._origin = origin;
  71055. this._radius = radius;
  71056. this._strength = strength;
  71057. this._falloff = falloff;
  71058. this._tickCallback = this._tick.bind(this);
  71059. }
  71060. /**
  71061. * Returns the data related to the gravitational field event (sphere).
  71062. * @returns {PhysicsGravitationalFieldEventData}
  71063. */
  71064. PhysicsGravitationalFieldEvent.prototype.getData = function () {
  71065. this._dataFetched = true;
  71066. return {
  71067. sphere: this._sphere,
  71068. };
  71069. };
  71070. /**
  71071. * Enables the gravitational field.
  71072. */
  71073. PhysicsGravitationalFieldEvent.prototype.enable = function () {
  71074. this._tickCallback.call(this);
  71075. this._scene.registerBeforeRender(this._tickCallback);
  71076. };
  71077. /**
  71078. * Disables the gravitational field.
  71079. */
  71080. PhysicsGravitationalFieldEvent.prototype.disable = function () {
  71081. this._scene.unregisterBeforeRender(this._tickCallback);
  71082. };
  71083. /**
  71084. * Disposes the sphere.
  71085. * @param {bolean} force
  71086. */
  71087. PhysicsGravitationalFieldEvent.prototype.dispose = function (force) {
  71088. var _this = this;
  71089. if (force === void 0) { force = true; }
  71090. if (force) {
  71091. this._sphere.dispose();
  71092. }
  71093. else {
  71094. setTimeout(function () {
  71095. if (!_this._dataFetched) {
  71096. _this._sphere.dispose();
  71097. }
  71098. }, 0);
  71099. }
  71100. };
  71101. PhysicsGravitationalFieldEvent.prototype._tick = function () {
  71102. // Since the params won't change, we fetch the event only once
  71103. if (this._sphere) {
  71104. this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  71105. }
  71106. else {
  71107. var radialExplosionEvent = this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  71108. if (radialExplosionEvent) {
  71109. this._sphere = radialExplosionEvent.getData().sphere.clone('radialExplosionEventSphereClone');
  71110. }
  71111. }
  71112. };
  71113. return PhysicsGravitationalFieldEvent;
  71114. }());
  71115. BABYLON.PhysicsGravitationalFieldEvent = PhysicsGravitationalFieldEvent;
  71116. /***** Updraft *****/
  71117. var PhysicsUpdraftEvent = /** @class */ (function () {
  71118. function PhysicsUpdraftEvent(_scene, _origin, _radius, _strength, _height, _updraftMode) {
  71119. this._scene = _scene;
  71120. this._origin = _origin;
  71121. this._radius = _radius;
  71122. this._strength = _strength;
  71123. this._height = _height;
  71124. this._updraftMode = _updraftMode;
  71125. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  71126. this._originDirection = BABYLON.Vector3.Zero(); // used if the updraftMode is perpendicular
  71127. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  71128. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  71129. this._physicsEngine = this._scene.getPhysicsEngine();
  71130. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  71131. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  71132. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  71133. this._originDirection = this._origin.subtract(this._originTop).normalize();
  71134. }
  71135. this._tickCallback = this._tick.bind(this);
  71136. }
  71137. /**
  71138. * Returns the data related to the updraft event (cylinder).
  71139. * @returns {PhysicsUpdraftEventData}
  71140. */
  71141. PhysicsUpdraftEvent.prototype.getData = function () {
  71142. this._dataFetched = true;
  71143. return {
  71144. cylinder: this._cylinder,
  71145. };
  71146. };
  71147. /**
  71148. * Enables the updraft.
  71149. */
  71150. PhysicsUpdraftEvent.prototype.enable = function () {
  71151. this._tickCallback.call(this);
  71152. this._scene.registerBeforeRender(this._tickCallback);
  71153. };
  71154. /**
  71155. * Disables the cortex.
  71156. */
  71157. PhysicsUpdraftEvent.prototype.disable = function () {
  71158. this._scene.unregisterBeforeRender(this._tickCallback);
  71159. };
  71160. /**
  71161. * Disposes the sphere.
  71162. * @param {bolean} force
  71163. */
  71164. PhysicsUpdraftEvent.prototype.dispose = function (force) {
  71165. var _this = this;
  71166. if (force === void 0) { force = true; }
  71167. if (force) {
  71168. this._cylinder.dispose();
  71169. }
  71170. else {
  71171. setTimeout(function () {
  71172. if (!_this._dataFetched) {
  71173. _this._cylinder.dispose();
  71174. }
  71175. }, 0);
  71176. }
  71177. };
  71178. PhysicsUpdraftEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  71179. if (impostor.mass === 0) {
  71180. return null;
  71181. }
  71182. if (!this._intersectsWithCylinder(impostor)) {
  71183. return null;
  71184. }
  71185. var impostorObjectCenter = impostor.getObjectCenter();
  71186. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  71187. var direction = this._originDirection;
  71188. }
  71189. else {
  71190. var direction = impostorObjectCenter.subtract(this._originTop);
  71191. }
  71192. var multiplier = this._strength * -1;
  71193. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  71194. return { force: force, contactPoint: impostorObjectCenter };
  71195. };
  71196. PhysicsUpdraftEvent.prototype._tick = function () {
  71197. var _this = this;
  71198. this._physicsEngine.getImpostors().forEach(function (impostor) {
  71199. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  71200. if (!impostorForceAndContactPoint) {
  71201. return;
  71202. }
  71203. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  71204. });
  71205. };
  71206. /*** Helpers ***/
  71207. PhysicsUpdraftEvent.prototype._prepareCylinder = function () {
  71208. if (!this._cylinder) {
  71209. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("updraftEventCylinder", {
  71210. height: this._height,
  71211. diameter: this._radius * 2,
  71212. }, this._scene);
  71213. this._cylinder.isVisible = false;
  71214. }
  71215. };
  71216. PhysicsUpdraftEvent.prototype._intersectsWithCylinder = function (impostor) {
  71217. var impostorObject = impostor.object;
  71218. this._prepareCylinder();
  71219. this._cylinder.position = this._cylinderPosition;
  71220. return this._cylinder.intersectsMesh(impostorObject, true);
  71221. };
  71222. return PhysicsUpdraftEvent;
  71223. }());
  71224. BABYLON.PhysicsUpdraftEvent = PhysicsUpdraftEvent;
  71225. /***** Vortex *****/
  71226. var PhysicsVortexEvent = /** @class */ (function () {
  71227. function PhysicsVortexEvent(_scene, _origin, _radius, _strength, _height) {
  71228. this._scene = _scene;
  71229. this._origin = _origin;
  71230. this._radius = _radius;
  71231. this._strength = _strength;
  71232. this._height = _height;
  71233. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  71234. this._centripetalForceThreshold = 0.7; // at which distance, relative to the radius the centripetal forces should kick in
  71235. this._updraftMultiplier = 0.02;
  71236. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  71237. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  71238. this._physicsEngine = this._scene.getPhysicsEngine();
  71239. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  71240. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  71241. this._tickCallback = this._tick.bind(this);
  71242. }
  71243. /**
  71244. * Returns the data related to the vortex event (cylinder).
  71245. * @returns {PhysicsVortexEventData}
  71246. */
  71247. PhysicsVortexEvent.prototype.getData = function () {
  71248. this._dataFetched = true;
  71249. return {
  71250. cylinder: this._cylinder,
  71251. };
  71252. };
  71253. /**
  71254. * Enables the vortex.
  71255. */
  71256. PhysicsVortexEvent.prototype.enable = function () {
  71257. this._tickCallback.call(this);
  71258. this._scene.registerBeforeRender(this._tickCallback);
  71259. };
  71260. /**
  71261. * Disables the cortex.
  71262. */
  71263. PhysicsVortexEvent.prototype.disable = function () {
  71264. this._scene.unregisterBeforeRender(this._tickCallback);
  71265. };
  71266. /**
  71267. * Disposes the sphere.
  71268. * @param {bolean} force
  71269. */
  71270. PhysicsVortexEvent.prototype.dispose = function (force) {
  71271. var _this = this;
  71272. if (force === void 0) { force = true; }
  71273. if (force) {
  71274. this._cylinder.dispose();
  71275. }
  71276. else {
  71277. setTimeout(function () {
  71278. if (!_this._dataFetched) {
  71279. _this._cylinder.dispose();
  71280. }
  71281. }, 0);
  71282. }
  71283. };
  71284. PhysicsVortexEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  71285. if (impostor.mass === 0) {
  71286. return null;
  71287. }
  71288. if (!this._intersectsWithCylinder(impostor)) {
  71289. return null;
  71290. }
  71291. if (impostor.object.getClassName() !== 'Mesh') {
  71292. return null;
  71293. }
  71294. var impostorObject = impostor.object;
  71295. var impostorObjectCenter = impostor.getObjectCenter();
  71296. var originOnPlane = new BABYLON.Vector3(this._origin.x, impostorObjectCenter.y, this._origin.z); // the distance to the origin as if both objects were on a plane (Y-axis)
  71297. var originToImpostorDirection = impostorObjectCenter.subtract(originOnPlane);
  71298. var ray = new BABYLON.Ray(originOnPlane, originToImpostorDirection, this._radius);
  71299. var hit = ray.intersectsMesh(impostorObject);
  71300. var contactPoint = hit.pickedPoint;
  71301. if (!contactPoint) {
  71302. return null;
  71303. }
  71304. var absoluteDistanceFromOrigin = hit.distance / this._radius;
  71305. var perpendicularDirection = BABYLON.Vector3.Cross(originOnPlane, impostorObjectCenter).normalize();
  71306. var directionToOrigin = contactPoint.normalize();
  71307. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  71308. directionToOrigin = directionToOrigin.negate();
  71309. }
  71310. // TODO: find a more physically based solution
  71311. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  71312. var forceX = directionToOrigin.x * this._strength / 8;
  71313. var forceY = directionToOrigin.y * this._updraftMultiplier;
  71314. var forceZ = directionToOrigin.z * this._strength / 8;
  71315. }
  71316. else {
  71317. var forceX = (perpendicularDirection.x + directionToOrigin.x) / 2;
  71318. var forceY = this._originTop.y * this._updraftMultiplier;
  71319. var forceZ = (perpendicularDirection.z + directionToOrigin.z) / 2;
  71320. }
  71321. var force = new BABYLON.Vector3(forceX, forceY, forceZ);
  71322. force = force.multiplyByFloats(this._strength, this._strength, this._strength);
  71323. return { force: force, contactPoint: impostorObjectCenter };
  71324. };
  71325. PhysicsVortexEvent.prototype._tick = function () {
  71326. var _this = this;
  71327. this._physicsEngine.getImpostors().forEach(function (impostor) {
  71328. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  71329. if (!impostorForceAndContactPoint) {
  71330. return;
  71331. }
  71332. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  71333. });
  71334. };
  71335. /*** Helpers ***/
  71336. PhysicsVortexEvent.prototype._prepareCylinder = function () {
  71337. if (!this._cylinder) {
  71338. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("vortexEventCylinder", {
  71339. height: this._height,
  71340. diameter: this._radius * 2,
  71341. }, this._scene);
  71342. this._cylinder.isVisible = false;
  71343. }
  71344. };
  71345. PhysicsVortexEvent.prototype._intersectsWithCylinder = function (impostor) {
  71346. var impostorObject = impostor.object;
  71347. this._prepareCylinder();
  71348. this._cylinder.position = this._cylinderPosition;
  71349. return this._cylinder.intersectsMesh(impostorObject, true);
  71350. };
  71351. return PhysicsVortexEvent;
  71352. }());
  71353. BABYLON.PhysicsVortexEvent = PhysicsVortexEvent;
  71354. /***** Enums *****/
  71355. /**
  71356. * The strenght of the force in correspondence to the distance of the affected object
  71357. */
  71358. var PhysicsRadialImpulseFalloff;
  71359. (function (PhysicsRadialImpulseFalloff) {
  71360. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Constant"] = 0] = "Constant";
  71361. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Linear"] = 1] = "Linear"; // impulse gets weaker if it's further from the origin
  71362. })(PhysicsRadialImpulseFalloff = BABYLON.PhysicsRadialImpulseFalloff || (BABYLON.PhysicsRadialImpulseFalloff = {}));
  71363. /**
  71364. * The strenght of the force in correspondence to the distance of the affected object
  71365. */
  71366. var PhysicsUpdraftMode;
  71367. (function (PhysicsUpdraftMode) {
  71368. PhysicsUpdraftMode[PhysicsUpdraftMode["Center"] = 0] = "Center";
  71369. PhysicsUpdraftMode[PhysicsUpdraftMode["Perpendicular"] = 1] = "Perpendicular"; // once a impostor is inside the cylinder, it will shoot out perpendicular from the ground of the cylinder
  71370. })(PhysicsUpdraftMode = BABYLON.PhysicsUpdraftMode || (BABYLON.PhysicsUpdraftMode = {}));
  71371. })(BABYLON || (BABYLON = {}));
  71372. //# sourceMappingURL=babylon.physicsHelper.js.map
  71373. var BABYLON;
  71374. (function (BABYLON) {
  71375. var CannonJSPlugin = /** @class */ (function () {
  71376. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  71377. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  71378. if (iterations === void 0) { iterations = 10; }
  71379. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  71380. this.name = "CannonJSPlugin";
  71381. this._physicsMaterials = new Array();
  71382. this._fixedTimeStep = 1 / 60;
  71383. //See https://github.com/schteppe/CANNON.js/blob/gh-pages/demos/collisionFilter.html
  71384. this.BJSCANNON = typeof CANNON !== 'undefined' ? CANNON : (typeof require !== 'undefined' ? require('cannon') : undefined);
  71385. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  71386. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  71387. this._tmpPosition = BABYLON.Vector3.Zero();
  71388. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  71389. this._tmpUnityRotation = new BABYLON.Quaternion();
  71390. if (!this.isSupported()) {
  71391. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  71392. return;
  71393. }
  71394. this._extendNamespace();
  71395. this.world = new this.BJSCANNON.World();
  71396. this.world.broadphase = new this.BJSCANNON.NaiveBroadphase();
  71397. this.world.solver.iterations = iterations;
  71398. }
  71399. CannonJSPlugin.prototype.setGravity = function (gravity) {
  71400. this.world.gravity.copy(gravity);
  71401. };
  71402. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  71403. this._fixedTimeStep = timeStep;
  71404. };
  71405. CannonJSPlugin.prototype.getTimeStep = function () {
  71406. return this._fixedTimeStep;
  71407. };
  71408. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  71409. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta : 0, 3);
  71410. };
  71411. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  71412. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  71413. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  71414. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  71415. };
  71416. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  71417. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  71418. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  71419. impostor.physicsBody.applyForce(impulse, worldPoint);
  71420. };
  71421. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  71422. //parent-child relationship. Does this impostor has a parent impostor?
  71423. if (impostor.parent) {
  71424. if (impostor.physicsBody) {
  71425. this.removePhysicsBody(impostor);
  71426. //TODO is that needed?
  71427. impostor.forceUpdate();
  71428. }
  71429. return;
  71430. }
  71431. //should a new body be created for this impostor?
  71432. if (impostor.isBodyInitRequired()) {
  71433. var shape = this._createShape(impostor);
  71434. //unregister events, if body is being changed
  71435. var oldBody = impostor.physicsBody;
  71436. if (oldBody) {
  71437. this.removePhysicsBody(impostor);
  71438. }
  71439. //create the body and material
  71440. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  71441. var bodyCreationObject = {
  71442. mass: impostor.getParam("mass"),
  71443. material: material
  71444. };
  71445. // A simple extend, in case native options were used.
  71446. var nativeOptions = impostor.getParam("nativeOptions");
  71447. for (var key in nativeOptions) {
  71448. if (nativeOptions.hasOwnProperty(key)) {
  71449. bodyCreationObject[key] = nativeOptions[key];
  71450. }
  71451. }
  71452. impostor.physicsBody = new this.BJSCANNON.Body(bodyCreationObject);
  71453. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  71454. this.world.addEventListener("preStep", impostor.beforeStep);
  71455. this.world.addEventListener("postStep", impostor.afterStep);
  71456. impostor.physicsBody.addShape(shape);
  71457. this.world.add(impostor.physicsBody);
  71458. //try to keep the body moving in the right direction by taking old properties.
  71459. //Should be tested!
  71460. if (oldBody) {
  71461. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  71462. impostor.physicsBody[param].copy(oldBody[param]);
  71463. });
  71464. }
  71465. this._processChildMeshes(impostor);
  71466. }
  71467. //now update the body's transformation
  71468. this._updatePhysicsBodyTransformation(impostor);
  71469. };
  71470. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  71471. var _this = this;
  71472. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes(true) : [];
  71473. var currentRotation = mainImpostor.object.rotationQuaternion;
  71474. if (meshChildren.length) {
  71475. var processMesh = function (localPosition, mesh) {
  71476. if (!currentRotation || !mesh.rotationQuaternion) {
  71477. return;
  71478. }
  71479. var childImpostor = mesh.getPhysicsImpostor();
  71480. if (childImpostor) {
  71481. var parent = childImpostor.parent;
  71482. if (parent !== mainImpostor) {
  71483. var pPosition = mesh.getAbsolutePosition().subtract(mainImpostor.object.getAbsolutePosition());
  71484. var localRotation = mesh.rotationQuaternion.multiply(BABYLON.Quaternion.Inverse(currentRotation));
  71485. if (childImpostor.physicsBody) {
  71486. _this.removePhysicsBody(childImpostor);
  71487. childImpostor.physicsBody = null;
  71488. }
  71489. childImpostor.parent = mainImpostor;
  71490. childImpostor.resetUpdateFlags();
  71491. 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));
  71492. //Add the mass of the children.
  71493. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  71494. }
  71495. }
  71496. currentRotation.multiplyInPlace(mesh.rotationQuaternion);
  71497. mesh.getChildMeshes(true).filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(_this, mesh.getAbsolutePosition()));
  71498. };
  71499. meshChildren.filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(this, mainImpostor.object.getAbsolutePosition()));
  71500. }
  71501. };
  71502. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  71503. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  71504. this.world.removeEventListener("preStep", impostor.beforeStep);
  71505. this.world.removeEventListener("postStep", impostor.afterStep);
  71506. this.world.remove(impostor.physicsBody);
  71507. };
  71508. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  71509. var mainBody = impostorJoint.mainImpostor.physicsBody;
  71510. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  71511. if (!mainBody || !connectedBody) {
  71512. return;
  71513. }
  71514. var constraint;
  71515. var jointData = impostorJoint.joint.jointData;
  71516. //TODO - https://github.com/schteppe/this.BJSCANNON.js/blob/gh-pages/demos/collisionFilter.html
  71517. var constraintData = {
  71518. pivotA: jointData.mainPivot ? new this.BJSCANNON.Vec3().copy(jointData.mainPivot) : null,
  71519. pivotB: jointData.connectedPivot ? new this.BJSCANNON.Vec3().copy(jointData.connectedPivot) : null,
  71520. axisA: jointData.mainAxis ? new this.BJSCANNON.Vec3().copy(jointData.mainAxis) : null,
  71521. axisB: jointData.connectedAxis ? new this.BJSCANNON.Vec3().copy(jointData.connectedAxis) : null,
  71522. maxForce: jointData.nativeParams.maxForce,
  71523. collideConnected: !!jointData.collision
  71524. };
  71525. switch (impostorJoint.joint.type) {
  71526. case BABYLON.PhysicsJoint.HingeJoint:
  71527. case BABYLON.PhysicsJoint.Hinge2Joint:
  71528. constraint = new this.BJSCANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  71529. break;
  71530. case BABYLON.PhysicsJoint.DistanceJoint:
  71531. constraint = new this.BJSCANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  71532. break;
  71533. case BABYLON.PhysicsJoint.SpringJoint:
  71534. var springData = jointData;
  71535. constraint = new this.BJSCANNON.Spring(mainBody, connectedBody, {
  71536. restLength: springData.length,
  71537. stiffness: springData.stiffness,
  71538. damping: springData.damping,
  71539. localAnchorA: constraintData.pivotA,
  71540. localAnchorB: constraintData.pivotB
  71541. });
  71542. break;
  71543. case BABYLON.PhysicsJoint.LockJoint:
  71544. constraint = new this.BJSCANNON.LockConstraint(mainBody, connectedBody, constraintData);
  71545. break;
  71546. case BABYLON.PhysicsJoint.PointToPointJoint:
  71547. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  71548. default:
  71549. constraint = new this.BJSCANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  71550. break;
  71551. }
  71552. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  71553. constraint.collideConnected = !!jointData.collision;
  71554. impostorJoint.joint.physicsJoint = constraint;
  71555. //don't add spring as constraint, as it is not one.
  71556. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  71557. this.world.addConstraint(constraint);
  71558. }
  71559. else {
  71560. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  71561. constraint.applyForce();
  71562. });
  71563. }
  71564. };
  71565. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  71566. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  71567. };
  71568. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  71569. var index;
  71570. var mat;
  71571. for (index = 0; index < this._physicsMaterials.length; index++) {
  71572. mat = this._physicsMaterials[index];
  71573. if (mat.friction === friction && mat.restitution === restitution) {
  71574. return mat;
  71575. }
  71576. }
  71577. var currentMat = new this.BJSCANNON.Material(name);
  71578. currentMat.friction = friction;
  71579. currentMat.restitution = restitution;
  71580. this._physicsMaterials.push(currentMat);
  71581. return currentMat;
  71582. };
  71583. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  71584. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  71585. };
  71586. CannonJSPlugin.prototype._createShape = function (impostor) {
  71587. var object = impostor.object;
  71588. var returnValue;
  71589. var extendSize = impostor.getObjectExtendSize();
  71590. switch (impostor.type) {
  71591. case BABYLON.PhysicsImpostor.SphereImpostor:
  71592. var radiusX = extendSize.x;
  71593. var radiusY = extendSize.y;
  71594. var radiusZ = extendSize.z;
  71595. returnValue = new this.BJSCANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  71596. break;
  71597. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  71598. case BABYLON.PhysicsImpostor.CylinderImpostor:
  71599. returnValue = new this.BJSCANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  71600. break;
  71601. case BABYLON.PhysicsImpostor.BoxImpostor:
  71602. var box = extendSize.scale(0.5);
  71603. returnValue = new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  71604. break;
  71605. case BABYLON.PhysicsImpostor.PlaneImpostor:
  71606. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  71607. returnValue = new this.BJSCANNON.Plane();
  71608. break;
  71609. case BABYLON.PhysicsImpostor.MeshImpostor:
  71610. // should transform the vertex data to world coordinates!!
  71611. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  71612. var rawFaces = object.getIndices ? object.getIndices() : [];
  71613. if (!rawVerts)
  71614. return;
  71615. // get only scale! so the object could transform correctly.
  71616. var oldPosition = object.position.clone();
  71617. var oldRotation = object.rotation && object.rotation.clone();
  71618. var oldQuaternion = object.rotationQuaternion && object.rotationQuaternion.clone();
  71619. object.position.copyFromFloats(0, 0, 0);
  71620. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  71621. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  71622. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  71623. var transform = object.computeWorldMatrix(true);
  71624. // convert rawVerts to object space
  71625. var temp = new Array();
  71626. var index;
  71627. for (index = 0; index < rawVerts.length; index += 3) {
  71628. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(rawVerts, index), transform).toArray(temp, index);
  71629. }
  71630. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  71631. returnValue = new this.BJSCANNON.Trimesh(temp, rawFaces);
  71632. //now set back the transformation!
  71633. object.position.copyFrom(oldPosition);
  71634. oldRotation && object.rotation && object.rotation.copyFrom(oldRotation);
  71635. oldQuaternion && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion);
  71636. break;
  71637. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  71638. var oldPosition2 = object.position.clone();
  71639. var oldRotation2 = object.rotation && object.rotation.clone();
  71640. var oldQuaternion2 = object.rotationQuaternion && object.rotationQuaternion.clone();
  71641. object.position.copyFromFloats(0, 0, 0);
  71642. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  71643. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  71644. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  71645. object.rotationQuaternion && object.rotationQuaternion.multiplyInPlace(this._minus90X);
  71646. returnValue = this._createHeightmap(object);
  71647. object.position.copyFrom(oldPosition2);
  71648. oldRotation2 && object.rotation && object.rotation.copyFrom(oldRotation2);
  71649. oldQuaternion2 && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion2);
  71650. object.computeWorldMatrix(true);
  71651. break;
  71652. case BABYLON.PhysicsImpostor.ParticleImpostor:
  71653. returnValue = new this.BJSCANNON.Particle();
  71654. break;
  71655. }
  71656. return returnValue;
  71657. };
  71658. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  71659. var pos = (object.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  71660. var transform = object.computeWorldMatrix(true);
  71661. // convert rawVerts to object space
  71662. var temp = new Array();
  71663. var index;
  71664. for (index = 0; index < pos.length; index += 3) {
  71665. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(pos, index), transform).toArray(temp, index);
  71666. }
  71667. pos = temp;
  71668. var matrix = new Array();
  71669. //For now pointDepth will not be used and will be automatically calculated.
  71670. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  71671. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  71672. var boundingInfo = object.getBoundingInfo();
  71673. var dim = Math.min(boundingInfo.boundingBox.extendSizeWorld.x, boundingInfo.boundingBox.extendSizeWorld.y);
  71674. var minY = boundingInfo.boundingBox.extendSizeWorld.z;
  71675. var elementSize = dim * 2 / arraySize;
  71676. for (var i = 0; i < pos.length; i = i + 3) {
  71677. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  71678. var z = Math.round(((pos[i + 1]) / elementSize - arraySize / 2) * -1);
  71679. var y = -pos[i + 2] + minY;
  71680. if (!matrix[x]) {
  71681. matrix[x] = [];
  71682. }
  71683. if (!matrix[x][z]) {
  71684. matrix[x][z] = y;
  71685. }
  71686. matrix[x][z] = Math.max(y, matrix[x][z]);
  71687. }
  71688. for (var x = 0; x <= arraySize; ++x) {
  71689. if (!matrix[x]) {
  71690. var loc = 1;
  71691. while (!matrix[(x + loc) % arraySize]) {
  71692. loc++;
  71693. }
  71694. matrix[x] = matrix[(x + loc) % arraySize].slice();
  71695. //console.log("missing x", x);
  71696. }
  71697. for (var z = 0; z <= arraySize; ++z) {
  71698. if (!matrix[x][z]) {
  71699. var loc = 1;
  71700. var newValue;
  71701. while (newValue === undefined) {
  71702. newValue = matrix[x][(z + loc++) % arraySize];
  71703. }
  71704. matrix[x][z] = newValue;
  71705. }
  71706. }
  71707. }
  71708. var shape = new this.BJSCANNON.Heightfield(matrix, {
  71709. elementSize: elementSize
  71710. });
  71711. //For future reference, needed for body transformation
  71712. shape.minY = minY;
  71713. return shape;
  71714. };
  71715. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  71716. var object = impostor.object;
  71717. //make sure it is updated...
  71718. object.computeWorldMatrix && object.computeWorldMatrix(true);
  71719. // The delta between the mesh position and the mesh bounding box center
  71720. var bInfo = object.getBoundingInfo();
  71721. if (!bInfo)
  71722. return;
  71723. var center = impostor.getObjectCenter();
  71724. //m.getAbsolutePosition().subtract(m.getBoundingInfo().boundingBox.centerWorld)
  71725. this._tmpDeltaPosition.copyFrom(object.getAbsolutePivotPoint().subtract(center));
  71726. this._tmpDeltaPosition.divideInPlace(impostor.object.scaling);
  71727. this._tmpPosition.copyFrom(center);
  71728. var quaternion = object.rotationQuaternion;
  71729. if (!quaternion) {
  71730. return;
  71731. }
  71732. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  71733. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  71734. //-90 DEG in X, precalculated
  71735. quaternion = quaternion.multiply(this._minus90X);
  71736. //Invert! (Precalculated, 90 deg in X)
  71737. //No need to clone. this will never change.
  71738. impostor.setDeltaRotation(this._plus90X);
  71739. }
  71740. //If it is a heightfield, if should be centered.
  71741. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  71742. var mesh = object;
  71743. var boundingInfo = mesh.getBoundingInfo();
  71744. //calculate the correct body position:
  71745. var rotationQuaternion = mesh.rotationQuaternion;
  71746. mesh.rotationQuaternion = this._tmpUnityRotation;
  71747. mesh.computeWorldMatrix(true);
  71748. //get original center with no rotation
  71749. var c = center.clone();
  71750. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  71751. //calculate the new center using a pivot (since this.BJSCANNON.js doesn't center height maps)
  71752. var p = BABYLON.Matrix.Translation(boundingInfo.boundingBox.extendSizeWorld.x, 0, -boundingInfo.boundingBox.extendSizeWorld.z);
  71753. mesh.setPivotMatrix(p);
  71754. mesh.computeWorldMatrix(true);
  71755. //calculate the translation
  71756. var translation = boundingInfo.boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate();
  71757. this._tmpPosition.copyFromFloats(translation.x, translation.y - boundingInfo.boundingBox.extendSizeWorld.y, translation.z);
  71758. //add it inverted to the delta
  71759. this._tmpDeltaPosition.copyFrom(boundingInfo.boundingBox.centerWorld.subtract(c));
  71760. this._tmpDeltaPosition.y += boundingInfo.boundingBox.extendSizeWorld.y;
  71761. //rotation is back
  71762. mesh.rotationQuaternion = rotationQuaternion;
  71763. mesh.setPivotMatrix(oldPivot);
  71764. mesh.computeWorldMatrix(true);
  71765. }
  71766. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  71767. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  71768. //this._tmpPosition.copyFrom(object.position);
  71769. }
  71770. impostor.setDeltaPosition(this._tmpDeltaPosition);
  71771. //Now update the impostor object
  71772. impostor.physicsBody.position.copy(this._tmpPosition);
  71773. impostor.physicsBody.quaternion.copy(quaternion);
  71774. };
  71775. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  71776. impostor.object.position.copyFrom(impostor.physicsBody.position);
  71777. if (impostor.object.rotationQuaternion) {
  71778. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  71779. }
  71780. };
  71781. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  71782. impostor.physicsBody.position.copy(newPosition);
  71783. impostor.physicsBody.quaternion.copy(newRotation);
  71784. };
  71785. CannonJSPlugin.prototype.isSupported = function () {
  71786. return this.BJSCANNON !== undefined;
  71787. };
  71788. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  71789. impostor.physicsBody.velocity.copy(velocity);
  71790. };
  71791. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  71792. impostor.physicsBody.angularVelocity.copy(velocity);
  71793. };
  71794. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  71795. var v = impostor.physicsBody.velocity;
  71796. if (!v) {
  71797. return null;
  71798. }
  71799. return new BABYLON.Vector3(v.x, v.y, v.z);
  71800. };
  71801. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  71802. var v = impostor.physicsBody.angularVelocity;
  71803. if (!v) {
  71804. return null;
  71805. }
  71806. return new BABYLON.Vector3(v.x, v.y, v.z);
  71807. };
  71808. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  71809. impostor.physicsBody.mass = mass;
  71810. impostor.physicsBody.updateMassProperties();
  71811. };
  71812. CannonJSPlugin.prototype.getBodyMass = function (impostor) {
  71813. return impostor.physicsBody.mass;
  71814. };
  71815. CannonJSPlugin.prototype.getBodyFriction = function (impostor) {
  71816. return impostor.physicsBody.material.friction;
  71817. };
  71818. CannonJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  71819. impostor.physicsBody.material.friction = friction;
  71820. };
  71821. CannonJSPlugin.prototype.getBodyRestitution = function (impostor) {
  71822. return impostor.physicsBody.material.restitution;
  71823. };
  71824. CannonJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  71825. impostor.physicsBody.material.restitution = restitution;
  71826. };
  71827. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  71828. impostor.physicsBody.sleep();
  71829. };
  71830. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  71831. impostor.physicsBody.wakeUp();
  71832. };
  71833. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  71834. joint.physicsJoint.distance = maxDistance;
  71835. };
  71836. // private enableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  71837. // if (!motorIndex) {
  71838. // joint.physicsJoint.enableMotor();
  71839. // }
  71840. // }
  71841. // private disableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  71842. // if (!motorIndex) {
  71843. // joint.physicsJoint.disableMotor();
  71844. // }
  71845. // }
  71846. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  71847. if (!motorIndex) {
  71848. joint.physicsJoint.enableMotor();
  71849. joint.physicsJoint.setMotorSpeed(speed);
  71850. if (maxForce) {
  71851. this.setLimit(joint, maxForce);
  71852. }
  71853. }
  71854. };
  71855. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  71856. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  71857. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  71858. };
  71859. CannonJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  71860. var body = impostor.physicsBody;
  71861. mesh.position.x = body.position.x;
  71862. mesh.position.y = body.position.y;
  71863. mesh.position.z = body.position.z;
  71864. if (mesh.rotationQuaternion) {
  71865. mesh.rotationQuaternion.x = body.quaternion.x;
  71866. mesh.rotationQuaternion.y = body.quaternion.y;
  71867. mesh.rotationQuaternion.z = body.quaternion.z;
  71868. mesh.rotationQuaternion.w = body.quaternion.w;
  71869. }
  71870. };
  71871. CannonJSPlugin.prototype.getRadius = function (impostor) {
  71872. var shape = impostor.physicsBody.shapes[0];
  71873. return shape.boundingSphereRadius;
  71874. };
  71875. CannonJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  71876. var shape = impostor.physicsBody.shapes[0];
  71877. result.x = shape.halfExtents.x * 2;
  71878. result.y = shape.halfExtents.y * 2;
  71879. result.z = shape.halfExtents.z * 2;
  71880. };
  71881. CannonJSPlugin.prototype.dispose = function () {
  71882. };
  71883. CannonJSPlugin.prototype._extendNamespace = function () {
  71884. //this will force cannon to execute at least one step when using interpolation
  71885. var step_tmp1 = new this.BJSCANNON.Vec3();
  71886. var Engine = this.BJSCANNON;
  71887. this.BJSCANNON.World.prototype.step = function (dt, timeSinceLastCalled, maxSubSteps) {
  71888. maxSubSteps = maxSubSteps || 10;
  71889. timeSinceLastCalled = timeSinceLastCalled || 0;
  71890. if (timeSinceLastCalled === 0) {
  71891. this.internalStep(dt);
  71892. this.time += dt;
  71893. }
  71894. else {
  71895. var internalSteps = Math.floor((this.time + timeSinceLastCalled) / dt) - Math.floor(this.time / dt);
  71896. internalSteps = Math.min(internalSteps, maxSubSteps) || 1;
  71897. var t0 = performance.now();
  71898. for (var i = 0; i !== internalSteps; i++) {
  71899. this.internalStep(dt);
  71900. if (performance.now() - t0 > dt * 1000) {
  71901. break;
  71902. }
  71903. }
  71904. this.time += timeSinceLastCalled;
  71905. var h = this.time % dt;
  71906. var h_div_dt = h / dt;
  71907. var interpvelo = step_tmp1;
  71908. var bodies = this.bodies;
  71909. for (var j = 0; j !== bodies.length; j++) {
  71910. var b = bodies[j];
  71911. if (b.type !== Engine.Body.STATIC && b.sleepState !== Engine.Body.SLEEPING) {
  71912. b.position.vsub(b.previousPosition, interpvelo);
  71913. interpvelo.scale(h_div_dt, interpvelo);
  71914. b.position.vadd(interpvelo, b.interpolatedPosition);
  71915. }
  71916. else {
  71917. b.interpolatedPosition.copy(b.position);
  71918. b.interpolatedQuaternion.copy(b.quaternion);
  71919. }
  71920. }
  71921. }
  71922. };
  71923. };
  71924. return CannonJSPlugin;
  71925. }());
  71926. BABYLON.CannonJSPlugin = CannonJSPlugin;
  71927. })(BABYLON || (BABYLON = {}));
  71928. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  71929. var BABYLON;
  71930. (function (BABYLON) {
  71931. var OimoJSPlugin = /** @class */ (function () {
  71932. function OimoJSPlugin(iterations) {
  71933. this.name = "OimoJSPlugin";
  71934. this._tmpImpostorsArray = [];
  71935. this._tmpPositionVector = BABYLON.Vector3.Zero();
  71936. this.BJSOIMO = typeof OIMO !== 'undefined' ? OIMO : (typeof require !== 'undefined' ? require('./Oimo') : undefined);
  71937. this.world = new this.BJSOIMO.World(1 / 60, 2, iterations, true);
  71938. this.world.worldscale(1);
  71939. this.world.clear();
  71940. //making sure no stats are calculated
  71941. this.world.isNoStat = true;
  71942. }
  71943. OimoJSPlugin.prototype.setGravity = function (gravity) {
  71944. this.world.gravity.copy(gravity);
  71945. };
  71946. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  71947. this.world.timeStep = timeStep;
  71948. };
  71949. OimoJSPlugin.prototype.getTimeStep = function () {
  71950. return this.world.timeStep;
  71951. };
  71952. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  71953. var _this = this;
  71954. impostors.forEach(function (impostor) {
  71955. impostor.beforeStep();
  71956. });
  71957. this.world.step();
  71958. impostors.forEach(function (impostor) {
  71959. impostor.afterStep();
  71960. //update the ordered impostors array
  71961. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  71962. });
  71963. //check for collisions
  71964. var contact = this.world.contacts;
  71965. while (contact !== null) {
  71966. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  71967. contact = contact.next;
  71968. continue;
  71969. }
  71970. //is this body colliding with any other? get the impostor
  71971. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  71972. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  71973. if (!mainImpostor || !collidingImpostor) {
  71974. contact = contact.next;
  71975. continue;
  71976. }
  71977. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  71978. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  71979. contact = contact.next;
  71980. }
  71981. };
  71982. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  71983. var mass = impostor.physicsBody.massInfo.mass;
  71984. impostor.physicsBody.applyImpulse(contactPoint.scale(this.BJSOIMO.INV_SCALE), force.scale(this.BJSOIMO.INV_SCALE * mass));
  71985. };
  71986. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  71987. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  71988. this.applyImpulse(impostor, force, contactPoint);
  71989. };
  71990. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  71991. var _this = this;
  71992. //parent-child relationship. Does this impostor has a parent impostor?
  71993. if (impostor.parent) {
  71994. if (impostor.physicsBody) {
  71995. this.removePhysicsBody(impostor);
  71996. //TODO is that needed?
  71997. impostor.forceUpdate();
  71998. }
  71999. return;
  72000. }
  72001. if (impostor.isBodyInitRequired()) {
  72002. var bodyConfig = {
  72003. name: impostor.uniqueId,
  72004. //Oimo must have mass, also for static objects.
  72005. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  72006. size: [],
  72007. type: [],
  72008. pos: [],
  72009. rot: [],
  72010. move: impostor.getParam("mass") !== 0,
  72011. //Supporting older versions of Oimo
  72012. world: this.world
  72013. };
  72014. var impostors = [impostor];
  72015. var addToArray = function (parent) {
  72016. if (!parent.getChildMeshes)
  72017. return;
  72018. parent.getChildMeshes().forEach(function (m) {
  72019. if (m.physicsImpostor) {
  72020. impostors.push(m.physicsImpostor);
  72021. //m.physicsImpostor._init();
  72022. }
  72023. });
  72024. };
  72025. addToArray(impostor.object);
  72026. var checkWithEpsilon_1 = function (value) {
  72027. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  72028. };
  72029. impostors.forEach(function (i) {
  72030. if (!impostor.object.rotationQuaternion) {
  72031. return;
  72032. }
  72033. //get the correct bounding box
  72034. var oldQuaternion = i.object.rotationQuaternion;
  72035. var rot = new _this.BJSOIMO.Euler().setFromQuaternion({
  72036. x: impostor.object.rotationQuaternion.x,
  72037. y: impostor.object.rotationQuaternion.y,
  72038. z: impostor.object.rotationQuaternion.z,
  72039. s: impostor.object.rotationQuaternion.w
  72040. });
  72041. var extendSize = i.getObjectExtendSize();
  72042. if (i === impostor) {
  72043. var center = impostor.getObjectCenter();
  72044. impostor.object.getAbsolutePivotPoint().subtractToRef(center, _this._tmpPositionVector);
  72045. _this._tmpPositionVector.divideInPlace(impostor.object.scaling);
  72046. //Can also use Array.prototype.push.apply
  72047. bodyConfig.pos.push(center.x);
  72048. bodyConfig.pos.push(center.y);
  72049. bodyConfig.pos.push(center.z);
  72050. //tmp solution
  72051. bodyConfig.rot.push(rot.x / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  72052. bodyConfig.rot.push(rot.y / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  72053. bodyConfig.rot.push(rot.z / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  72054. }
  72055. else {
  72056. var localPosition = i.object.getAbsolutePosition().subtract(impostor.object.getAbsolutePosition());
  72057. bodyConfig.pos.push(localPosition.x);
  72058. bodyConfig.pos.push(localPosition.y);
  72059. bodyConfig.pos.push(localPosition.z);
  72060. //tmp solution until https://github.com/lo-th/OIMO.js/pull/37 is merged
  72061. bodyConfig.rot.push(0);
  72062. bodyConfig.rot.push(0);
  72063. bodyConfig.rot.push(0);
  72064. }
  72065. // register mesh
  72066. switch (i.type) {
  72067. case BABYLON.PhysicsImpostor.ParticleImpostor:
  72068. BABYLON.Tools.Warn("No Particle support in this.BJSOIMO.js. using SphereImpostor instead");
  72069. case BABYLON.PhysicsImpostor.SphereImpostor:
  72070. var radiusX = extendSize.x;
  72071. var radiusY = extendSize.y;
  72072. var radiusZ = extendSize.z;
  72073. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  72074. bodyConfig.type.push('sphere');
  72075. //due to the way oimo works with compounds, add 3 times
  72076. bodyConfig.size.push(size);
  72077. bodyConfig.size.push(size);
  72078. bodyConfig.size.push(size);
  72079. break;
  72080. case BABYLON.PhysicsImpostor.CylinderImpostor:
  72081. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  72082. var sizeY = checkWithEpsilon_1(extendSize.y);
  72083. bodyConfig.type.push('cylinder');
  72084. bodyConfig.size.push(sizeX);
  72085. bodyConfig.size.push(sizeY);
  72086. //due to the way oimo works with compounds, add one more value.
  72087. bodyConfig.size.push(sizeY);
  72088. break;
  72089. case BABYLON.PhysicsImpostor.PlaneImpostor:
  72090. case BABYLON.PhysicsImpostor.BoxImpostor:
  72091. default:
  72092. var sizeX = checkWithEpsilon_1(extendSize.x);
  72093. var sizeY = checkWithEpsilon_1(extendSize.y);
  72094. var sizeZ = checkWithEpsilon_1(extendSize.z);
  72095. bodyConfig.type.push('box');
  72096. bodyConfig.size.push(sizeX);
  72097. bodyConfig.size.push(sizeY);
  72098. bodyConfig.size.push(sizeZ);
  72099. break;
  72100. }
  72101. //actually not needed, but hey...
  72102. i.object.rotationQuaternion = oldQuaternion;
  72103. });
  72104. impostor.physicsBody = new this.BJSOIMO.Body(bodyConfig).body; //this.world.add(bodyConfig);
  72105. }
  72106. else {
  72107. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  72108. }
  72109. impostor.setDeltaPosition(this._tmpPositionVector);
  72110. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  72111. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  72112. };
  72113. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  72114. //impostor.physicsBody.dispose();
  72115. //Same as : (older oimo versions)
  72116. this.world.removeRigidBody(impostor.physicsBody);
  72117. };
  72118. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  72119. var mainBody = impostorJoint.mainImpostor.physicsBody;
  72120. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  72121. if (!mainBody || !connectedBody) {
  72122. return;
  72123. }
  72124. var jointData = impostorJoint.joint.jointData;
  72125. var options = jointData.nativeParams || {};
  72126. var type;
  72127. var nativeJointData = {
  72128. body1: mainBody,
  72129. body2: connectedBody,
  72130. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  72131. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  72132. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  72133. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  72134. min: options.min,
  72135. max: options.max,
  72136. collision: options.collision || jointData.collision,
  72137. spring: options.spring,
  72138. //supporting older version of Oimo
  72139. world: this.world
  72140. };
  72141. switch (impostorJoint.joint.type) {
  72142. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  72143. type = "jointBall";
  72144. break;
  72145. case BABYLON.PhysicsJoint.SpringJoint:
  72146. BABYLON.Tools.Warn("this.BJSOIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  72147. var springData = jointData;
  72148. nativeJointData.min = springData.length || nativeJointData.min;
  72149. //Max should also be set, just make sure it is at least min
  72150. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  72151. case BABYLON.PhysicsJoint.DistanceJoint:
  72152. type = "jointDistance";
  72153. nativeJointData.max = jointData.maxDistance;
  72154. break;
  72155. case BABYLON.PhysicsJoint.PrismaticJoint:
  72156. type = "jointPrisme";
  72157. break;
  72158. case BABYLON.PhysicsJoint.SliderJoint:
  72159. type = "jointSlide";
  72160. break;
  72161. case BABYLON.PhysicsJoint.WheelJoint:
  72162. type = "jointWheel";
  72163. break;
  72164. case BABYLON.PhysicsJoint.HingeJoint:
  72165. default:
  72166. type = "jointHinge";
  72167. break;
  72168. }
  72169. nativeJointData.type = type;
  72170. impostorJoint.joint.physicsJoint = new this.BJSOIMO.Link(nativeJointData).joint; //this.world.add(nativeJointData);
  72171. };
  72172. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  72173. //Bug in Oimo prevents us from disposing a joint in the playground
  72174. //joint.joint.physicsJoint.dispose();
  72175. //So we will bruteforce it!
  72176. try {
  72177. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  72178. }
  72179. catch (e) {
  72180. BABYLON.Tools.Warn(e);
  72181. }
  72182. };
  72183. OimoJSPlugin.prototype.isSupported = function () {
  72184. return this.BJSOIMO !== undefined;
  72185. };
  72186. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  72187. if (!impostor.physicsBody.sleeping) {
  72188. //TODO check that
  72189. if (impostor.physicsBody.shapes.next) {
  72190. var parentShape = this._getLastShape(impostor.physicsBody);
  72191. impostor.object.position.x = parentShape.position.x * this.BJSOIMO.WORLD_SCALE;
  72192. impostor.object.position.y = parentShape.position.y * this.BJSOIMO.WORLD_SCALE;
  72193. impostor.object.position.z = parentShape.position.z * this.BJSOIMO.WORLD_SCALE;
  72194. }
  72195. else {
  72196. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  72197. }
  72198. if (impostor.object.rotationQuaternion) {
  72199. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  72200. impostor.object.rotationQuaternion.normalize();
  72201. }
  72202. }
  72203. };
  72204. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  72205. var body = impostor.physicsBody;
  72206. body.position.init(newPosition.x * this.BJSOIMO.INV_SCALE, newPosition.y * this.BJSOIMO.INV_SCALE, newPosition.z * this.BJSOIMO.INV_SCALE);
  72207. body.orientation.init(newRotation.w, newRotation.x, newRotation.y, newRotation.z);
  72208. body.syncShapes();
  72209. body.awake();
  72210. };
  72211. OimoJSPlugin.prototype._getLastShape = function (body) {
  72212. var lastShape = body.shapes;
  72213. while (lastShape.next) {
  72214. lastShape = lastShape.next;
  72215. }
  72216. return lastShape;
  72217. };
  72218. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  72219. impostor.physicsBody.linearVelocity.init(velocity.x, velocity.y, velocity.z);
  72220. };
  72221. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  72222. impostor.physicsBody.angularVelocity.init(velocity.x, velocity.y, velocity.z);
  72223. };
  72224. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  72225. var v = impostor.physicsBody.linearVelocity;
  72226. if (!v) {
  72227. return null;
  72228. }
  72229. return new BABYLON.Vector3(v.x, v.y, v.z);
  72230. };
  72231. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  72232. var v = impostor.physicsBody.angularVelocity;
  72233. if (!v) {
  72234. return null;
  72235. }
  72236. return new BABYLON.Vector3(v.x, v.y, v.z);
  72237. };
  72238. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  72239. var staticBody = mass === 0;
  72240. //this will actually set the body's density and not its mass.
  72241. //But this is how oimo treats the mass variable.
  72242. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  72243. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  72244. };
  72245. OimoJSPlugin.prototype.getBodyMass = function (impostor) {
  72246. return impostor.physicsBody.shapes.density;
  72247. };
  72248. OimoJSPlugin.prototype.getBodyFriction = function (impostor) {
  72249. return impostor.physicsBody.shapes.friction;
  72250. };
  72251. OimoJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  72252. impostor.physicsBody.shapes.friction = friction;
  72253. };
  72254. OimoJSPlugin.prototype.getBodyRestitution = function (impostor) {
  72255. return impostor.physicsBody.shapes.restitution;
  72256. };
  72257. OimoJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  72258. impostor.physicsBody.shapes.restitution = restitution;
  72259. };
  72260. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  72261. impostor.physicsBody.sleep();
  72262. };
  72263. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  72264. impostor.physicsBody.awake();
  72265. };
  72266. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  72267. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  72268. if (minDistance !== void 0) {
  72269. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  72270. }
  72271. };
  72272. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  72273. //TODO separate rotational and transational motors.
  72274. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  72275. if (motor) {
  72276. motor.setMotor(speed, maxForce);
  72277. }
  72278. };
  72279. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  72280. //TODO separate rotational and transational motors.
  72281. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  72282. if (motor) {
  72283. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  72284. }
  72285. };
  72286. OimoJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  72287. var body = impostor.physicsBody;
  72288. mesh.position.x = body.position.x;
  72289. mesh.position.y = body.position.y;
  72290. mesh.position.z = body.position.z;
  72291. if (mesh.rotationQuaternion) {
  72292. mesh.rotationQuaternion.x = body.orientation.x;
  72293. mesh.rotationQuaternion.y = body.orientation.y;
  72294. mesh.rotationQuaternion.z = body.orientation.z;
  72295. mesh.rotationQuaternion.w = body.orientation.s;
  72296. }
  72297. };
  72298. OimoJSPlugin.prototype.getRadius = function (impostor) {
  72299. return impostor.physicsBody.shapes.radius;
  72300. };
  72301. OimoJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  72302. var shape = impostor.physicsBody.shapes;
  72303. result.x = shape.halfWidth * 2;
  72304. result.y = shape.halfHeight * 2;
  72305. result.z = shape.halfDepth * 2;
  72306. };
  72307. OimoJSPlugin.prototype.dispose = function () {
  72308. this.world.clear();
  72309. };
  72310. return OimoJSPlugin;
  72311. }());
  72312. BABYLON.OimoJSPlugin = OimoJSPlugin;
  72313. })(BABYLON || (BABYLON = {}));
  72314. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  72315. var BABYLON;
  72316. (function (BABYLON) {
  72317. /*
  72318. * Based on jsTGALoader - Javascript loader for TGA file
  72319. * By Vincent Thibault
  72320. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  72321. */
  72322. var TGATools = /** @class */ (function () {
  72323. function TGATools() {
  72324. }
  72325. TGATools.GetTGAHeader = function (data) {
  72326. var offset = 0;
  72327. var header = {
  72328. id_length: data[offset++],
  72329. colormap_type: data[offset++],
  72330. image_type: data[offset++],
  72331. colormap_index: data[offset++] | data[offset++] << 8,
  72332. colormap_length: data[offset++] | data[offset++] << 8,
  72333. colormap_size: data[offset++],
  72334. origin: [
  72335. data[offset++] | data[offset++] << 8,
  72336. data[offset++] | data[offset++] << 8
  72337. ],
  72338. width: data[offset++] | data[offset++] << 8,
  72339. height: data[offset++] | data[offset++] << 8,
  72340. pixel_size: data[offset++],
  72341. flags: data[offset++]
  72342. };
  72343. return header;
  72344. };
  72345. TGATools.UploadContent = function (gl, data) {
  72346. // Not enough data to contain header ?
  72347. if (data.length < 19) {
  72348. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  72349. return;
  72350. }
  72351. // Read Header
  72352. var offset = 18;
  72353. var header = TGATools.GetTGAHeader(data);
  72354. // Assume it's a valid Targa file.
  72355. if (header.id_length + offset > data.length) {
  72356. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  72357. return;
  72358. }
  72359. // Skip not needed data
  72360. offset += header.id_length;
  72361. var use_rle = false;
  72362. var use_pal = false;
  72363. var use_grey = false;
  72364. // Get some informations.
  72365. switch (header.image_type) {
  72366. case TGATools._TYPE_RLE_INDEXED:
  72367. use_rle = true;
  72368. case TGATools._TYPE_INDEXED:
  72369. use_pal = true;
  72370. break;
  72371. case TGATools._TYPE_RLE_RGB:
  72372. use_rle = true;
  72373. case TGATools._TYPE_RGB:
  72374. // use_rgb = true;
  72375. break;
  72376. case TGATools._TYPE_RLE_GREY:
  72377. use_rle = true;
  72378. case TGATools._TYPE_GREY:
  72379. use_grey = true;
  72380. break;
  72381. }
  72382. var pixel_data;
  72383. // var numAlphaBits = header.flags & 0xf;
  72384. var pixel_size = header.pixel_size >> 3;
  72385. var pixel_total = header.width * header.height * pixel_size;
  72386. // Read palettes
  72387. var palettes;
  72388. if (use_pal) {
  72389. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  72390. }
  72391. // Read LRE
  72392. if (use_rle) {
  72393. pixel_data = new Uint8Array(pixel_total);
  72394. var c, count, i;
  72395. var localOffset = 0;
  72396. var pixels = new Uint8Array(pixel_size);
  72397. while (offset < pixel_total && localOffset < pixel_total) {
  72398. c = data[offset++];
  72399. count = (c & 0x7f) + 1;
  72400. // RLE pixels
  72401. if (c & 0x80) {
  72402. // Bind pixel tmp array
  72403. for (i = 0; i < pixel_size; ++i) {
  72404. pixels[i] = data[offset++];
  72405. }
  72406. // Copy pixel array
  72407. for (i = 0; i < count; ++i) {
  72408. pixel_data.set(pixels, localOffset + i * pixel_size);
  72409. }
  72410. localOffset += pixel_size * count;
  72411. }
  72412. else {
  72413. count *= pixel_size;
  72414. for (i = 0; i < count; ++i) {
  72415. pixel_data[localOffset + i] = data[offset++];
  72416. }
  72417. localOffset += count;
  72418. }
  72419. }
  72420. }
  72421. else {
  72422. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  72423. }
  72424. // Load to texture
  72425. var x_start, y_start, x_step, y_step, y_end, x_end;
  72426. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  72427. default:
  72428. case TGATools._ORIGIN_UL:
  72429. x_start = 0;
  72430. x_step = 1;
  72431. x_end = header.width;
  72432. y_start = 0;
  72433. y_step = 1;
  72434. y_end = header.height;
  72435. break;
  72436. case TGATools._ORIGIN_BL:
  72437. x_start = 0;
  72438. x_step = 1;
  72439. x_end = header.width;
  72440. y_start = header.height - 1;
  72441. y_step = -1;
  72442. y_end = -1;
  72443. break;
  72444. case TGATools._ORIGIN_UR:
  72445. x_start = header.width - 1;
  72446. x_step = -1;
  72447. x_end = -1;
  72448. y_start = 0;
  72449. y_step = 1;
  72450. y_end = header.height;
  72451. break;
  72452. case TGATools._ORIGIN_BR:
  72453. x_start = header.width - 1;
  72454. x_step = -1;
  72455. x_end = -1;
  72456. y_start = header.height - 1;
  72457. y_step = -1;
  72458. y_end = -1;
  72459. break;
  72460. }
  72461. // Load the specify method
  72462. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  72463. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  72464. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  72465. };
  72466. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  72467. var image = pixel_data, colormap = palettes;
  72468. var width = header.width, height = header.height;
  72469. var color, i = 0, x, y;
  72470. var imageData = new Uint8Array(width * height * 4);
  72471. for (y = y_start; y !== y_end; y += y_step) {
  72472. for (x = x_start; x !== x_end; x += x_step, i++) {
  72473. color = image[i];
  72474. imageData[(x + width * y) * 4 + 3] = 255;
  72475. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  72476. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  72477. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  72478. }
  72479. }
  72480. return imageData;
  72481. };
  72482. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  72483. var image = pixel_data;
  72484. var width = header.width, height = header.height;
  72485. var color, i = 0, x, y;
  72486. var imageData = new Uint8Array(width * height * 4);
  72487. for (y = y_start; y !== y_end; y += y_step) {
  72488. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  72489. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  72490. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  72491. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  72492. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  72493. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  72494. }
  72495. }
  72496. return imageData;
  72497. };
  72498. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  72499. var image = pixel_data;
  72500. var width = header.width, height = header.height;
  72501. var i = 0, x, y;
  72502. var imageData = new Uint8Array(width * height * 4);
  72503. for (y = y_start; y !== y_end; y += y_step) {
  72504. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  72505. imageData[(x + width * y) * 4 + 3] = 255;
  72506. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  72507. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  72508. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  72509. }
  72510. }
  72511. return imageData;
  72512. };
  72513. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  72514. var image = pixel_data;
  72515. var width = header.width, height = header.height;
  72516. var i = 0, x, y;
  72517. var imageData = new Uint8Array(width * height * 4);
  72518. for (y = y_start; y !== y_end; y += y_step) {
  72519. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  72520. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  72521. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  72522. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  72523. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  72524. }
  72525. }
  72526. return imageData;
  72527. };
  72528. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  72529. var image = pixel_data;
  72530. var width = header.width, height = header.height;
  72531. var color, i = 0, x, y;
  72532. var imageData = new Uint8Array(width * height * 4);
  72533. for (y = y_start; y !== y_end; y += y_step) {
  72534. for (x = x_start; x !== x_end; x += x_step, i++) {
  72535. color = image[i];
  72536. imageData[(x + width * y) * 4 + 0] = color;
  72537. imageData[(x + width * y) * 4 + 1] = color;
  72538. imageData[(x + width * y) * 4 + 2] = color;
  72539. imageData[(x + width * y) * 4 + 3] = 255;
  72540. }
  72541. }
  72542. return imageData;
  72543. };
  72544. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  72545. var image = pixel_data;
  72546. var width = header.width, height = header.height;
  72547. var i = 0, x, y;
  72548. var imageData = new Uint8Array(width * height * 4);
  72549. for (y = y_start; y !== y_end; y += y_step) {
  72550. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  72551. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  72552. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  72553. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  72554. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  72555. }
  72556. }
  72557. return imageData;
  72558. };
  72559. //private static _TYPE_NO_DATA = 0;
  72560. TGATools._TYPE_INDEXED = 1;
  72561. TGATools._TYPE_RGB = 2;
  72562. TGATools._TYPE_GREY = 3;
  72563. TGATools._TYPE_RLE_INDEXED = 9;
  72564. TGATools._TYPE_RLE_RGB = 10;
  72565. TGATools._TYPE_RLE_GREY = 11;
  72566. TGATools._ORIGIN_MASK = 0x30;
  72567. TGATools._ORIGIN_SHIFT = 0x04;
  72568. TGATools._ORIGIN_BL = 0x00;
  72569. TGATools._ORIGIN_BR = 0x01;
  72570. TGATools._ORIGIN_UL = 0x02;
  72571. TGATools._ORIGIN_UR = 0x03;
  72572. return TGATools;
  72573. }());
  72574. BABYLON.TGATools = TGATools;
  72575. })(BABYLON || (BABYLON = {}));
  72576. //# sourceMappingURL=babylon.tga.js.map
  72577. var BABYLON;
  72578. (function (BABYLON) {
  72579. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  72580. // All values and structures referenced from:
  72581. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  72582. var DDS_MAGIC = 0x20534444;
  72583. var
  72584. //DDSD_CAPS = 0x1,
  72585. //DDSD_HEIGHT = 0x2,
  72586. //DDSD_WIDTH = 0x4,
  72587. //DDSD_PITCH = 0x8,
  72588. //DDSD_PIXELFORMAT = 0x1000,
  72589. DDSD_MIPMAPCOUNT = 0x20000;
  72590. //DDSD_LINEARSIZE = 0x80000,
  72591. //DDSD_DEPTH = 0x800000;
  72592. // var DDSCAPS_COMPLEX = 0x8,
  72593. // DDSCAPS_MIPMAP = 0x400000,
  72594. // DDSCAPS_TEXTURE = 0x1000;
  72595. var DDSCAPS2_CUBEMAP = 0x200;
  72596. // DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  72597. // DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  72598. // DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  72599. // DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  72600. // DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  72601. // DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  72602. // DDSCAPS2_VOLUME = 0x200000;
  72603. var
  72604. //DDPF_ALPHAPIXELS = 0x1,
  72605. //DDPF_ALPHA = 0x2,
  72606. DDPF_FOURCC = 0x4, DDPF_RGB = 0x40,
  72607. //DDPF_YUV = 0x200,
  72608. DDPF_LUMINANCE = 0x20000;
  72609. function FourCCToInt32(value) {
  72610. return value.charCodeAt(0) +
  72611. (value.charCodeAt(1) << 8) +
  72612. (value.charCodeAt(2) << 16) +
  72613. (value.charCodeAt(3) << 24);
  72614. }
  72615. function Int32ToFourCC(value) {
  72616. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  72617. }
  72618. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  72619. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  72620. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  72621. var FOURCC_DX10 = FourCCToInt32("DX10");
  72622. var FOURCC_D3DFMT_R16G16B16A16F = 113;
  72623. var FOURCC_D3DFMT_R32G32B32A32F = 116;
  72624. var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
  72625. var DXGI_FORMAT_B8G8R8X8_UNORM = 88;
  72626. var headerLengthInt = 31; // The header length in 32 bit ints
  72627. // Offsets into the header array
  72628. var off_magic = 0;
  72629. var off_size = 1;
  72630. var off_flags = 2;
  72631. var off_height = 3;
  72632. var off_width = 4;
  72633. var off_mipmapCount = 7;
  72634. var off_pfFlags = 20;
  72635. var off_pfFourCC = 21;
  72636. var off_RGBbpp = 22;
  72637. var off_RMask = 23;
  72638. var off_GMask = 24;
  72639. var off_BMask = 25;
  72640. var off_AMask = 26;
  72641. // var off_caps1 = 27;
  72642. var off_caps2 = 28;
  72643. // var off_caps3 = 29;
  72644. // var off_caps4 = 30;
  72645. var off_dxgiFormat = 32;
  72646. ;
  72647. var DDSTools = /** @class */ (function () {
  72648. function DDSTools() {
  72649. }
  72650. DDSTools.GetDDSInfo = function (arrayBuffer) {
  72651. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  72652. var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);
  72653. var mipmapCount = 1;
  72654. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  72655. mipmapCount = Math.max(1, header[off_mipmapCount]);
  72656. }
  72657. var fourCC = header[off_pfFourCC];
  72658. var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0;
  72659. var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  72660. switch (fourCC) {
  72661. case FOURCC_D3DFMT_R16G16B16A16F:
  72662. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  72663. break;
  72664. case FOURCC_D3DFMT_R32G32B32A32F:
  72665. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  72666. break;
  72667. case FOURCC_DX10:
  72668. if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
  72669. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  72670. break;
  72671. }
  72672. }
  72673. return {
  72674. width: header[off_width],
  72675. height: header[off_height],
  72676. mipmapCount: mipmapCount,
  72677. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  72678. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  72679. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  72680. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
  72681. isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || fourCC === FOURCC_DXT5),
  72682. dxgiFormat: dxgiFormat,
  72683. textureType: textureType
  72684. };
  72685. };
  72686. DDSTools._ToHalfFloat = function (value) {
  72687. if (!DDSTools._FloatView) {
  72688. DDSTools._FloatView = new Float32Array(1);
  72689. DDSTools._Int32View = new Int32Array(DDSTools._FloatView.buffer);
  72690. }
  72691. DDSTools._FloatView[0] = value;
  72692. var x = DDSTools._Int32View[0];
  72693. var bits = (x >> 16) & 0x8000; /* Get the sign */
  72694. var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
  72695. var e = (x >> 23) & 0xff; /* Using int is faster here */
  72696. /* If zero, or denormal, or exponent underflows too much for a denormal
  72697. * half, return signed zero. */
  72698. if (e < 103) {
  72699. return bits;
  72700. }
  72701. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  72702. if (e > 142) {
  72703. bits |= 0x7c00;
  72704. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  72705. * not Inf, so make sure we set one mantissa bit too. */
  72706. bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);
  72707. return bits;
  72708. }
  72709. /* If exponent underflows but not too much, return a denormal */
  72710. if (e < 113) {
  72711. m |= 0x0800;
  72712. /* Extra rounding may overflow and set mantissa to 0 and exponent
  72713. * to 1, which is OK. */
  72714. bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
  72715. return bits;
  72716. }
  72717. bits |= ((e - 112) << 10) | (m >> 1);
  72718. bits += m & 1;
  72719. return bits;
  72720. };
  72721. DDSTools._FromHalfFloat = function (value) {
  72722. var s = (value & 0x8000) >> 15;
  72723. var e = (value & 0x7C00) >> 10;
  72724. var f = value & 0x03FF;
  72725. if (e === 0) {
  72726. return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
  72727. }
  72728. else if (e == 0x1F) {
  72729. return f ? NaN : ((s ? -1 : 1) * Infinity);
  72730. }
  72731. return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + (f / Math.pow(2, 10)));
  72732. };
  72733. DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  72734. var destArray = new Float32Array(dataLength);
  72735. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  72736. var index = 0;
  72737. for (var y = 0; y < height; y++) {
  72738. for (var x = 0; x < width; x++) {
  72739. var srcPos = (x + y * width) * 4;
  72740. destArray[index] = DDSTools._FromHalfFloat(srcData[srcPos]);
  72741. destArray[index + 1] = DDSTools._FromHalfFloat(srcData[srcPos + 1]);
  72742. destArray[index + 2] = DDSTools._FromHalfFloat(srcData[srcPos + 2]);
  72743. if (DDSTools.StoreLODInAlphaChannel) {
  72744. destArray[index + 3] = lod;
  72745. }
  72746. else {
  72747. destArray[index + 3] = DDSTools._FromHalfFloat(srcData[srcPos + 3]);
  72748. }
  72749. index += 4;
  72750. }
  72751. }
  72752. return destArray;
  72753. };
  72754. DDSTools._GetHalfFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  72755. if (DDSTools.StoreLODInAlphaChannel) {
  72756. var destArray = new Uint16Array(dataLength);
  72757. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  72758. var index = 0;
  72759. for (var y = 0; y < height; y++) {
  72760. for (var x = 0; x < width; x++) {
  72761. var srcPos = (x + y * width) * 4;
  72762. destArray[index] = srcData[srcPos];
  72763. destArray[index + 1] = srcData[srcPos + 1];
  72764. destArray[index + 2] = srcData[srcPos + 2];
  72765. destArray[index + 3] = DDSTools._ToHalfFloat(lod);
  72766. index += 4;
  72767. }
  72768. }
  72769. return destArray;
  72770. }
  72771. return new Uint16Array(arrayBuffer, dataOffset, dataLength);
  72772. };
  72773. DDSTools._GetFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  72774. if (DDSTools.StoreLODInAlphaChannel) {
  72775. var destArray = new Float32Array(dataLength);
  72776. var srcData = new Float32Array(arrayBuffer, dataOffset);
  72777. var index = 0;
  72778. for (var y = 0; y < height; y++) {
  72779. for (var x = 0; x < width; x++) {
  72780. var srcPos = (x + y * width) * 4;
  72781. destArray[index] = srcData[srcPos];
  72782. destArray[index + 1] = srcData[srcPos + 1];
  72783. destArray[index + 2] = srcData[srcPos + 2];
  72784. destArray[index + 3] = lod;
  72785. index += 4;
  72786. }
  72787. }
  72788. return destArray;
  72789. }
  72790. return new Float32Array(arrayBuffer, dataOffset, dataLength);
  72791. };
  72792. DDSTools._GetFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  72793. var destArray = new Uint8Array(dataLength);
  72794. var srcData = new Float32Array(arrayBuffer, dataOffset);
  72795. var index = 0;
  72796. for (var y = 0; y < height; y++) {
  72797. for (var x = 0; x < width; x++) {
  72798. var srcPos = (x + y * width) * 4;
  72799. destArray[index] = BABYLON.Scalar.Clamp(srcData[srcPos]) * 255;
  72800. destArray[index + 1] = BABYLON.Scalar.Clamp(srcData[srcPos + 1]) * 255;
  72801. destArray[index + 2] = BABYLON.Scalar.Clamp(srcData[srcPos + 2]) * 255;
  72802. if (DDSTools.StoreLODInAlphaChannel) {
  72803. destArray[index + 3] = lod;
  72804. }
  72805. else {
  72806. destArray[index + 3] = BABYLON.Scalar.Clamp(srcData[srcPos + 3]) * 255;
  72807. }
  72808. index += 4;
  72809. }
  72810. }
  72811. return destArray;
  72812. };
  72813. DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  72814. var destArray = new Uint8Array(dataLength);
  72815. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  72816. var index = 0;
  72817. for (var y = 0; y < height; y++) {
  72818. for (var x = 0; x < width; x++) {
  72819. var srcPos = (x + y * width) * 4;
  72820. destArray[index] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos])) * 255;
  72821. destArray[index + 1] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 1])) * 255;
  72822. destArray[index + 2] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 2])) * 255;
  72823. if (DDSTools.StoreLODInAlphaChannel) {
  72824. destArray[index + 3] = lod;
  72825. }
  72826. else {
  72827. destArray[index + 3] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 3])) * 255;
  72828. }
  72829. index += 4;
  72830. }
  72831. }
  72832. return destArray;
  72833. };
  72834. DDSTools._GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset) {
  72835. var byteArray = new Uint8Array(dataLength);
  72836. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  72837. var index = 0;
  72838. for (var y = 0; y < height; y++) {
  72839. for (var x = 0; x < width; x++) {
  72840. var srcPos = (x + y * width) * 4;
  72841. byteArray[index] = srcData[srcPos + rOffset];
  72842. byteArray[index + 1] = srcData[srcPos + gOffset];
  72843. byteArray[index + 2] = srcData[srcPos + bOffset];
  72844. byteArray[index + 3] = srcData[srcPos + aOffset];
  72845. index += 4;
  72846. }
  72847. }
  72848. return byteArray;
  72849. };
  72850. DDSTools._ExtractLongWordOrder = function (value) {
  72851. if (value === 0 || value === 255 || value === -16777216) {
  72852. return 0;
  72853. }
  72854. return 1 + DDSTools._ExtractLongWordOrder(value >> 8);
  72855. };
  72856. DDSTools._GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset) {
  72857. var byteArray = new Uint8Array(dataLength);
  72858. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  72859. var index = 0;
  72860. for (var y = 0; y < height; y++) {
  72861. for (var x = 0; x < width; x++) {
  72862. var srcPos = (x + y * width) * 3;
  72863. byteArray[index] = srcData[srcPos + rOffset];
  72864. byteArray[index + 1] = srcData[srcPos + gOffset];
  72865. byteArray[index + 2] = srcData[srcPos + bOffset];
  72866. index += 3;
  72867. }
  72868. }
  72869. return byteArray;
  72870. };
  72871. DDSTools._GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  72872. var byteArray = new Uint8Array(dataLength);
  72873. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  72874. var index = 0;
  72875. for (var y = 0; y < height; y++) {
  72876. for (var x = 0; x < width; x++) {
  72877. var srcPos = (x + y * width);
  72878. byteArray[index] = srcData[srcPos];
  72879. index++;
  72880. }
  72881. }
  72882. return byteArray;
  72883. };
  72884. DDSTools.UploadDDSLevels = function (engine, gl, arrayBuffer, info, loadMipmaps, faces, lodIndex, currentFace) {
  72885. if (lodIndex === void 0) { lodIndex = -1; }
  72886. var ext = engine.getCaps().s3tc;
  72887. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  72888. var fourCC, width, height, dataLength = 0, dataOffset;
  72889. var byteArray, mipmapCount, mip;
  72890. var internalFormat = 0;
  72891. var format = 0;
  72892. var blockBytes = 1;
  72893. if (header[off_magic] !== DDS_MAGIC) {
  72894. BABYLON.Tools.Error("Invalid magic number in DDS header");
  72895. return;
  72896. }
  72897. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  72898. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  72899. return;
  72900. }
  72901. if (info.isCompressed && !ext) {
  72902. BABYLON.Tools.Error("Compressed textures are not supported on this platform.");
  72903. return;
  72904. }
  72905. var bpp = header[off_RGBbpp];
  72906. dataOffset = header[off_size] + 4;
  72907. var computeFormats = false;
  72908. if (info.isFourCC) {
  72909. fourCC = header[off_pfFourCC];
  72910. switch (fourCC) {
  72911. case FOURCC_DXT1:
  72912. blockBytes = 8;
  72913. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  72914. break;
  72915. case FOURCC_DXT3:
  72916. blockBytes = 16;
  72917. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  72918. break;
  72919. case FOURCC_DXT5:
  72920. blockBytes = 16;
  72921. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  72922. break;
  72923. case FOURCC_D3DFMT_R16G16B16A16F:
  72924. computeFormats = true;
  72925. break;
  72926. case FOURCC_D3DFMT_R32G32B32A32F:
  72927. computeFormats = true;
  72928. break;
  72929. case FOURCC_DX10:
  72930. // There is an additionnal header so dataOffset need to be changed
  72931. dataOffset += 5 * 4; // 5 uints
  72932. var supported = false;
  72933. switch (info.dxgiFormat) {
  72934. case DXGI_FORMAT_R16G16B16A16_FLOAT:
  72935. computeFormats = true;
  72936. supported = true;
  72937. break;
  72938. case DXGI_FORMAT_B8G8R8X8_UNORM:
  72939. info.isRGB = true;
  72940. info.isFourCC = false;
  72941. bpp = 32;
  72942. supported = true;
  72943. break;
  72944. }
  72945. if (supported) {
  72946. break;
  72947. }
  72948. default:
  72949. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  72950. return;
  72951. }
  72952. }
  72953. var rOffset = DDSTools._ExtractLongWordOrder(header[off_RMask]);
  72954. var gOffset = DDSTools._ExtractLongWordOrder(header[off_GMask]);
  72955. var bOffset = DDSTools._ExtractLongWordOrder(header[off_BMask]);
  72956. var aOffset = DDSTools._ExtractLongWordOrder(header[off_AMask]);
  72957. if (computeFormats) {
  72958. format = engine._getWebGLTextureType(info.textureType);
  72959. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  72960. }
  72961. mipmapCount = 1;
  72962. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  72963. mipmapCount = Math.max(1, header[off_mipmapCount]);
  72964. }
  72965. for (var face = 0; face < faces; face++) {
  72966. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face + (currentFace ? currentFace : 0));
  72967. width = header[off_width];
  72968. height = header[off_height];
  72969. for (mip = 0; mip < mipmapCount; ++mip) {
  72970. if (lodIndex === -1 || lodIndex === mip) {
  72971. // In case of fixed LOD, if the lod has just been uploaded, early exit.
  72972. var i = (lodIndex === -1) ? mip : 0;
  72973. if (!info.isCompressed && info.isFourCC) {
  72974. dataLength = width * height * 4;
  72975. var floatArray = null;
  72976. if (engine.badOS || engine.badDesktopOS || (!engine.getCaps().textureHalfFloat && !engine.getCaps().textureFloat)) {
  72977. if (bpp === 128) {
  72978. floatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  72979. }
  72980. else if (bpp === 64) {
  72981. floatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  72982. }
  72983. info.textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  72984. format = engine._getWebGLTextureType(info.textureType);
  72985. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  72986. }
  72987. else {
  72988. if (bpp === 128) {
  72989. floatArray = DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  72990. }
  72991. else if (bpp === 64 && !engine.getCaps().textureHalfFloat) {
  72992. floatArray = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  72993. info.textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  72994. format = engine._getWebGLTextureType(info.textureType);
  72995. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  72996. }
  72997. else {
  72998. floatArray = DDSTools._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  72999. }
  73000. }
  73001. if (floatArray) {
  73002. engine._uploadDataToTexture(sampler, i, internalFormat, width, height, gl.RGBA, format, floatArray);
  73003. }
  73004. }
  73005. else if (info.isRGB) {
  73006. if (bpp === 24) {
  73007. dataLength = width * height * 3;
  73008. byteArray = DDSTools._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset);
  73009. engine._uploadDataToTexture(sampler, i, gl.RGB, width, height, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  73010. }
  73011. else {
  73012. dataLength = width * height * 4;
  73013. byteArray = DDSTools._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset);
  73014. engine._uploadDataToTexture(sampler, i, gl.RGBA, width, height, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  73015. }
  73016. }
  73017. else if (info.isLuminance) {
  73018. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  73019. var unpaddedRowSize = width;
  73020. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  73021. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  73022. byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  73023. engine._uploadDataToTexture(sampler, i, gl.LUMINANCE, width, height, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  73024. }
  73025. else {
  73026. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  73027. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  73028. engine._uploadCompressedDataToTexture(sampler, i, internalFormat, width, height, byteArray);
  73029. }
  73030. }
  73031. dataOffset += bpp ? (width * height * (bpp / 8)) : dataLength;
  73032. width *= 0.5;
  73033. height *= 0.5;
  73034. width = Math.max(1.0, width);
  73035. height = Math.max(1.0, height);
  73036. }
  73037. if (currentFace !== undefined) {
  73038. // Loading a single face
  73039. break;
  73040. }
  73041. }
  73042. };
  73043. DDSTools.StoreLODInAlphaChannel = false;
  73044. return DDSTools;
  73045. }());
  73046. BABYLON.DDSTools = DDSTools;
  73047. })(BABYLON || (BABYLON = {}));
  73048. //# sourceMappingURL=babylon.dds.js.map
  73049. var BABYLON;
  73050. (function (BABYLON) {
  73051. /**
  73052. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  73053. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  73054. */
  73055. var KhronosTextureContainer = /** @class */ (function () {
  73056. /**
  73057. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  73058. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  73059. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  73060. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  73061. */
  73062. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  73063. this.arrayBuffer = arrayBuffer;
  73064. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  73065. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  73066. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  73067. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  73068. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  73069. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  73070. BABYLON.Tools.Error("texture missing KTX identifier");
  73071. return;
  73072. }
  73073. // load the reset of the header in native 32 bit int
  73074. var header = new Int32Array(this.arrayBuffer, 12, 13);
  73075. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  73076. var oppositeEndianess = header[0] === 0x01020304;
  73077. // read all the header elements in order they exist in the file, without modification (sans endainness)
  73078. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  73079. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  73080. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  73081. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  73082. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  73083. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  73084. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  73085. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  73086. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  73087. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  73088. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  73089. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  73090. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  73091. if (this.glType !== 0) {
  73092. BABYLON.Tools.Error("only compressed formats currently supported");
  73093. return;
  73094. }
  73095. else {
  73096. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  73097. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  73098. }
  73099. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  73100. BABYLON.Tools.Error("only 2D textures currently supported");
  73101. return;
  73102. }
  73103. if (this.numberOfArrayElements !== 0) {
  73104. BABYLON.Tools.Error("texture arrays not currently supported");
  73105. return;
  73106. }
  73107. if (this.numberOfFaces !== facesExpected) {
  73108. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  73109. return;
  73110. }
  73111. // we now have a completely validated file, so could use existence of loadType as success
  73112. // would need to make this more elaborate & adjust checks above to support more than one load type
  73113. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  73114. }
  73115. // not as fast hardware based, but will probably never need to use
  73116. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  73117. return ((val & 0xFF) << 24)
  73118. | ((val & 0xFF00) << 8)
  73119. | ((val >> 8) & 0xFF00)
  73120. | ((val >> 24) & 0xFF);
  73121. };
  73122. /**
  73123. * It is assumed that the texture has already been created & is currently bound
  73124. */
  73125. KhronosTextureContainer.prototype.uploadLevels = function (gl, loadMipmaps) {
  73126. switch (this.loadType) {
  73127. case KhronosTextureContainer.COMPRESSED_2D:
  73128. this._upload2DCompressedLevels(gl, loadMipmaps);
  73129. break;
  73130. case KhronosTextureContainer.TEX_2D:
  73131. case KhronosTextureContainer.COMPRESSED_3D:
  73132. case KhronosTextureContainer.TEX_3D:
  73133. }
  73134. };
  73135. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (gl, loadMipmaps) {
  73136. // initialize width & height for level 1
  73137. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  73138. var width = this.pixelWidth;
  73139. var height = this.pixelHeight;
  73140. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  73141. for (var level = 0; level < mipmapCount; level++) {
  73142. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  73143. for (var face = 0; face < this.numberOfFaces; face++) {
  73144. var sampler = this.numberOfFaces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  73145. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset + 4, imageSize);
  73146. gl.compressedTexImage2D(sampler, level, this.glInternalFormat, width, height, 0, byteArray);
  73147. dataOffset += imageSize + 4; // size of the image + 4 for the imageSize field
  73148. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  73149. }
  73150. width = Math.max(1.0, width * 0.5);
  73151. height = Math.max(1.0, height * 0.5);
  73152. }
  73153. };
  73154. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  73155. // load types
  73156. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  73157. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  73158. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  73159. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  73160. return KhronosTextureContainer;
  73161. }());
  73162. BABYLON.KhronosTextureContainer = KhronosTextureContainer;
  73163. })(BABYLON || (BABYLON = {}));
  73164. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  73165. var BABYLON;
  73166. (function (BABYLON) {
  73167. var Debug = /** @class */ (function () {
  73168. function Debug() {
  73169. }
  73170. Debug.AxesViewer = /** @class */ (function () {
  73171. function AxesViewer(scene, scaleLines) {
  73172. if (scaleLines === void 0) { scaleLines = 1; }
  73173. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  73174. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  73175. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  73176. this.scaleLines = 1;
  73177. this.scaleLines = scaleLines;
  73178. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  73179. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  73180. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  73181. this._xmesh.renderingGroupId = 2;
  73182. this._ymesh.renderingGroupId = 2;
  73183. this._zmesh.renderingGroupId = 2;
  73184. this._xmesh.material.checkReadyOnlyOnce = true;
  73185. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  73186. this._ymesh.material.checkReadyOnlyOnce = true;
  73187. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  73188. this._zmesh.material.checkReadyOnlyOnce = true;
  73189. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  73190. this.scene = scene;
  73191. }
  73192. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  73193. var scaleLines = this.scaleLines;
  73194. if (this._xmesh) {
  73195. this._xmesh.position.copyFrom(position);
  73196. }
  73197. if (this._ymesh) {
  73198. this._ymesh.position.copyFrom(position);
  73199. }
  73200. if (this._zmesh) {
  73201. this._zmesh.position.copyFrom(position);
  73202. }
  73203. var point2 = this._xline[1];
  73204. point2.x = xaxis.x * scaleLines;
  73205. point2.y = xaxis.y * scaleLines;
  73206. point2.z = xaxis.z * scaleLines;
  73207. BABYLON.Mesh.CreateLines("", this._xline, null, false, this._xmesh);
  73208. point2 = this._yline[1];
  73209. point2.x = yaxis.x * scaleLines;
  73210. point2.y = yaxis.y * scaleLines;
  73211. point2.z = yaxis.z * scaleLines;
  73212. BABYLON.Mesh.CreateLines("", this._yline, null, false, this._ymesh);
  73213. point2 = this._zline[1];
  73214. point2.x = zaxis.x * scaleLines;
  73215. point2.y = zaxis.y * scaleLines;
  73216. point2.z = zaxis.z * scaleLines;
  73217. BABYLON.Mesh.CreateLines("", this._zline, null, false, this._zmesh);
  73218. };
  73219. AxesViewer.prototype.dispose = function () {
  73220. if (this._xmesh) {
  73221. this._xmesh.dispose();
  73222. }
  73223. if (this._ymesh) {
  73224. this._ymesh.dispose();
  73225. }
  73226. if (this._zmesh) {
  73227. this._zmesh.dispose();
  73228. }
  73229. this._xmesh = null;
  73230. this._ymesh = null;
  73231. this._zmesh = null;
  73232. this.scene = null;
  73233. };
  73234. return AxesViewer;
  73235. }());
  73236. Debug.BoneAxesViewer = /** @class */ (function (_super) {
  73237. __extends(BoneAxesViewer, _super);
  73238. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  73239. if (scaleLines === void 0) { scaleLines = 1; }
  73240. var _this = _super.call(this, scene, scaleLines) || this;
  73241. _this.pos = BABYLON.Vector3.Zero();
  73242. _this.xaxis = BABYLON.Vector3.Zero();
  73243. _this.yaxis = BABYLON.Vector3.Zero();
  73244. _this.zaxis = BABYLON.Vector3.Zero();
  73245. _this.mesh = mesh;
  73246. _this.bone = bone;
  73247. return _this;
  73248. }
  73249. BoneAxesViewer.prototype.update = function () {
  73250. if (!this.mesh || !this.bone) {
  73251. return;
  73252. }
  73253. var bone = this.bone;
  73254. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  73255. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  73256. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  73257. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  73258. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  73259. };
  73260. BoneAxesViewer.prototype.dispose = function () {
  73261. if (this.mesh) {
  73262. this.mesh = null;
  73263. this.bone = null;
  73264. _super.prototype.dispose.call(this);
  73265. }
  73266. };
  73267. return BoneAxesViewer;
  73268. }(Debug.AxesViewer));
  73269. Debug.PhysicsViewer = /** @class */ (function () {
  73270. function PhysicsViewer(scene) {
  73271. this._impostors = [];
  73272. this._meshes = [];
  73273. this._numMeshes = 0;
  73274. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  73275. var physicEngine = this._scene.getPhysicsEngine();
  73276. if (physicEngine) {
  73277. this._physicsEnginePlugin = physicEngine.getPhysicsPlugin();
  73278. }
  73279. }
  73280. PhysicsViewer.prototype._updateDebugMeshes = function () {
  73281. var plugin = this._physicsEnginePlugin;
  73282. for (var i = 0; i < this._numMeshes; i++) {
  73283. var impostor = this._impostors[i];
  73284. if (!impostor) {
  73285. continue;
  73286. }
  73287. if (impostor.isDisposed) {
  73288. this.hideImpostor(this._impostors[i--]);
  73289. }
  73290. else {
  73291. var mesh = this._meshes[i];
  73292. if (mesh && plugin) {
  73293. plugin.syncMeshWithImpostor(mesh, impostor);
  73294. }
  73295. }
  73296. }
  73297. };
  73298. PhysicsViewer.prototype.showImpostor = function (impostor) {
  73299. if (!this._scene) {
  73300. return;
  73301. }
  73302. for (var i = 0; i < this._numMeshes; i++) {
  73303. if (this._impostors[i] == impostor) {
  73304. return;
  73305. }
  73306. }
  73307. var debugMesh = this._getDebugMesh(impostor, this._scene);
  73308. if (debugMesh) {
  73309. this._impostors[this._numMeshes] = impostor;
  73310. this._meshes[this._numMeshes] = debugMesh;
  73311. if (this._numMeshes === 0) {
  73312. this._renderFunction = this._updateDebugMeshes.bind(this);
  73313. this._scene.registerBeforeRender(this._renderFunction);
  73314. }
  73315. this._numMeshes++;
  73316. }
  73317. };
  73318. PhysicsViewer.prototype.hideImpostor = function (impostor) {
  73319. if (!impostor || !this._scene) {
  73320. return;
  73321. }
  73322. var removed = false;
  73323. for (var i = 0; i < this._numMeshes; i++) {
  73324. if (this._impostors[i] == impostor) {
  73325. var mesh = this._meshes[i];
  73326. if (!mesh) {
  73327. continue;
  73328. }
  73329. this._scene.removeMesh(mesh);
  73330. mesh.dispose();
  73331. this._numMeshes--;
  73332. if (this._numMeshes > 0) {
  73333. this._meshes[i] = this._meshes[this._numMeshes];
  73334. this._impostors[i] = this._impostors[this._numMeshes];
  73335. this._meshes[this._numMeshes] = null;
  73336. this._impostors[this._numMeshes] = null;
  73337. }
  73338. else {
  73339. this._meshes[0] = null;
  73340. this._impostors[0] = null;
  73341. }
  73342. removed = true;
  73343. break;
  73344. }
  73345. }
  73346. if (removed && this._numMeshes === 0) {
  73347. this._scene.unregisterBeforeRender(this._renderFunction);
  73348. }
  73349. };
  73350. PhysicsViewer.prototype._getDebugMaterial = function (scene) {
  73351. if (!this._debugMaterial) {
  73352. this._debugMaterial = new BABYLON.StandardMaterial('', scene);
  73353. this._debugMaterial.wireframe = true;
  73354. }
  73355. return this._debugMaterial;
  73356. };
  73357. PhysicsViewer.prototype._getDebugBoxMesh = function (scene) {
  73358. if (!this._debugBoxMesh) {
  73359. this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
  73360. this._debugBoxMesh.renderingGroupId = 1;
  73361. this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  73362. this._debugBoxMesh.material = this._getDebugMaterial(scene);
  73363. scene.removeMesh(this._debugBoxMesh);
  73364. }
  73365. return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
  73366. };
  73367. PhysicsViewer.prototype._getDebugSphereMesh = function (scene) {
  73368. if (!this._debugSphereMesh) {
  73369. this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
  73370. this._debugSphereMesh.renderingGroupId = 1;
  73371. this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  73372. this._debugSphereMesh.material = this._getDebugMaterial(scene);
  73373. scene.removeMesh(this._debugSphereMesh);
  73374. }
  73375. return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
  73376. };
  73377. PhysicsViewer.prototype._getDebugMesh = function (impostor, scene) {
  73378. var mesh = null;
  73379. if (impostor.type == BABYLON.PhysicsImpostor.BoxImpostor) {
  73380. mesh = this._getDebugBoxMesh(scene);
  73381. impostor.getBoxSizeToRef(mesh.scaling);
  73382. }
  73383. else if (impostor.type == BABYLON.PhysicsImpostor.SphereImpostor) {
  73384. mesh = this._getDebugSphereMesh(scene);
  73385. var radius = impostor.getRadius();
  73386. mesh.scaling.x = radius * 2;
  73387. mesh.scaling.y = radius * 2;
  73388. mesh.scaling.z = radius * 2;
  73389. }
  73390. return mesh;
  73391. };
  73392. PhysicsViewer.prototype.dispose = function () {
  73393. for (var i = 0; i < this._numMeshes; i++) {
  73394. this.hideImpostor(this._impostors[i]);
  73395. }
  73396. if (this._debugBoxMesh) {
  73397. this._debugBoxMesh.dispose();
  73398. }
  73399. if (this._debugSphereMesh) {
  73400. this._debugSphereMesh.dispose();
  73401. }
  73402. if (this._debugMaterial) {
  73403. this._debugMaterial.dispose();
  73404. }
  73405. this._impostors.length = 0;
  73406. this._scene = null;
  73407. this._physicsEnginePlugin = null;
  73408. };
  73409. return PhysicsViewer;
  73410. }());
  73411. Debug.SkeletonViewer = /** @class */ (function () {
  73412. function SkeletonViewer(skeleton, mesh, scene, autoUpdateBonesMatrices, renderingGroupId) {
  73413. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  73414. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  73415. this.skeleton = skeleton;
  73416. this.mesh = mesh;
  73417. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  73418. this.renderingGroupId = renderingGroupId;
  73419. this.color = BABYLON.Color3.White();
  73420. this._debugLines = new Array();
  73421. this._isEnabled = false;
  73422. this._scene = scene;
  73423. this.update();
  73424. this._renderFunction = this.update.bind(this);
  73425. }
  73426. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  73427. get: function () {
  73428. return this._isEnabled;
  73429. },
  73430. set: function (value) {
  73431. if (this._isEnabled === value) {
  73432. return;
  73433. }
  73434. this._isEnabled = value;
  73435. if (value) {
  73436. this._scene.registerBeforeRender(this._renderFunction);
  73437. }
  73438. else {
  73439. this._scene.unregisterBeforeRender(this._renderFunction);
  73440. }
  73441. },
  73442. enumerable: true,
  73443. configurable: true
  73444. });
  73445. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  73446. if (x === void 0) { x = 0; }
  73447. if (y === void 0) { y = 0; }
  73448. if (z === void 0) { z = 0; }
  73449. var tmat = BABYLON.Tmp.Matrix[0];
  73450. var parentBone = bone.getParent();
  73451. tmat.copyFrom(bone.getLocalMatrix());
  73452. if (x !== 0 || y !== 0 || z !== 0) {
  73453. var tmat2 = BABYLON.Tmp.Matrix[1];
  73454. BABYLON.Matrix.IdentityToRef(tmat2);
  73455. tmat2.m[12] = x;
  73456. tmat2.m[13] = y;
  73457. tmat2.m[14] = z;
  73458. tmat2.multiplyToRef(tmat, tmat);
  73459. }
  73460. if (parentBone) {
  73461. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  73462. }
  73463. tmat.multiplyToRef(meshMat, tmat);
  73464. position.x = tmat.m[12];
  73465. position.y = tmat.m[13];
  73466. position.z = tmat.m[14];
  73467. };
  73468. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  73469. var len = bones.length;
  73470. var meshPos = this.mesh.position;
  73471. for (var i = 0; i < len; i++) {
  73472. var bone = bones[i];
  73473. var points = this._debugLines[i];
  73474. if (!points) {
  73475. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  73476. this._debugLines[i] = points;
  73477. }
  73478. this._getBonePosition(points[0], bone, meshMat);
  73479. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  73480. points[0].subtractInPlace(meshPos);
  73481. points[1].subtractInPlace(meshPos);
  73482. }
  73483. };
  73484. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  73485. var len = bones.length;
  73486. var boneNum = 0;
  73487. var meshPos = this.mesh.position;
  73488. for (var i = len - 1; i >= 0; i--) {
  73489. var childBone = bones[i];
  73490. var parentBone = childBone.getParent();
  73491. if (!parentBone) {
  73492. continue;
  73493. }
  73494. var points = this._debugLines[boneNum];
  73495. if (!points) {
  73496. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  73497. this._debugLines[boneNum] = points;
  73498. }
  73499. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  73500. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  73501. points[0].subtractInPlace(meshPos);
  73502. points[1].subtractInPlace(meshPos);
  73503. boneNum++;
  73504. }
  73505. };
  73506. SkeletonViewer.prototype.update = function () {
  73507. if (this.autoUpdateBonesMatrices) {
  73508. this.skeleton.computeAbsoluteTransforms();
  73509. }
  73510. if (this.skeleton.bones[0].length === undefined) {
  73511. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  73512. }
  73513. else {
  73514. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  73515. }
  73516. if (!this._debugMesh) {
  73517. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: null }, this._scene);
  73518. this._debugMesh.renderingGroupId = this.renderingGroupId;
  73519. }
  73520. else {
  73521. BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  73522. }
  73523. this._debugMesh.position.copyFrom(this.mesh.position);
  73524. this._debugMesh.color = this.color;
  73525. };
  73526. SkeletonViewer.prototype.dispose = function () {
  73527. if (this._debugMesh) {
  73528. this.isEnabled = false;
  73529. this._debugMesh.dispose();
  73530. this._debugMesh = null;
  73531. }
  73532. };
  73533. return SkeletonViewer;
  73534. }());
  73535. return Debug;
  73536. }());
  73537. BABYLON.Debug = Debug;
  73538. })(BABYLON || (BABYLON = {}));
  73539. //# sourceMappingURL=babylon.debugModules.js.map
  73540. var BABYLON;
  73541. (function (BABYLON) {
  73542. var RayHelper = /** @class */ (function () {
  73543. function RayHelper(ray) {
  73544. this.ray = ray;
  73545. }
  73546. RayHelper.CreateAndShow = function (ray, scene, color) {
  73547. var helper = new RayHelper(ray);
  73548. helper.show(scene, color);
  73549. return helper;
  73550. };
  73551. RayHelper.prototype.show = function (scene, color) {
  73552. if (!this._renderFunction && this.ray) {
  73553. var ray = this.ray;
  73554. this._renderFunction = this._render.bind(this);
  73555. this._scene = scene;
  73556. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  73557. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  73558. if (this._renderFunction) {
  73559. this._scene.registerBeforeRender(this._renderFunction);
  73560. }
  73561. }
  73562. if (color && this._renderLine) {
  73563. this._renderLine.color.copyFrom(color);
  73564. }
  73565. };
  73566. RayHelper.prototype.hide = function () {
  73567. if (this._renderFunction && this._scene) {
  73568. this._scene.unregisterBeforeRender(this._renderFunction);
  73569. this._scene = null;
  73570. this._renderFunction = null;
  73571. if (this._renderLine) {
  73572. this._renderLine.dispose();
  73573. this._renderLine = null;
  73574. }
  73575. this._renderPoints = [];
  73576. }
  73577. };
  73578. RayHelper.prototype._render = function () {
  73579. var ray = this.ray;
  73580. if (!ray) {
  73581. return;
  73582. }
  73583. var point = this._renderPoints[1];
  73584. var len = Math.min(ray.length, 1000000);
  73585. point.copyFrom(ray.direction);
  73586. point.scaleInPlace(len);
  73587. point.addInPlace(ray.origin);
  73588. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  73589. };
  73590. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  73591. this._attachedToMesh = mesh;
  73592. var ray = this.ray;
  73593. if (!ray) {
  73594. return;
  73595. }
  73596. if (!ray.direction) {
  73597. ray.direction = BABYLON.Vector3.Zero();
  73598. }
  73599. if (!ray.origin) {
  73600. ray.origin = BABYLON.Vector3.Zero();
  73601. }
  73602. if (length) {
  73603. ray.length = length;
  73604. }
  73605. if (!meshSpaceOrigin) {
  73606. meshSpaceOrigin = BABYLON.Vector3.Zero();
  73607. }
  73608. if (!meshSpaceDirection) {
  73609. // -1 so that this will work with Mesh.lookAt
  73610. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  73611. }
  73612. if (!this._meshSpaceDirection) {
  73613. this._meshSpaceDirection = meshSpaceDirection.clone();
  73614. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  73615. }
  73616. else {
  73617. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  73618. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  73619. }
  73620. if (!this._updateToMeshFunction) {
  73621. this._updateToMeshFunction = this._updateToMesh.bind(this);
  73622. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  73623. }
  73624. this._updateToMesh();
  73625. };
  73626. RayHelper.prototype.detachFromMesh = function () {
  73627. if (this._attachedToMesh) {
  73628. if (this._updateToMeshFunction) {
  73629. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  73630. }
  73631. this._attachedToMesh = null;
  73632. this._updateToMeshFunction = null;
  73633. }
  73634. };
  73635. RayHelper.prototype._updateToMesh = function () {
  73636. var ray = this.ray;
  73637. if (!this._attachedToMesh || !ray) {
  73638. return;
  73639. }
  73640. if (this._attachedToMesh._isDisposed) {
  73641. this.detachFromMesh();
  73642. return;
  73643. }
  73644. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  73645. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  73646. };
  73647. RayHelper.prototype.dispose = function () {
  73648. this.hide();
  73649. this.detachFromMesh();
  73650. this.ray = null;
  73651. };
  73652. return RayHelper;
  73653. }());
  73654. BABYLON.RayHelper = RayHelper;
  73655. })(BABYLON || (BABYLON = {}));
  73656. //# sourceMappingURL=babylon.rayHelper.js.map
  73657. var BABYLON;
  73658. (function (BABYLON) {
  73659. // load the inspector using require, if not present in the global namespace.
  73660. var DebugLayer = /** @class */ (function () {
  73661. function DebugLayer(scene) {
  73662. this.BJSINSPECTOR = typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  73663. this._scene = scene;
  73664. // load inspector using require, if it doesn't exist on the global namespace.
  73665. }
  73666. /** Creates the inspector window. */
  73667. DebugLayer.prototype._createInspector = function (config) {
  73668. if (config === void 0) { config = {}; }
  73669. var popup = config.popup || false;
  73670. var initialTab = config.initialTab || 0;
  73671. var parentElement = config.parentElement || null;
  73672. if (!this._inspector) {
  73673. this.BJSINSPECTOR = this.BJSINSPECTOR || typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  73674. this._inspector = new this.BJSINSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  73675. } // else nothing to do,; instance is already existing
  73676. };
  73677. DebugLayer.prototype.isVisible = function () {
  73678. if (!this._inspector) {
  73679. return false;
  73680. }
  73681. return true;
  73682. };
  73683. DebugLayer.prototype.hide = function () {
  73684. if (this._inspector) {
  73685. try {
  73686. this._inspector.dispose();
  73687. }
  73688. catch (e) {
  73689. // If the inspector has been removed directly from the inspector tool
  73690. }
  73691. this._inspector = null;
  73692. }
  73693. };
  73694. DebugLayer.prototype.show = function (config) {
  73695. if (config === void 0) { config = {}; }
  73696. if (typeof this.BJSINSPECTOR == 'undefined') {
  73697. // Load inspector and add it to the DOM
  73698. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  73699. }
  73700. else {
  73701. // Otherwise creates the inspector
  73702. this._createInspector(config);
  73703. }
  73704. };
  73705. DebugLayer.InspectorURL = 'https://preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  73706. return DebugLayer;
  73707. }());
  73708. BABYLON.DebugLayer = DebugLayer;
  73709. })(BABYLON || (BABYLON = {}));
  73710. //# sourceMappingURL=babylon.debugLayer.js.map
  73711. var BABYLON;
  73712. (function (BABYLON) {
  73713. var BoundingBoxRenderer = /** @class */ (function () {
  73714. function BoundingBoxRenderer(scene) {
  73715. this.frontColor = new BABYLON.Color3(1, 1, 1);
  73716. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  73717. this.showBackLines = true;
  73718. this.renderList = new BABYLON.SmartArray(32);
  73719. this._vertexBuffers = {};
  73720. this._scene = scene;
  73721. }
  73722. BoundingBoxRenderer.prototype._prepareRessources = function () {
  73723. if (this._colorShader) {
  73724. return;
  73725. }
  73726. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  73727. attributes: [BABYLON.VertexBuffer.PositionKind],
  73728. uniforms: ["world", "viewProjection", "color"]
  73729. });
  73730. var engine = this._scene.getEngine();
  73731. var boxdata = BABYLON.VertexData.CreateBox({ size: 1.0 });
  73732. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  73733. this._createIndexBuffer();
  73734. };
  73735. BoundingBoxRenderer.prototype._createIndexBuffer = function () {
  73736. var engine = this._scene.getEngine();
  73737. 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]);
  73738. };
  73739. BoundingBoxRenderer.prototype._rebuild = function () {
  73740. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  73741. if (vb) {
  73742. vb._rebuild();
  73743. }
  73744. this._createIndexBuffer();
  73745. };
  73746. BoundingBoxRenderer.prototype.reset = function () {
  73747. this.renderList.reset();
  73748. };
  73749. BoundingBoxRenderer.prototype.render = function () {
  73750. if (this.renderList.length === 0) {
  73751. return;
  73752. }
  73753. this._prepareRessources();
  73754. if (!this._colorShader.isReady()) {
  73755. return;
  73756. }
  73757. var engine = this._scene.getEngine();
  73758. engine.setDepthWrite(false);
  73759. this._colorShader._preBind();
  73760. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  73761. var boundingBox = this.renderList.data[boundingBoxIndex];
  73762. var min = boundingBox.minimum;
  73763. var max = boundingBox.maximum;
  73764. var diff = max.subtract(min);
  73765. var median = min.add(diff.scale(0.5));
  73766. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  73767. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  73768. .multiply(boundingBox.getWorldMatrix());
  73769. // VBOs
  73770. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  73771. if (this.showBackLines) {
  73772. // Back
  73773. engine.setDepthFunctionToGreaterOrEqual();
  73774. this._scene.resetCachedMaterial();
  73775. this._colorShader.setColor4("color", this.backColor.toColor4());
  73776. this._colorShader.bind(worldMatrix);
  73777. // Draw order
  73778. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  73779. }
  73780. // Front
  73781. engine.setDepthFunctionToLess();
  73782. this._scene.resetCachedMaterial();
  73783. this._colorShader.setColor4("color", this.frontColor.toColor4());
  73784. this._colorShader.bind(worldMatrix);
  73785. // Draw order
  73786. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  73787. }
  73788. this._colorShader.unbind();
  73789. engine.setDepthFunctionToLessOrEqual();
  73790. engine.setDepthWrite(true);
  73791. };
  73792. BoundingBoxRenderer.prototype.renderOcclusionBoundingBox = function (mesh) {
  73793. this._prepareRessources();
  73794. if (!this._colorShader.isReady() || !mesh._boundingInfo) {
  73795. return;
  73796. }
  73797. var engine = this._scene.getEngine();
  73798. engine.setDepthWrite(false);
  73799. engine.setColorWrite(false);
  73800. this._colorShader._preBind();
  73801. var boundingBox = mesh._boundingInfo.boundingBox;
  73802. var min = boundingBox.minimum;
  73803. var max = boundingBox.maximum;
  73804. var diff = max.subtract(min);
  73805. var median = min.add(diff.scale(0.5));
  73806. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  73807. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  73808. .multiply(boundingBox.getWorldMatrix());
  73809. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  73810. engine.setDepthFunctionToLess();
  73811. this._scene.resetCachedMaterial();
  73812. this._colorShader.bind(worldMatrix);
  73813. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  73814. this._colorShader.unbind();
  73815. engine.setDepthFunctionToLessOrEqual();
  73816. engine.setDepthWrite(true);
  73817. engine.setColorWrite(true);
  73818. };
  73819. BoundingBoxRenderer.prototype.dispose = function () {
  73820. if (!this._colorShader) {
  73821. return;
  73822. }
  73823. this.renderList.dispose();
  73824. this._colorShader.dispose();
  73825. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  73826. if (buffer) {
  73827. buffer.dispose();
  73828. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  73829. }
  73830. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  73831. };
  73832. return BoundingBoxRenderer;
  73833. }());
  73834. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  73835. })(BABYLON || (BABYLON = {}));
  73836. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  73837. var BABYLON;
  73838. (function (BABYLON) {
  73839. var MorphTarget = /** @class */ (function () {
  73840. function MorphTarget(name, influence) {
  73841. if (influence === void 0) { influence = 0; }
  73842. this.name = name;
  73843. this.animations = new Array();
  73844. this._positions = null;
  73845. this._normals = null;
  73846. this._tangents = null;
  73847. this.onInfluenceChanged = new BABYLON.Observable();
  73848. this.influence = influence;
  73849. }
  73850. Object.defineProperty(MorphTarget.prototype, "influence", {
  73851. get: function () {
  73852. return this._influence;
  73853. },
  73854. set: function (influence) {
  73855. if (this._influence === influence) {
  73856. return;
  73857. }
  73858. var previous = this._influence;
  73859. this._influence = influence;
  73860. if (this.onInfluenceChanged.hasObservers) {
  73861. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  73862. }
  73863. },
  73864. enumerable: true,
  73865. configurable: true
  73866. });
  73867. Object.defineProperty(MorphTarget.prototype, "hasPositions", {
  73868. get: function () {
  73869. return !!this._positions;
  73870. },
  73871. enumerable: true,
  73872. configurable: true
  73873. });
  73874. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  73875. get: function () {
  73876. return !!this._normals;
  73877. },
  73878. enumerable: true,
  73879. configurable: true
  73880. });
  73881. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  73882. get: function () {
  73883. return !!this._tangents;
  73884. },
  73885. enumerable: true,
  73886. configurable: true
  73887. });
  73888. MorphTarget.prototype.setPositions = function (data) {
  73889. this._positions = data;
  73890. };
  73891. MorphTarget.prototype.getPositions = function () {
  73892. return this._positions;
  73893. };
  73894. MorphTarget.prototype.setNormals = function (data) {
  73895. this._normals = data;
  73896. };
  73897. MorphTarget.prototype.getNormals = function () {
  73898. return this._normals;
  73899. };
  73900. MorphTarget.prototype.setTangents = function (data) {
  73901. this._tangents = data;
  73902. };
  73903. MorphTarget.prototype.getTangents = function () {
  73904. return this._tangents;
  73905. };
  73906. /**
  73907. * Serializes the current target into a Serialization object.
  73908. * Returns the serialized object.
  73909. */
  73910. MorphTarget.prototype.serialize = function () {
  73911. var serializationObject = {};
  73912. serializationObject.name = this.name;
  73913. serializationObject.influence = this.influence;
  73914. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  73915. if (this.hasNormals) {
  73916. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  73917. }
  73918. if (this.hasTangents) {
  73919. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  73920. }
  73921. // Animations
  73922. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  73923. return serializationObject;
  73924. };
  73925. // Statics
  73926. MorphTarget.Parse = function (serializationObject) {
  73927. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  73928. result.setPositions(serializationObject.positions);
  73929. if (serializationObject.normals) {
  73930. result.setNormals(serializationObject.normals);
  73931. }
  73932. if (serializationObject.tangents) {
  73933. result.setTangents(serializationObject.tangents);
  73934. }
  73935. // Animations
  73936. if (serializationObject.animations) {
  73937. for (var animationIndex = 0; animationIndex < serializationObject.animations.length; animationIndex++) {
  73938. var parsedAnimation = serializationObject.animations[animationIndex];
  73939. result.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  73940. }
  73941. }
  73942. return result;
  73943. };
  73944. MorphTarget.FromMesh = function (mesh, name, influence) {
  73945. if (!name) {
  73946. name = mesh.name;
  73947. }
  73948. var result = new MorphTarget(name, influence);
  73949. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  73950. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  73951. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  73952. }
  73953. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  73954. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  73955. }
  73956. return result;
  73957. };
  73958. return MorphTarget;
  73959. }());
  73960. BABYLON.MorphTarget = MorphTarget;
  73961. })(BABYLON || (BABYLON = {}));
  73962. //# sourceMappingURL=babylon.morphTarget.js.map
  73963. var BABYLON;
  73964. (function (BABYLON) {
  73965. var MorphTargetManager = /** @class */ (function () {
  73966. function MorphTargetManager(scene) {
  73967. if (scene === void 0) { scene = null; }
  73968. this._targets = new Array();
  73969. this._targetObservable = new Array();
  73970. this._activeTargets = new BABYLON.SmartArray(16);
  73971. this._supportsNormals = false;
  73972. this._supportsTangents = false;
  73973. this._vertexCount = 0;
  73974. this._uniqueId = 0;
  73975. this._tempInfluences = new Array();
  73976. if (!scene) {
  73977. scene = BABYLON.Engine.LastCreatedScene;
  73978. }
  73979. this._scene = scene;
  73980. if (this._scene) {
  73981. this._scene.morphTargetManagers.push(this);
  73982. this._uniqueId = this._scene.getUniqueId();
  73983. }
  73984. }
  73985. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  73986. get: function () {
  73987. return this._uniqueId;
  73988. },
  73989. enumerable: true,
  73990. configurable: true
  73991. });
  73992. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  73993. get: function () {
  73994. return this._vertexCount;
  73995. },
  73996. enumerable: true,
  73997. configurable: true
  73998. });
  73999. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  74000. get: function () {
  74001. return this._supportsNormals;
  74002. },
  74003. enumerable: true,
  74004. configurable: true
  74005. });
  74006. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  74007. get: function () {
  74008. return this._supportsTangents;
  74009. },
  74010. enumerable: true,
  74011. configurable: true
  74012. });
  74013. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  74014. get: function () {
  74015. return this._targets.length;
  74016. },
  74017. enumerable: true,
  74018. configurable: true
  74019. });
  74020. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  74021. get: function () {
  74022. return this._activeTargets.length;
  74023. },
  74024. enumerable: true,
  74025. configurable: true
  74026. });
  74027. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  74028. get: function () {
  74029. return this._influences;
  74030. },
  74031. enumerable: true,
  74032. configurable: true
  74033. });
  74034. MorphTargetManager.prototype.getActiveTarget = function (index) {
  74035. return this._activeTargets.data[index];
  74036. };
  74037. MorphTargetManager.prototype.getTarget = function (index) {
  74038. return this._targets[index];
  74039. };
  74040. MorphTargetManager.prototype.addTarget = function (target) {
  74041. var _this = this;
  74042. this._targets.push(target);
  74043. this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {
  74044. _this._syncActiveTargets(needUpdate);
  74045. }));
  74046. this._syncActiveTargets(true);
  74047. };
  74048. MorphTargetManager.prototype.removeTarget = function (target) {
  74049. var index = this._targets.indexOf(target);
  74050. if (index >= 0) {
  74051. this._targets.splice(index, 1);
  74052. target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);
  74053. this._syncActiveTargets(true);
  74054. }
  74055. };
  74056. /**
  74057. * Serializes the current manager into a Serialization object.
  74058. * Returns the serialized object.
  74059. */
  74060. MorphTargetManager.prototype.serialize = function () {
  74061. var serializationObject = {};
  74062. serializationObject.id = this.uniqueId;
  74063. serializationObject.targets = [];
  74064. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  74065. var target = _a[_i];
  74066. serializationObject.targets.push(target.serialize());
  74067. }
  74068. return serializationObject;
  74069. };
  74070. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  74071. var influenceCount = 0;
  74072. this._activeTargets.reset();
  74073. this._supportsNormals = true;
  74074. this._supportsTangents = true;
  74075. this._vertexCount = 0;
  74076. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  74077. var target = _a[_i];
  74078. this._activeTargets.push(target);
  74079. this._tempInfluences[influenceCount++] = target.influence;
  74080. var positions = target.getPositions();
  74081. if (positions) {
  74082. this._supportsNormals = this._supportsNormals && target.hasNormals;
  74083. this._supportsTangents = this._supportsTangents && target.hasTangents;
  74084. var vertexCount = positions.length / 3;
  74085. if (this._vertexCount === 0) {
  74086. this._vertexCount = vertexCount;
  74087. }
  74088. else if (this._vertexCount !== vertexCount) {
  74089. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  74090. return;
  74091. }
  74092. }
  74093. }
  74094. if (!this._influences || this._influences.length !== influenceCount) {
  74095. this._influences = new Float32Array(influenceCount);
  74096. }
  74097. for (var index = 0; index < influenceCount; index++) {
  74098. this._influences[index] = this._tempInfluences[index];
  74099. }
  74100. if (needUpdate && this._scene) {
  74101. // Flag meshes as dirty to resync with the active targets
  74102. for (var _b = 0, _c = this._scene.meshes; _b < _c.length; _b++) {
  74103. var mesh = _c[_b];
  74104. if (mesh.morphTargetManager === this) {
  74105. mesh._syncGeometryWithMorphTargetManager();
  74106. }
  74107. }
  74108. }
  74109. };
  74110. // Statics
  74111. MorphTargetManager.Parse = function (serializationObject, scene) {
  74112. var result = new MorphTargetManager(scene);
  74113. result._uniqueId = serializationObject.id;
  74114. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  74115. var targetData = _a[_i];
  74116. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  74117. }
  74118. return result;
  74119. };
  74120. return MorphTargetManager;
  74121. }());
  74122. BABYLON.MorphTargetManager = MorphTargetManager;
  74123. })(BABYLON || (BABYLON = {}));
  74124. //# sourceMappingURL=babylon.morphTargetManager.js.map
  74125. var BABYLON;
  74126. (function (BABYLON) {
  74127. var Octree = /** @class */ (function () {
  74128. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  74129. if (maxDepth === void 0) { maxDepth = 2; }
  74130. this.maxDepth = maxDepth;
  74131. this.dynamicContent = new Array();
  74132. this._maxBlockCapacity = maxBlockCapacity || 64;
  74133. this._selectionContent = new BABYLON.SmartArrayNoDuplicate(1024);
  74134. this._creationFunc = creationFunc;
  74135. }
  74136. // Methods
  74137. Octree.prototype.update = function (worldMin, worldMax, entries) {
  74138. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  74139. };
  74140. Octree.prototype.addMesh = function (entry) {
  74141. for (var index = 0; index < this.blocks.length; index++) {
  74142. var block = this.blocks[index];
  74143. block.addEntry(entry);
  74144. }
  74145. };
  74146. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  74147. this._selectionContent.reset();
  74148. for (var index = 0; index < this.blocks.length; index++) {
  74149. var block = this.blocks[index];
  74150. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  74151. }
  74152. if (allowDuplicate) {
  74153. this._selectionContent.concat(this.dynamicContent);
  74154. }
  74155. else {
  74156. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  74157. }
  74158. return this._selectionContent;
  74159. };
  74160. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  74161. this._selectionContent.reset();
  74162. for (var index = 0; index < this.blocks.length; index++) {
  74163. var block = this.blocks[index];
  74164. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  74165. }
  74166. if (allowDuplicate) {
  74167. this._selectionContent.concat(this.dynamicContent);
  74168. }
  74169. else {
  74170. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  74171. }
  74172. return this._selectionContent;
  74173. };
  74174. Octree.prototype.intersectsRay = function (ray) {
  74175. this._selectionContent.reset();
  74176. for (var index = 0; index < this.blocks.length; index++) {
  74177. var block = this.blocks[index];
  74178. block.intersectsRay(ray, this._selectionContent);
  74179. }
  74180. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  74181. return this._selectionContent;
  74182. };
  74183. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  74184. target.blocks = new Array();
  74185. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  74186. // Segmenting space
  74187. for (var x = 0; x < 2; x++) {
  74188. for (var y = 0; y < 2; y++) {
  74189. for (var z = 0; z < 2; z++) {
  74190. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  74191. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  74192. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  74193. block.addEntries(entries);
  74194. target.blocks.push(block);
  74195. }
  74196. }
  74197. }
  74198. };
  74199. Octree.CreationFuncForMeshes = function (entry, block) {
  74200. var boundingInfo = entry.getBoundingInfo();
  74201. if (!entry.isBlocked && boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  74202. block.entries.push(entry);
  74203. }
  74204. };
  74205. Octree.CreationFuncForSubMeshes = function (entry, block) {
  74206. var boundingInfo = entry.getBoundingInfo();
  74207. if (boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  74208. block.entries.push(entry);
  74209. }
  74210. };
  74211. return Octree;
  74212. }());
  74213. BABYLON.Octree = Octree;
  74214. })(BABYLON || (BABYLON = {}));
  74215. //# sourceMappingURL=babylon.octree.js.map
  74216. var BABYLON;
  74217. (function (BABYLON) {
  74218. var OctreeBlock = /** @class */ (function () {
  74219. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  74220. this.entries = new Array();
  74221. this._boundingVectors = new Array();
  74222. this._capacity = capacity;
  74223. this._depth = depth;
  74224. this._maxDepth = maxDepth;
  74225. this._creationFunc = creationFunc;
  74226. this._minPoint = minPoint;
  74227. this._maxPoint = maxPoint;
  74228. this._boundingVectors.push(minPoint.clone());
  74229. this._boundingVectors.push(maxPoint.clone());
  74230. this._boundingVectors.push(minPoint.clone());
  74231. this._boundingVectors[2].x = maxPoint.x;
  74232. this._boundingVectors.push(minPoint.clone());
  74233. this._boundingVectors[3].y = maxPoint.y;
  74234. this._boundingVectors.push(minPoint.clone());
  74235. this._boundingVectors[4].z = maxPoint.z;
  74236. this._boundingVectors.push(maxPoint.clone());
  74237. this._boundingVectors[5].z = minPoint.z;
  74238. this._boundingVectors.push(maxPoint.clone());
  74239. this._boundingVectors[6].x = minPoint.x;
  74240. this._boundingVectors.push(maxPoint.clone());
  74241. this._boundingVectors[7].y = minPoint.y;
  74242. }
  74243. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  74244. // Property
  74245. get: function () {
  74246. return this._capacity;
  74247. },
  74248. enumerable: true,
  74249. configurable: true
  74250. });
  74251. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  74252. get: function () {
  74253. return this._minPoint;
  74254. },
  74255. enumerable: true,
  74256. configurable: true
  74257. });
  74258. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  74259. get: function () {
  74260. return this._maxPoint;
  74261. },
  74262. enumerable: true,
  74263. configurable: true
  74264. });
  74265. // Methods
  74266. OctreeBlock.prototype.addEntry = function (entry) {
  74267. if (this.blocks) {
  74268. for (var index = 0; index < this.blocks.length; index++) {
  74269. var block = this.blocks[index];
  74270. block.addEntry(entry);
  74271. }
  74272. return;
  74273. }
  74274. this._creationFunc(entry, this);
  74275. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  74276. this.createInnerBlocks();
  74277. }
  74278. };
  74279. OctreeBlock.prototype.addEntries = function (entries) {
  74280. for (var index = 0; index < entries.length; index++) {
  74281. var mesh = entries[index];
  74282. this.addEntry(mesh);
  74283. }
  74284. };
  74285. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  74286. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  74287. if (this.blocks) {
  74288. for (var index = 0; index < this.blocks.length; index++) {
  74289. var block = this.blocks[index];
  74290. block.select(frustumPlanes, selection, allowDuplicate);
  74291. }
  74292. return;
  74293. }
  74294. if (allowDuplicate) {
  74295. selection.concat(this.entries);
  74296. }
  74297. else {
  74298. selection.concatWithNoDuplicate(this.entries);
  74299. }
  74300. }
  74301. };
  74302. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  74303. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  74304. if (this.blocks) {
  74305. for (var index = 0; index < this.blocks.length; index++) {
  74306. var block = this.blocks[index];
  74307. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  74308. }
  74309. return;
  74310. }
  74311. if (allowDuplicate) {
  74312. selection.concat(this.entries);
  74313. }
  74314. else {
  74315. selection.concatWithNoDuplicate(this.entries);
  74316. }
  74317. }
  74318. };
  74319. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  74320. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  74321. if (this.blocks) {
  74322. for (var index = 0; index < this.blocks.length; index++) {
  74323. var block = this.blocks[index];
  74324. block.intersectsRay(ray, selection);
  74325. }
  74326. return;
  74327. }
  74328. selection.concatWithNoDuplicate(this.entries);
  74329. }
  74330. };
  74331. OctreeBlock.prototype.createInnerBlocks = function () {
  74332. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  74333. };
  74334. return OctreeBlock;
  74335. }());
  74336. BABYLON.OctreeBlock = OctreeBlock;
  74337. })(BABYLON || (BABYLON = {}));
  74338. //# sourceMappingURL=babylon.octreeBlock.js.map
  74339. var BABYLON;
  74340. (function (BABYLON) {
  74341. var VRDistortionCorrectionPostProcess = /** @class */ (function (_super) {
  74342. __extends(VRDistortionCorrectionPostProcess, _super);
  74343. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  74344. var _this = _super.call(this, name, "vrDistortionCorrection", [
  74345. 'LensCenter',
  74346. 'Scale',
  74347. 'ScaleIn',
  74348. 'HmdWarpParam'
  74349. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE) || this;
  74350. _this._isRightEye = isRightEye;
  74351. _this._distortionFactors = vrMetrics.distortionK;
  74352. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  74353. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  74354. _this.adaptScaleToCurrentViewport = true;
  74355. _this.onSizeChangedObservable.add(function () {
  74356. _this.aspectRatio = _this.width * .5 / _this.height;
  74357. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  74358. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  74359. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  74360. });
  74361. _this.onApplyObservable.add(function (effect) {
  74362. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  74363. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  74364. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  74365. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  74366. });
  74367. return _this;
  74368. }
  74369. return VRDistortionCorrectionPostProcess;
  74370. }(BABYLON.PostProcess));
  74371. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  74372. })(BABYLON || (BABYLON = {}));
  74373. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  74374. var BABYLON;
  74375. (function (BABYLON) {
  74376. var AnaglyphPostProcess = /** @class */ (function (_super) {
  74377. __extends(AnaglyphPostProcess, _super);
  74378. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  74379. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  74380. _this._passedProcess = rigCameras[0]._rigPostProcess;
  74381. _this.onApplyObservable.add(function (effect) {
  74382. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  74383. });
  74384. return _this;
  74385. }
  74386. return AnaglyphPostProcess;
  74387. }(BABYLON.PostProcess));
  74388. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  74389. })(BABYLON || (BABYLON = {}));
  74390. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  74391. var BABYLON;
  74392. (function (BABYLON) {
  74393. var StereoscopicInterlacePostProcess = /** @class */ (function (_super) {
  74394. __extends(StereoscopicInterlacePostProcess, _super);
  74395. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  74396. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  74397. _this._passedProcess = rigCameras[0]._rigPostProcess;
  74398. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  74399. _this.onSizeChangedObservable.add(function () {
  74400. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  74401. });
  74402. _this.onApplyObservable.add(function (effect) {
  74403. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  74404. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  74405. });
  74406. return _this;
  74407. }
  74408. return StereoscopicInterlacePostProcess;
  74409. }(BABYLON.PostProcess));
  74410. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  74411. })(BABYLON || (BABYLON = {}));
  74412. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  74413. var BABYLON;
  74414. (function (BABYLON) {
  74415. /**
  74416. * Takes information about the orientation of the device as reported by the deviceorientation event to orient the camera.
  74417. * Screen rotation is taken into account.
  74418. */
  74419. var FreeCameraDeviceOrientationInput = /** @class */ (function () {
  74420. function FreeCameraDeviceOrientationInput() {
  74421. var _this = this;
  74422. this._screenOrientationAngle = 0;
  74423. this._screenQuaternion = new BABYLON.Quaternion();
  74424. this._alpha = 0;
  74425. this._beta = 0;
  74426. this._gamma = 0;
  74427. this._orientationChanged = function () {
  74428. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  74429. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  74430. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  74431. };
  74432. this._deviceOrientation = function (evt) {
  74433. _this._alpha = evt.alpha !== null ? evt.alpha : 0;
  74434. _this._beta = evt.beta !== null ? evt.beta : 0;
  74435. _this._gamma = evt.gamma !== null ? evt.gamma : 0;
  74436. };
  74437. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  74438. this._orientationChanged();
  74439. }
  74440. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  74441. get: function () {
  74442. return this._camera;
  74443. },
  74444. set: function (camera) {
  74445. this._camera = camera;
  74446. if (this._camera != null && !this._camera.rotationQuaternion) {
  74447. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  74448. }
  74449. },
  74450. enumerable: true,
  74451. configurable: true
  74452. });
  74453. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  74454. window.addEventListener("orientationchange", this._orientationChanged);
  74455. window.addEventListener("deviceorientation", this._deviceOrientation);
  74456. //In certain cases, the attach control is called AFTER orientation was changed,
  74457. //So this is needed.
  74458. this._orientationChanged();
  74459. };
  74460. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  74461. window.removeEventListener("orientationchange", this._orientationChanged);
  74462. window.removeEventListener("deviceorientation", this._deviceOrientation);
  74463. };
  74464. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  74465. //if no device orientation provided, don't update the rotation.
  74466. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  74467. if (!this._alpha)
  74468. return;
  74469. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  74470. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  74471. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  74472. //Mirror on XY Plane
  74473. this._camera.rotationQuaternion.z *= -1;
  74474. this._camera.rotationQuaternion.w *= -1;
  74475. };
  74476. FreeCameraDeviceOrientationInput.prototype.getClassName = function () {
  74477. return "FreeCameraDeviceOrientationInput";
  74478. };
  74479. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  74480. return "deviceOrientation";
  74481. };
  74482. return FreeCameraDeviceOrientationInput;
  74483. }());
  74484. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  74485. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  74486. })(BABYLON || (BABYLON = {}));
  74487. //# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map
  74488. var BABYLON;
  74489. (function (BABYLON) {
  74490. var ArcRotateCameraVRDeviceOrientationInput = /** @class */ (function () {
  74491. function ArcRotateCameraVRDeviceOrientationInput() {
  74492. this.alphaCorrection = 1;
  74493. this.betaCorrection = 1;
  74494. this.gammaCorrection = 1;
  74495. this._alpha = 0;
  74496. this._gamma = 0;
  74497. this._dirty = false;
  74498. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  74499. }
  74500. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  74501. this.camera.attachControl(element, noPreventDefault);
  74502. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  74503. };
  74504. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  74505. if (evt.alpha !== null) {
  74506. this._alpha = +evt.alpha | 0;
  74507. }
  74508. if (evt.gamma !== null) {
  74509. this._gamma = +evt.gamma | 0;
  74510. }
  74511. this._dirty = true;
  74512. };
  74513. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  74514. if (this._dirty) {
  74515. this._dirty = false;
  74516. if (this._gamma < 0) {
  74517. this._gamma = 180 + this._gamma;
  74518. }
  74519. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  74520. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  74521. }
  74522. };
  74523. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  74524. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  74525. };
  74526. ArcRotateCameraVRDeviceOrientationInput.prototype.getClassName = function () {
  74527. return "ArcRotateCameraVRDeviceOrientationInput";
  74528. };
  74529. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  74530. return "VRDeviceOrientation";
  74531. };
  74532. return ArcRotateCameraVRDeviceOrientationInput;
  74533. }());
  74534. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  74535. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  74536. })(BABYLON || (BABYLON = {}));
  74537. //# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map
  74538. var BABYLON;
  74539. (function (BABYLON) {
  74540. var VRCameraMetrics = /** @class */ (function () {
  74541. function VRCameraMetrics() {
  74542. this.compensateDistortion = true;
  74543. }
  74544. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  74545. get: function () {
  74546. return this.hResolution / (2 * this.vResolution);
  74547. },
  74548. enumerable: true,
  74549. configurable: true
  74550. });
  74551. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  74552. get: function () {
  74553. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  74554. },
  74555. enumerable: true,
  74556. configurable: true
  74557. });
  74558. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  74559. get: function () {
  74560. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  74561. var h = (4 * meters) / this.hScreenSize;
  74562. return BABYLON.Matrix.Translation(h, 0, 0);
  74563. },
  74564. enumerable: true,
  74565. configurable: true
  74566. });
  74567. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  74568. get: function () {
  74569. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  74570. var h = (4 * meters) / this.hScreenSize;
  74571. return BABYLON.Matrix.Translation(-h, 0, 0);
  74572. },
  74573. enumerable: true,
  74574. configurable: true
  74575. });
  74576. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  74577. get: function () {
  74578. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  74579. },
  74580. enumerable: true,
  74581. configurable: true
  74582. });
  74583. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  74584. get: function () {
  74585. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  74586. },
  74587. enumerable: true,
  74588. configurable: true
  74589. });
  74590. VRCameraMetrics.GetDefault = function () {
  74591. var result = new VRCameraMetrics();
  74592. result.hResolution = 1280;
  74593. result.vResolution = 800;
  74594. result.hScreenSize = 0.149759993;
  74595. result.vScreenSize = 0.0935999975;
  74596. result.vScreenCenter = 0.0467999987;
  74597. result.eyeToScreenDistance = 0.0410000011;
  74598. result.lensSeparationDistance = 0.0635000020;
  74599. result.interpupillaryDistance = 0.0640000030;
  74600. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  74601. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  74602. result.postProcessScaleFactor = 1.714605507808412;
  74603. result.lensCenterOffset = 0.151976421;
  74604. return result;
  74605. };
  74606. return VRCameraMetrics;
  74607. }());
  74608. BABYLON.VRCameraMetrics = VRCameraMetrics;
  74609. })(BABYLON || (BABYLON = {}));
  74610. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  74611. var BABYLON;
  74612. (function (BABYLON) {
  74613. /**
  74614. * This represents a WebVR camera.
  74615. * The WebVR camera is Babylon's simple interface to interaction with Windows Mixed Reality, HTC Vive and Oculus Rift.
  74616. * @example http://doc.babylonjs.com/how_to/webvr_camera
  74617. */
  74618. var WebVRFreeCamera = /** @class */ (function (_super) {
  74619. __extends(WebVRFreeCamera, _super);
  74620. /**
  74621. * Instantiates a WebVRFreeCamera.
  74622. * @param name The name of the WebVRFreeCamera
  74623. * @param position The starting anchor position for the camera
  74624. * @param scene The scene the camera belongs to
  74625. * @param webVROptions a set of customizable options for the webVRCamera
  74626. */
  74627. function WebVRFreeCamera(name, position, scene, webVROptions) {
  74628. if (webVROptions === void 0) { webVROptions = {}; }
  74629. var _this = _super.call(this, name, position, scene) || this;
  74630. _this.webVROptions = webVROptions;
  74631. /**
  74632. * The vrDisplay tied to the camera. See https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay
  74633. */
  74634. _this._vrDevice = null;
  74635. /**
  74636. * The rawPose of the vrDevice.
  74637. */
  74638. _this.rawPose = null;
  74639. _this._specsVersion = "1.1";
  74640. _this._attached = false;
  74641. _this._descendants = [];
  74642. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  74643. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  74644. _this._deviceRoomRotationQuaternion = BABYLON.Quaternion.Identity();
  74645. _this._standingMatrix = null;
  74646. /**
  74647. * Represents device position in babylon space.
  74648. */
  74649. _this.devicePosition = BABYLON.Vector3.Zero();
  74650. /**
  74651. * Represents device rotation in babylon space.
  74652. */
  74653. _this.deviceRotationQuaternion = BABYLON.Quaternion.Identity();
  74654. /**
  74655. * The scale of the device to be used when translating from device space to babylon space.
  74656. */
  74657. _this.deviceScaleFactor = 1;
  74658. _this._deviceToWorld = BABYLON.Matrix.Identity();
  74659. _this._worldToDevice = BABYLON.Matrix.Identity();
  74660. /**
  74661. * References to the webVR controllers for the vrDevice.
  74662. */
  74663. _this.controllers = [];
  74664. /**
  74665. * Emits an event when a controller is attached.
  74666. */
  74667. _this.onControllersAttachedObservable = new BABYLON.Observable();
  74668. /**
  74669. * Emits an event when a controller's mesh has been loaded;
  74670. */
  74671. _this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  74672. /**
  74673. * If the rig cameras be used as parent instead of this camera.
  74674. */
  74675. _this.rigParenting = true;
  74676. _this._defaultHeight = undefined;
  74677. _this._workingVector = BABYLON.Vector3.Zero();
  74678. _this._oneVector = BABYLON.Vector3.One();
  74679. _this._workingMatrix = BABYLON.Matrix.Identity();
  74680. _this._cache.position = BABYLON.Vector3.Zero();
  74681. if (webVROptions.defaultHeight) {
  74682. _this._defaultHeight = webVROptions.defaultHeight;
  74683. _this.position.y = _this._defaultHeight;
  74684. }
  74685. _this.minZ = 0.1;
  74686. //legacy support - the compensation boolean was removed.
  74687. if (arguments.length === 5) {
  74688. _this.webVROptions = arguments[4];
  74689. }
  74690. // default webVR options
  74691. if (_this.webVROptions.trackPosition == undefined) {
  74692. _this.webVROptions.trackPosition = true;
  74693. }
  74694. if (_this.webVROptions.controllerMeshes == undefined) {
  74695. _this.webVROptions.controllerMeshes = true;
  74696. }
  74697. if (_this.webVROptions.defaultLightingOnControllers == undefined) {
  74698. _this.webVROptions.defaultLightingOnControllers = true;
  74699. }
  74700. _this.rotationQuaternion = new BABYLON.Quaternion();
  74701. if (_this.webVROptions && _this.webVROptions.positionScale) {
  74702. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  74703. }
  74704. //enable VR
  74705. var engine = _this.getEngine();
  74706. _this._onVREnabled = function (success) { if (success) {
  74707. _this.initControllers();
  74708. } };
  74709. engine.onVRRequestPresentComplete.add(_this._onVREnabled);
  74710. engine.initWebVR().add(function (event) {
  74711. if (!event.vrDisplay || _this._vrDevice === event.vrDisplay) {
  74712. return;
  74713. }
  74714. _this._vrDevice = event.vrDisplay;
  74715. //reset the rig parameters.
  74716. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });
  74717. if (_this._attached) {
  74718. _this.getEngine().enableVR();
  74719. }
  74720. });
  74721. if (typeof (VRFrameData) !== "undefined")
  74722. _this._frameData = new VRFrameData();
  74723. /**
  74724. * The idea behind the following lines:
  74725. * objects that have the camera as parent should actually have the rig cameras as a parent.
  74726. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  74727. * the second will not show it correctly.
  74728. *
  74729. * To solve this - each object that has the camera as parent will be added to a protected array.
  74730. * When the rig camera renders, it will take this array and set all of those to be its children.
  74731. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  74732. * Amazing!
  74733. */
  74734. scene.onBeforeCameraRenderObservable.add(function (camera) {
  74735. if (camera.parent === _this && _this.rigParenting) {
  74736. _this._descendants = _this.getDescendants(true, function (n) {
  74737. // don't take the cameras or the controllers!
  74738. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  74739. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  74740. return !isController && !isRigCamera;
  74741. });
  74742. _this._descendants.forEach(function (node) {
  74743. node.parent = camera;
  74744. });
  74745. }
  74746. });
  74747. scene.onAfterCameraRenderObservable.add(function (camera) {
  74748. if (camera.parent === _this && _this.rigParenting) {
  74749. _this._descendants.forEach(function (node) {
  74750. node.parent = _this;
  74751. });
  74752. }
  74753. });
  74754. return _this;
  74755. }
  74756. /**
  74757. * Gets the device distance from the ground.
  74758. * @returns the distance from the vrDevice to ground in device space. If standing matrix is not supported for the vrDevice 0 is returned.
  74759. */
  74760. WebVRFreeCamera.prototype.deviceDistanceToRoomGround = function () {
  74761. if (this._standingMatrix && this._defaultHeight === undefined) {
  74762. // Add standing matrix offset to get real offset from ground in room
  74763. this._standingMatrix.getTranslationToRef(this._workingVector);
  74764. return this._deviceRoomPosition.y + this._workingVector.y;
  74765. }
  74766. //If VRDisplay does not inform stage parameters and no default height is set we fallback to zero.
  74767. return this._defaultHeight || 0;
  74768. };
  74769. /**
  74770. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  74771. * @param callback will be called when the standing matrix is set. Callback parameter is if the standing matrix is supported.
  74772. */
  74773. WebVRFreeCamera.prototype.useStandingMatrix = function (callback) {
  74774. var _this = this;
  74775. if (callback === void 0) { callback = function (bool) { }; }
  74776. // Use standing matrix if available
  74777. if (!navigator || !navigator.getVRDisplays) {
  74778. callback(false);
  74779. }
  74780. else {
  74781. navigator.getVRDisplays().then(function (displays) {
  74782. if (!displays || !displays[0] || !displays[0].stageParameters || !displays[0].stageParameters.sittingToStandingTransform) {
  74783. callback(false);
  74784. }
  74785. else {
  74786. _this._standingMatrix = new BABYLON.Matrix();
  74787. BABYLON.Matrix.FromFloat32ArrayToRefScaled(displays[0].stageParameters.sittingToStandingTransform, 0, 1, _this._standingMatrix);
  74788. if (!_this.getScene().useRightHandedSystem) {
  74789. [2, 6, 8, 9, 14].forEach(function (num) {
  74790. if (_this._standingMatrix) {
  74791. _this._standingMatrix.m[num] *= -1;
  74792. }
  74793. });
  74794. }
  74795. callback(true);
  74796. }
  74797. });
  74798. }
  74799. };
  74800. /**
  74801. * Disposes the camera
  74802. */
  74803. WebVRFreeCamera.prototype.dispose = function () {
  74804. this.getEngine().onVRRequestPresentComplete.removeCallback(this._onVREnabled);
  74805. _super.prototype.dispose.call(this);
  74806. };
  74807. /**
  74808. * Gets a vrController by name.
  74809. * @param name The name of the controller to retreive
  74810. * @returns the controller matching the name specified or null if not found
  74811. */
  74812. WebVRFreeCamera.prototype.getControllerByName = function (name) {
  74813. for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) {
  74814. var gp = _a[_i];
  74815. if (gp.hand === name) {
  74816. return gp;
  74817. }
  74818. }
  74819. return null;
  74820. };
  74821. Object.defineProperty(WebVRFreeCamera.prototype, "leftController", {
  74822. /**
  74823. * The controller corrisponding to the users left hand.
  74824. */
  74825. get: function () {
  74826. if (!this._leftController) {
  74827. this._leftController = this.getControllerByName("left");
  74828. }
  74829. return this._leftController;
  74830. },
  74831. enumerable: true,
  74832. configurable: true
  74833. });
  74834. ;
  74835. Object.defineProperty(WebVRFreeCamera.prototype, "rightController", {
  74836. /**
  74837. * The controller corrisponding to the users right hand.
  74838. */
  74839. get: function () {
  74840. if (!this._rightController) {
  74841. this._rightController = this.getControllerByName("right");
  74842. }
  74843. return this._rightController;
  74844. },
  74845. enumerable: true,
  74846. configurable: true
  74847. });
  74848. ;
  74849. /**
  74850. * Casts a ray forward from the vrCamera's gaze.
  74851. * @param length Length of the ray (default: 100)
  74852. * @returns the ray corrisponding to the gaze
  74853. */
  74854. WebVRFreeCamera.prototype.getForwardRay = function (length) {
  74855. if (length === void 0) { length = 100; }
  74856. if (this.leftCamera) {
  74857. // Use left eye to avoid computation to compute center on every call
  74858. return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.leftCamera.globalPosition); // Need the actual rendered camera
  74859. }
  74860. else {
  74861. return _super.prototype.getForwardRay.call(this, length);
  74862. }
  74863. };
  74864. /**
  74865. * Updates the camera based on device's frame data
  74866. */
  74867. WebVRFreeCamera.prototype._checkInputs = function () {
  74868. if (this._vrDevice && this._vrDevice.isPresenting) {
  74869. this._vrDevice.getFrameData(this._frameData);
  74870. this.updateFromDevice(this._frameData.pose);
  74871. }
  74872. _super.prototype._checkInputs.call(this);
  74873. };
  74874. /**
  74875. * Updates the poseControlled values based on the input device pose.
  74876. * @param poseData Pose coming from the device
  74877. */
  74878. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  74879. if (poseData && poseData.orientation) {
  74880. this.rawPose = poseData;
  74881. this._deviceRoomRotationQuaternion.copyFromFloats(poseData.orientation[0], poseData.orientation[1], -poseData.orientation[2], -poseData.orientation[3]);
  74882. if (this.getScene().useRightHandedSystem) {
  74883. this._deviceRoomRotationQuaternion.z *= -1;
  74884. this._deviceRoomRotationQuaternion.w *= -1;
  74885. }
  74886. if (this.webVROptions.trackPosition && this.rawPose.position) {
  74887. this._deviceRoomPosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  74888. if (this.getScene().useRightHandedSystem) {
  74889. this._deviceRoomPosition.z *= -1;
  74890. }
  74891. }
  74892. }
  74893. };
  74894. /**
  74895. * WebVR's attach control will start broadcasting frames to the device.
  74896. * Note that in certain browsers (chrome for example) this function must be called
  74897. * within a user-interaction callback. Example:
  74898. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  74899. *
  74900. * @param element html element to attach the vrDevice to
  74901. * @param noPreventDefault prevent the default html element operation when attaching the vrDevice
  74902. */
  74903. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  74904. _super.prototype.attachControl.call(this, element, noPreventDefault);
  74905. this._attached = true;
  74906. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  74907. if (this._vrDevice) {
  74908. this.getEngine().enableVR();
  74909. }
  74910. };
  74911. /**
  74912. * Detaches the camera from the html element and disables VR
  74913. *
  74914. * @param element html element to detach from
  74915. */
  74916. WebVRFreeCamera.prototype.detachControl = function (element) {
  74917. this.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  74918. this.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  74919. _super.prototype.detachControl.call(this, element);
  74920. this._attached = false;
  74921. this.getEngine().disableVR();
  74922. };
  74923. /**
  74924. * @returns the name of this class
  74925. */
  74926. WebVRFreeCamera.prototype.getClassName = function () {
  74927. return "WebVRFreeCamera";
  74928. };
  74929. /**
  74930. * Calls resetPose on the vrDisplay
  74931. * See: https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay/resetPose
  74932. */
  74933. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  74934. //uses the vrDisplay's "resetPose()".
  74935. //pitch and roll won't be affected.
  74936. this._vrDevice.resetPose();
  74937. };
  74938. /**
  74939. * Updates the rig cameras (left and right eye)
  74940. */
  74941. WebVRFreeCamera.prototype._updateRigCameras = function () {
  74942. var camLeft = this._rigCameras[0];
  74943. var camRight = this._rigCameras[1];
  74944. camLeft.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  74945. camRight.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  74946. camLeft.position.copyFrom(this._deviceRoomPosition);
  74947. camRight.position.copyFrom(this._deviceRoomPosition);
  74948. };
  74949. /**
  74950. * Updates the cached values of the camera
  74951. * @param ignoreParentClass ignores updating the parent class's cache (default: false)
  74952. */
  74953. WebVRFreeCamera.prototype._updateCache = function (ignoreParentClass) {
  74954. var _this = this;
  74955. if (!this.rotationQuaternion.equals(this._cache.rotationQuaternion) || !this.position.equals(this._cache.position)) {
  74956. // Update to ensure devicePosition is up to date with most recent _deviceRoomPosition
  74957. if (!this.updateCacheCalled) {
  74958. // make sure it is only called once per loop. this.update() might cause an infinite loop.
  74959. this.updateCacheCalled = true;
  74960. this.update();
  74961. }
  74962. // Set working vector to the device position in room space rotated by the new rotation
  74963. this.rotationQuaternion.toRotationMatrix(this._workingMatrix);
  74964. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._workingMatrix, this._workingVector);
  74965. // Subtract this vector from the current device position in world to get the translation for the device world matrix
  74966. this.devicePosition.subtractToRef(this._workingVector, this._workingVector);
  74967. BABYLON.Matrix.ComposeToRef(this._oneVector, this.rotationQuaternion, this._workingVector, this._deviceToWorld);
  74968. // Add translation from anchor position
  74969. this._deviceToWorld.getTranslationToRef(this._workingVector);
  74970. this._workingVector.addInPlace(this.position);
  74971. this._workingVector.subtractInPlace(this._cache.position);
  74972. this._deviceToWorld.setTranslation(this._workingVector);
  74973. // Set an inverted matrix to be used when updating the camera
  74974. this._deviceToWorld.invertToRef(this._worldToDevice);
  74975. // Update the gamepad to ensure the mesh is updated on the same frame as camera
  74976. this.controllers.forEach(function (controller) {
  74977. controller._deviceToWorld = _this._deviceToWorld;
  74978. controller.update();
  74979. });
  74980. }
  74981. if (!ignoreParentClass) {
  74982. _super.prototype._updateCache.call(this);
  74983. }
  74984. this.updateCacheCalled = false;
  74985. };
  74986. /**
  74987. * Updates the current device position and rotation in the babylon world
  74988. */
  74989. WebVRFreeCamera.prototype.update = function () {
  74990. // Get current device position in babylon world
  74991. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._deviceToWorld, this.devicePosition);
  74992. // Get current device rotation in babylon world
  74993. BABYLON.Matrix.FromQuaternionToRef(this._deviceRoomRotationQuaternion, this._workingMatrix);
  74994. this._workingMatrix.multiplyToRef(this._deviceToWorld, this._workingMatrix);
  74995. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  74996. _super.prototype.update.call(this);
  74997. };
  74998. /**
  74999. * Gets the view matrix of this camera (Always set to identity as left and right eye cameras contain the actual view matrix)
  75000. * @returns an identity matrix
  75001. */
  75002. WebVRFreeCamera.prototype._getViewMatrix = function () {
  75003. return BABYLON.Matrix.Identity();
  75004. };
  75005. /**
  75006. * This function is called by the two RIG cameras.
  75007. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  75008. */
  75009. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  75010. var _this = this;
  75011. //WebVR 1.1
  75012. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  75013. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  75014. if (!this.getScene().useRightHandedSystem) {
  75015. [2, 6, 8, 9, 14].forEach(function (num) {
  75016. _this._webvrViewMatrix.m[num] *= -1;
  75017. });
  75018. }
  75019. // update the camera rotation matrix
  75020. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  75021. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  75022. // Computing target and final matrix
  75023. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  75024. var parentCamera = this._cameraRigParams["parentCamera"];
  75025. // should the view matrix be updated with scale and position offset?
  75026. if (parentCamera.deviceScaleFactor !== 1) {
  75027. this._webvrViewMatrix.invert();
  75028. // scale the position, if set
  75029. if (parentCamera.deviceScaleFactor) {
  75030. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  75031. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  75032. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  75033. }
  75034. this._webvrViewMatrix.invert();
  75035. }
  75036. parentCamera._worldToDevice.multiplyToRef(this._webvrViewMatrix, this._webvrViewMatrix);
  75037. return this._webvrViewMatrix;
  75038. };
  75039. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  75040. var _this = this;
  75041. var parentCamera = this.parent;
  75042. parentCamera._vrDevice.depthNear = parentCamera.minZ;
  75043. parentCamera._vrDevice.depthFar = parentCamera.maxZ;
  75044. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  75045. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  75046. //babylon compatible matrix
  75047. if (!this.getScene().useRightHandedSystem) {
  75048. [8, 9, 10, 11].forEach(function (num) {
  75049. _this._projectionMatrix.m[num] *= -1;
  75050. });
  75051. }
  75052. return this._projectionMatrix;
  75053. };
  75054. /**
  75055. * Initializes the controllers and their meshes
  75056. */
  75057. WebVRFreeCamera.prototype.initControllers = function () {
  75058. var _this = this;
  75059. this.controllers = [];
  75060. var manager = this.getScene().gamepadManager;
  75061. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  75062. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  75063. var webVrController = gamepad;
  75064. if (webVrController.defaultModel) {
  75065. webVrController.defaultModel.setEnabled(false);
  75066. }
  75067. if (webVrController.hand === "right") {
  75068. _this._rightController = null;
  75069. }
  75070. if (webVrController.hand === "left") {
  75071. _this._rightController = null;
  75072. }
  75073. var controllerIndex = _this.controllers.indexOf(webVrController);
  75074. if (controllerIndex !== -1) {
  75075. _this.controllers.splice(controllerIndex, 1);
  75076. }
  75077. }
  75078. });
  75079. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  75080. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  75081. var webVrController_1 = gamepad;
  75082. webVrController_1._deviceToWorld = _this._deviceToWorld;
  75083. if (_this.webVROptions.controllerMeshes) {
  75084. if (webVrController_1.defaultModel) {
  75085. webVrController_1.defaultModel.setEnabled(true);
  75086. }
  75087. else {
  75088. // Load the meshes
  75089. webVrController_1.initControllerMesh(_this.getScene(), function (loadedMesh) {
  75090. _this.onControllerMeshLoadedObservable.notifyObservers(webVrController_1);
  75091. if (_this.webVROptions.defaultLightingOnControllers) {
  75092. if (!_this._lightOnControllers) {
  75093. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  75094. }
  75095. var activateLightOnSubMeshes_1 = function (mesh, light) {
  75096. var children = mesh.getChildren();
  75097. if (children.length !== 0) {
  75098. children.forEach(function (mesh) {
  75099. light.includedOnlyMeshes.push(mesh);
  75100. activateLightOnSubMeshes_1(mesh, light);
  75101. });
  75102. }
  75103. };
  75104. _this._lightOnControllers.includedOnlyMeshes.push(loadedMesh);
  75105. activateLightOnSubMeshes_1(loadedMesh, _this._lightOnControllers);
  75106. }
  75107. });
  75108. }
  75109. }
  75110. webVrController_1.attachToPoseControlledCamera(_this);
  75111. // since this is async - sanity check. Is the controller already stored?
  75112. if (_this.controllers.indexOf(webVrController_1) === -1) {
  75113. //add to the controllers array
  75114. _this.controllers.push(webVrController_1);
  75115. // Forced to add some control code for Vive as it doesn't always fill properly the "hand" property
  75116. // Sometimes, both controllers are set correctly (left and right), sometimes none, sometimes only one of them...
  75117. // So we're overriding setting left & right manually to be sure
  75118. var firstViveWandDetected = false;
  75119. for (var i = 0; i < _this.controllers.length; i++) {
  75120. if (_this.controllers[i].controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  75121. if (!firstViveWandDetected) {
  75122. firstViveWandDetected = true;
  75123. _this.controllers[i].hand = "left";
  75124. }
  75125. else {
  75126. _this.controllers[i].hand = "right";
  75127. }
  75128. }
  75129. }
  75130. //did we find enough controllers? Great! let the developer know.
  75131. if (_this.controllers.length >= 2) {
  75132. _this.onControllersAttachedObservable.notifyObservers(_this.controllers);
  75133. }
  75134. }
  75135. }
  75136. });
  75137. };
  75138. return WebVRFreeCamera;
  75139. }(BABYLON.FreeCamera));
  75140. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  75141. })(BABYLON || (BABYLON = {}));
  75142. //# sourceMappingURL=babylon.webVRCamera.js.map
  75143. var BABYLON;
  75144. (function (BABYLON) {
  75145. // We're mainly based on the logic defined into the FreeCamera code
  75146. /**
  75147. * This is a camera specifically designed to react to device orientation events such as a modern mobile device
  75148. * being tilted forward or back and left or right.
  75149. */
  75150. var DeviceOrientationCamera = /** @class */ (function (_super) {
  75151. __extends(DeviceOrientationCamera, _super);
  75152. /**
  75153. * Creates a new device orientation camera. @see DeviceOrientationCamera
  75154. * @param name The name of the camera
  75155. * @param position The start position camera
  75156. * @param scene The scene the camera belongs to
  75157. */
  75158. function DeviceOrientationCamera(name, position, scene) {
  75159. var _this = _super.call(this, name, position, scene) || this;
  75160. _this._quaternionCache = new BABYLON.Quaternion();
  75161. _this.inputs.addDeviceOrientation();
  75162. return _this;
  75163. }
  75164. /**
  75165. * Gets the current instance class name ("DeviceOrientationCamera").
  75166. * This helps avoiding instanceof at run time.
  75167. * @returns the class name
  75168. */
  75169. DeviceOrientationCamera.prototype.getClassName = function () {
  75170. return "DeviceOrientationCamera";
  75171. };
  75172. /**
  75173. * Checks and applies the current values of the inputs to the camera. (Internal use only)
  75174. */
  75175. DeviceOrientationCamera.prototype._checkInputs = function () {
  75176. _super.prototype._checkInputs.call(this);
  75177. this._quaternionCache.copyFrom(this.rotationQuaternion);
  75178. if (this._initialQuaternion) {
  75179. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  75180. }
  75181. };
  75182. /**
  75183. * Reset the camera to its default orientation on the specified axis only.
  75184. * @param axis The axis to reset
  75185. */
  75186. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  75187. var _this = this;
  75188. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  75189. //can only work if this camera has a rotation quaternion already.
  75190. if (!this.rotationQuaternion)
  75191. return;
  75192. if (!this._initialQuaternion) {
  75193. this._initialQuaternion = new BABYLON.Quaternion();
  75194. }
  75195. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  75196. ['x', 'y', 'z'].forEach(function (axisName) {
  75197. if (!axis[axisName]) {
  75198. _this._initialQuaternion[axisName] = 0;
  75199. }
  75200. else {
  75201. _this._initialQuaternion[axisName] *= -1;
  75202. }
  75203. });
  75204. this._initialQuaternion.normalize();
  75205. //force rotation update
  75206. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  75207. };
  75208. return DeviceOrientationCamera;
  75209. }(BABYLON.FreeCamera));
  75210. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  75211. })(BABYLON || (BABYLON = {}));
  75212. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  75213. var BABYLON;
  75214. (function (BABYLON) {
  75215. var VRDeviceOrientationFreeCamera = /** @class */ (function (_super) {
  75216. __extends(VRDeviceOrientationFreeCamera, _super);
  75217. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  75218. if (compensateDistortion === void 0) { compensateDistortion = true; }
  75219. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  75220. var _this = _super.call(this, name, position, scene) || this;
  75221. vrCameraMetrics.compensateDistortion = compensateDistortion;
  75222. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  75223. return _this;
  75224. }
  75225. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  75226. return "VRDeviceOrientationFreeCamera";
  75227. };
  75228. return VRDeviceOrientationFreeCamera;
  75229. }(BABYLON.DeviceOrientationCamera));
  75230. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  75231. var VRDeviceOrientationGamepadCamera = /** @class */ (function (_super) {
  75232. __extends(VRDeviceOrientationGamepadCamera, _super);
  75233. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  75234. if (compensateDistortion === void 0) { compensateDistortion = true; }
  75235. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  75236. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  75237. _this.inputs.addGamepad();
  75238. return _this;
  75239. }
  75240. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  75241. return "VRDeviceOrientationGamepadCamera";
  75242. };
  75243. return VRDeviceOrientationGamepadCamera;
  75244. }(VRDeviceOrientationFreeCamera));
  75245. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  75246. var VRDeviceOrientationArcRotateCamera = /** @class */ (function (_super) {
  75247. __extends(VRDeviceOrientationArcRotateCamera, _super);
  75248. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  75249. if (compensateDistortion === void 0) { compensateDistortion = true; }
  75250. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  75251. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  75252. vrCameraMetrics.compensateDistortion = compensateDistortion;
  75253. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  75254. _this.inputs.addVRDeviceOrientation();
  75255. return _this;
  75256. }
  75257. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  75258. return "VRDeviceOrientationArcRotateCamera";
  75259. };
  75260. return VRDeviceOrientationArcRotateCamera;
  75261. }(BABYLON.ArcRotateCamera));
  75262. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  75263. })(BABYLON || (BABYLON = {}));
  75264. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  75265. var BABYLON;
  75266. (function (BABYLON) {
  75267. var AnaglyphFreeCamera = /** @class */ (function (_super) {
  75268. __extends(AnaglyphFreeCamera, _super);
  75269. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  75270. var _this = _super.call(this, name, position, scene) || this;
  75271. _this.interaxialDistance = interaxialDistance;
  75272. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  75273. return _this;
  75274. }
  75275. AnaglyphFreeCamera.prototype.getClassName = function () {
  75276. return "AnaglyphFreeCamera";
  75277. };
  75278. return AnaglyphFreeCamera;
  75279. }(BABYLON.FreeCamera));
  75280. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  75281. var AnaglyphArcRotateCamera = /** @class */ (function (_super) {
  75282. __extends(AnaglyphArcRotateCamera, _super);
  75283. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  75284. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  75285. _this.interaxialDistance = interaxialDistance;
  75286. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  75287. return _this;
  75288. }
  75289. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  75290. return "AnaglyphArcRotateCamera";
  75291. };
  75292. return AnaglyphArcRotateCamera;
  75293. }(BABYLON.ArcRotateCamera));
  75294. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  75295. var AnaglyphGamepadCamera = /** @class */ (function (_super) {
  75296. __extends(AnaglyphGamepadCamera, _super);
  75297. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  75298. var _this = _super.call(this, name, position, scene) || this;
  75299. _this.interaxialDistance = interaxialDistance;
  75300. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  75301. return _this;
  75302. }
  75303. AnaglyphGamepadCamera.prototype.getClassName = function () {
  75304. return "AnaglyphGamepadCamera";
  75305. };
  75306. return AnaglyphGamepadCamera;
  75307. }(BABYLON.GamepadCamera));
  75308. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  75309. var AnaglyphUniversalCamera = /** @class */ (function (_super) {
  75310. __extends(AnaglyphUniversalCamera, _super);
  75311. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  75312. var _this = _super.call(this, name, position, scene) || this;
  75313. _this.interaxialDistance = interaxialDistance;
  75314. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  75315. return _this;
  75316. }
  75317. AnaglyphUniversalCamera.prototype.getClassName = function () {
  75318. return "AnaglyphUniversalCamera";
  75319. };
  75320. return AnaglyphUniversalCamera;
  75321. }(BABYLON.UniversalCamera));
  75322. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  75323. var StereoscopicFreeCamera = /** @class */ (function (_super) {
  75324. __extends(StereoscopicFreeCamera, _super);
  75325. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  75326. var _this = _super.call(this, name, position, scene) || this;
  75327. _this.interaxialDistance = interaxialDistance;
  75328. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  75329. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  75330. return _this;
  75331. }
  75332. StereoscopicFreeCamera.prototype.getClassName = function () {
  75333. return "StereoscopicFreeCamera";
  75334. };
  75335. return StereoscopicFreeCamera;
  75336. }(BABYLON.FreeCamera));
  75337. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  75338. var StereoscopicArcRotateCamera = /** @class */ (function (_super) {
  75339. __extends(StereoscopicArcRotateCamera, _super);
  75340. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  75341. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  75342. _this.interaxialDistance = interaxialDistance;
  75343. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  75344. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  75345. return _this;
  75346. }
  75347. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  75348. return "StereoscopicArcRotateCamera";
  75349. };
  75350. return StereoscopicArcRotateCamera;
  75351. }(BABYLON.ArcRotateCamera));
  75352. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  75353. var StereoscopicGamepadCamera = /** @class */ (function (_super) {
  75354. __extends(StereoscopicGamepadCamera, _super);
  75355. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  75356. var _this = _super.call(this, name, position, scene) || this;
  75357. _this.interaxialDistance = interaxialDistance;
  75358. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  75359. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  75360. return _this;
  75361. }
  75362. StereoscopicGamepadCamera.prototype.getClassName = function () {
  75363. return "StereoscopicGamepadCamera";
  75364. };
  75365. return StereoscopicGamepadCamera;
  75366. }(BABYLON.GamepadCamera));
  75367. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  75368. var StereoscopicUniversalCamera = /** @class */ (function (_super) {
  75369. __extends(StereoscopicUniversalCamera, _super);
  75370. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  75371. var _this = _super.call(this, name, position, scene) || this;
  75372. _this.interaxialDistance = interaxialDistance;
  75373. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  75374. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  75375. return _this;
  75376. }
  75377. StereoscopicUniversalCamera.prototype.getClassName = function () {
  75378. return "StereoscopicUniversalCamera";
  75379. };
  75380. return StereoscopicUniversalCamera;
  75381. }(BABYLON.UniversalCamera));
  75382. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  75383. })(BABYLON || (BABYLON = {}));
  75384. //# sourceMappingURL=babylon.stereoscopicCameras.js.map
  75385. var BABYLON;
  75386. (function (BABYLON) {
  75387. /**
  75388. * Helps to quickly add VR support to an existing scene.
  75389. * See http://doc.babylonjs.com/how_to/webvr_helper
  75390. */
  75391. var VRExperienceHelper = /** @class */ (function () {
  75392. /**
  75393. * Instantiates a VRExperienceHelper.
  75394. * Helps to quickly add VR support to an existing scene.
  75395. * @param scene The scene the VRExperienceHelper belongs to.
  75396. * @param webVROptions Options to modify the vr experience helper's behavior.
  75397. */
  75398. function VRExperienceHelper(scene, /** Options to modify the vr experience helper's behavior. */ webVROptions) {
  75399. if (webVROptions === void 0) { webVROptions = {}; }
  75400. var _this = this;
  75401. this.webVROptions = webVROptions;
  75402. // Can the system support WebVR, even if a headset isn't plugged in?
  75403. this._webVRsupported = false;
  75404. // If WebVR is supported, is a headset plugged in and are we ready to present?
  75405. this._webVRready = false;
  75406. // Are we waiting for the requestPresent callback to complete?
  75407. this._webVRrequesting = false;
  75408. // Are we presenting to the headset right now?
  75409. this._webVRpresenting = false;
  75410. // Are we presenting in the fullscreen fallback?
  75411. this._fullscreenVRpresenting = false;
  75412. /**
  75413. * Observable raised when entering VR.
  75414. */
  75415. this.onEnteringVRObservable = new BABYLON.Observable();
  75416. /**
  75417. * Observable raised when exiting VR.
  75418. */
  75419. this.onExitingVRObservable = new BABYLON.Observable();
  75420. /**
  75421. * Observable raised when controller mesh is loaded.
  75422. */
  75423. this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  75424. this._useCustomVRButton = false;
  75425. this._teleportationRequested = false;
  75426. this._teleportationEnabledOnLeftController = false;
  75427. this._teleportationEnabledOnRightController = false;
  75428. this._interactionsEnabledOnLeftController = false;
  75429. this._interactionsEnabledOnRightController = false;
  75430. this._leftControllerReady = false;
  75431. this._rightControllerReady = false;
  75432. this._floorMeshesCollection = [];
  75433. this._teleportationAllowed = false;
  75434. this._rotationAllowed = true;
  75435. this._teleportationRequestInitiated = false;
  75436. this._teleportationBackRequestInitiated = false;
  75437. this.teleportBackwardsVector = new BABYLON.Vector3(0, -1, -1);
  75438. this._rotationRightAsked = false;
  75439. this._rotationLeftAsked = false;
  75440. this._isDefaultTeleportationTarget = true;
  75441. this._teleportationFillColor = "#444444";
  75442. this._teleportationBorderColor = "#FFFFFF";
  75443. this._rotationAngle = 0;
  75444. this._haloCenter = new BABYLON.Vector3(0, 0, 0);
  75445. this._padSensibilityUp = 0.65;
  75446. this._padSensibilityDown = 0.35;
  75447. /**
  75448. * Observable raised when a new mesh is selected based on meshSelectionPredicate
  75449. */
  75450. this.onNewMeshSelected = new BABYLON.Observable();
  75451. /**
  75452. * Observable raised when a new mesh is picked based on meshSelectionPredicate
  75453. */
  75454. this.onNewMeshPicked = new BABYLON.Observable();
  75455. /**
  75456. * Observable raised before camera teleportation
  75457. */
  75458. this.onBeforeCameraTeleport = new BABYLON.Observable();
  75459. /**
  75460. * Observable raised after camera teleportation
  75461. */
  75462. this.onAfterCameraTeleport = new BABYLON.Observable();
  75463. /**
  75464. * Observable raised when current selected mesh gets unselected
  75465. */
  75466. this.onSelectedMeshUnselected = new BABYLON.Observable();
  75467. /**
  75468. * Set teleportation enabled. If set to false camera teleportation will be disabled but camera rotation will be kept.
  75469. */
  75470. this.teleportationEnabled = true;
  75471. this._pointerDownOnMeshAsked = false;
  75472. this._isActionableMesh = false;
  75473. this._teleportationInitialized = false;
  75474. this._interactionsEnabled = false;
  75475. this._interactionsRequested = false;
  75476. this._displayGaze = true;
  75477. this._displayLaserPointer = true;
  75478. this._dpadPressed = true;
  75479. this._onResize = function () {
  75480. _this.moveButtonToBottomRight();
  75481. if (_this._fullscreenVRpresenting && _this._webVRready) {
  75482. _this.exitVR();
  75483. }
  75484. };
  75485. this._onFullscreenChange = function () {
  75486. if (document.fullscreen !== undefined) {
  75487. _this._fullscreenVRpresenting = document.fullscreen;
  75488. }
  75489. else if (document.mozFullScreen !== undefined) {
  75490. _this._fullscreenVRpresenting = document.mozFullScreen;
  75491. }
  75492. else if (document.webkitIsFullScreen !== undefined) {
  75493. _this._fullscreenVRpresenting = document.webkitIsFullScreen;
  75494. }
  75495. else if (document.msIsFullScreen !== undefined) {
  75496. _this._fullscreenVRpresenting = document.msIsFullScreen;
  75497. }
  75498. if (!_this._fullscreenVRpresenting && _this._canvas) {
  75499. _this.exitVR();
  75500. if (!_this._useCustomVRButton) {
  75501. _this._btnVR.style.top = _this._canvas.offsetTop + _this._canvas.offsetHeight - 70 + "px";
  75502. _this._btnVR.style.left = _this._canvas.offsetLeft + _this._canvas.offsetWidth - 100 + "px";
  75503. }
  75504. }
  75505. };
  75506. this.beforeRender = function () {
  75507. _this._castRayAndSelectObject();
  75508. };
  75509. this._onNewGamepadConnected = function (gamepad) {
  75510. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  75511. if (gamepad.leftStick) {
  75512. gamepad.onleftstickchanged(function (stickValues) {
  75513. if (_this._teleportationInitialized && _this.teleportationEnabled) {
  75514. // Listening to classic/xbox gamepad only if no VR controller is active
  75515. if ((!_this._leftLaserPointer && !_this._rightLaserPointer) ||
  75516. ((_this._leftLaserPointer && !_this._leftLaserPointer.isVisible) &&
  75517. (_this._rightLaserPointer && !_this._rightLaserPointer.isVisible))) {
  75518. _this._checkTeleportWithRay(stickValues);
  75519. _this._checkTeleportBackwards(stickValues);
  75520. }
  75521. }
  75522. });
  75523. }
  75524. if (gamepad.rightStick) {
  75525. gamepad.onrightstickchanged(function (stickValues) {
  75526. if (_this._teleportationInitialized) {
  75527. _this._checkRotate(stickValues);
  75528. }
  75529. });
  75530. }
  75531. if (gamepad.type === BABYLON.Gamepad.XBOX) {
  75532. gamepad.onbuttondown(function (buttonPressed) {
  75533. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  75534. _this._selectionPointerDown();
  75535. }
  75536. });
  75537. gamepad.onbuttonup(function (buttonPressed) {
  75538. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  75539. _this._selectionPointerUp();
  75540. }
  75541. });
  75542. }
  75543. }
  75544. else {
  75545. var webVRController = gamepad;
  75546. _this._tryEnableInteractionOnController(webVRController);
  75547. }
  75548. };
  75549. // This only succeeds if the controller's mesh exists for the controller so this must be called whenever new controller is connected or when mesh is loaded
  75550. this._tryEnableInteractionOnController = function (webVRController) {
  75551. if (webVRController.hand === "left") {
  75552. _this._leftControllerReady = true;
  75553. if (_this._interactionsRequested && !_this._interactionsEnabledOnLeftController) {
  75554. _this._enableInteractionOnController(webVRController);
  75555. }
  75556. if (_this._teleportationRequested && !_this._teleportationEnabledOnLeftController) {
  75557. _this._enableTeleportationOnController(webVRController);
  75558. }
  75559. }
  75560. if (webVRController.hand === "right") {
  75561. _this._rightControllerReady = true;
  75562. if (_this._interactionsRequested && !_this._interactionsEnabledOnRightController) {
  75563. _this._enableInteractionOnController(webVRController);
  75564. }
  75565. if (_this._teleportationRequested && !_this._teleportationEnabledOnRightController) {
  75566. _this._enableTeleportationOnController(webVRController);
  75567. }
  75568. }
  75569. };
  75570. this._onNewGamepadDisconnected = function (gamepad) {
  75571. if (gamepad instanceof BABYLON.WebVRController) {
  75572. if (gamepad.hand === "left") {
  75573. _this._interactionsEnabledOnLeftController = false;
  75574. _this._teleportationEnabledOnLeftController = false;
  75575. _this._leftControllerReady = false;
  75576. if (_this._leftLaserPointer) {
  75577. _this._leftLaserPointer.dispose();
  75578. }
  75579. }
  75580. if (gamepad.hand === "right") {
  75581. _this._interactionsEnabledOnRightController = false;
  75582. _this._teleportationEnabledOnRightController = false;
  75583. _this._rightControllerReady = false;
  75584. if (_this._rightLaserPointer) {
  75585. _this._rightLaserPointer.dispose();
  75586. }
  75587. }
  75588. }
  75589. };
  75590. this._workingVector = BABYLON.Vector3.Zero();
  75591. this._workingQuaternion = BABYLON.Quaternion.Identity();
  75592. this._workingMatrix = BABYLON.Matrix.Identity();
  75593. this._scene = scene;
  75594. this._canvas = scene.getEngine().getRenderingCanvas();
  75595. // Parse options
  75596. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera === undefined) {
  75597. webVROptions.createFallbackVRDeviceOrientationFreeCamera = true;
  75598. }
  75599. if (webVROptions.createDeviceOrientationCamera === undefined) {
  75600. webVROptions.createDeviceOrientationCamera = true;
  75601. }
  75602. if (webVROptions.defaultHeight === undefined) {
  75603. webVROptions.defaultHeight = 1.7;
  75604. }
  75605. if (webVROptions.useCustomVRButton) {
  75606. this._useCustomVRButton = true;
  75607. if (webVROptions.customVRButton) {
  75608. this._btnVR = webVROptions.customVRButton;
  75609. }
  75610. }
  75611. if (webVROptions.rayLength) {
  75612. this._rayLength = webVROptions.rayLength;
  75613. }
  75614. this._defaultHeight = webVROptions.defaultHeight;
  75615. // Set position
  75616. if (this._scene.activeCamera) {
  75617. this._position = this._scene.activeCamera.position.clone();
  75618. }
  75619. else {
  75620. this._position = new BABYLON.Vector3(0, this._defaultHeight, 0);
  75621. }
  75622. // Set non-vr camera
  75623. if (webVROptions.createDeviceOrientationCamera || !this._scene.activeCamera) {
  75624. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", this._position.clone(), scene);
  75625. // Copy data from existing camera
  75626. if (this._scene.activeCamera) {
  75627. this._deviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  75628. this._deviceOrientationCamera.maxZ = this._scene.activeCamera.maxZ;
  75629. // Set rotation from previous camera
  75630. if (this._scene.activeCamera instanceof BABYLON.TargetCamera && this._scene.activeCamera.rotation) {
  75631. var targetCamera = this._scene.activeCamera;
  75632. if (targetCamera.rotationQuaternion) {
  75633. this._deviceOrientationCamera.rotationQuaternion.copyFrom(targetCamera.rotationQuaternion);
  75634. }
  75635. else {
  75636. this._deviceOrientationCamera.rotationQuaternion.copyFrom(BABYLON.Quaternion.RotationYawPitchRoll(targetCamera.rotation.y, targetCamera.rotation.x, targetCamera.rotation.z));
  75637. }
  75638. this._deviceOrientationCamera.rotation = targetCamera.rotation.clone();
  75639. }
  75640. }
  75641. this._scene.activeCamera = this._deviceOrientationCamera;
  75642. if (this._canvas) {
  75643. this._scene.activeCamera.attachControl(this._canvas);
  75644. }
  75645. }
  75646. else {
  75647. this._existingCamera = this._scene.activeCamera;
  75648. }
  75649. // Create VR cameras
  75650. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  75651. this._vrDeviceOrientationCamera = new BABYLON.VRDeviceOrientationFreeCamera("VRDeviceOrientationVRHelper", this._position, this._scene);
  75652. }
  75653. this._webVRCamera = new BABYLON.WebVRFreeCamera("WebVRHelper", this._position, this._scene, webVROptions);
  75654. this._webVRCamera.useStandingMatrix();
  75655. // Create default button
  75656. if (!this._useCustomVRButton) {
  75657. this._btnVR = document.createElement("BUTTON");
  75658. this._btnVR.className = "babylonVRicon";
  75659. this._btnVR.id = "babylonVRiconbtn";
  75660. this._btnVR.title = "Click to switch to VR";
  75661. 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) }";
  75662. css += ".babylonVRicon.vrdisplaypresenting { display: none; }";
  75663. // TODO: Add user feedback so that they know what state the VRDisplay is in (disconnected, connected, entering-VR)
  75664. // css += ".babylonVRicon.vrdisplaysupported { }";
  75665. // css += ".babylonVRicon.vrdisplayready { }";
  75666. // css += ".babylonVRicon.vrdisplayrequesting { }";
  75667. var style = document.createElement('style');
  75668. style.appendChild(document.createTextNode(css));
  75669. document.getElementsByTagName('head')[0].appendChild(style);
  75670. this.moveButtonToBottomRight();
  75671. }
  75672. // VR button click event
  75673. if (this._btnVR) {
  75674. this._btnVR.addEventListener("click", function () {
  75675. if (!_this.isInVRMode) {
  75676. _this.enterVR();
  75677. }
  75678. else {
  75679. _this.exitVR();
  75680. }
  75681. });
  75682. }
  75683. // Window events
  75684. window.addEventListener("resize", this._onResize);
  75685. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  75686. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  75687. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  75688. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  75689. // Display vr button when headset is connected
  75690. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  75691. this.displayVRButton();
  75692. }
  75693. else {
  75694. this._scene.getEngine().onVRDisplayChangedObservable.add(function (e) {
  75695. if (e.vrDisplay) {
  75696. _this.displayVRButton();
  75697. }
  75698. });
  75699. }
  75700. // Exiting VR mode using 'ESC' key on desktop
  75701. this._onKeyDown = function (event) {
  75702. if (event.keyCode === 27 && _this.isInVRMode) {
  75703. _this.exitVR();
  75704. }
  75705. };
  75706. document.addEventListener("keydown", this._onKeyDown);
  75707. // Exiting VR mode double tapping the touch screen
  75708. this._scene.onPrePointerObservable.add(function (pointerInfo, eventState) {
  75709. if (_this.isInVRMode) {
  75710. _this.exitVR();
  75711. if (_this._fullscreenVRpresenting) {
  75712. _this._scene.getEngine().switchFullscreen(true);
  75713. }
  75714. }
  75715. }, BABYLON.PointerEventTypes.POINTERDOUBLETAP, false);
  75716. // Listen for WebVR display changes
  75717. this._onVRDisplayChanged = function (eventArgs) { return _this.onVRDisplayChanged(eventArgs); };
  75718. this._onVrDisplayPresentChange = function () { return _this.onVrDisplayPresentChange(); };
  75719. this._onVRRequestPresentStart = function () {
  75720. _this._webVRrequesting = true;
  75721. _this.updateButtonVisibility();
  75722. };
  75723. this._onVRRequestPresentComplete = function (success) {
  75724. _this._webVRrequesting = false;
  75725. _this.updateButtonVisibility();
  75726. };
  75727. scene.getEngine().onVRDisplayChangedObservable.add(this._onVRDisplayChanged);
  75728. scene.getEngine().onVRRequestPresentStart.add(this._onVRRequestPresentStart);
  75729. scene.getEngine().onVRRequestPresentComplete.add(this._onVRRequestPresentComplete);
  75730. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  75731. scene.onDisposeObservable.add(function () {
  75732. _this.dispose();
  75733. });
  75734. // Gamepad connection events
  75735. this._webVRCamera.onControllerMeshLoadedObservable.add(function (webVRController) { return _this._onDefaultMeshLoaded(webVRController); });
  75736. this._scene.gamepadManager.onGamepadConnectedObservable.add(this._onNewGamepadConnected);
  75737. this._scene.gamepadManager.onGamepadDisconnectedObservable.add(this._onNewGamepadDisconnected);
  75738. this.updateButtonVisibility();
  75739. //create easing functions
  75740. this._circleEase = new BABYLON.CircleEase();
  75741. this._circleEase.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  75742. }
  75743. Object.defineProperty(VRExperienceHelper.prototype, "onEnteringVR", {
  75744. /** Return this.onEnteringVRObservable
  75745. * Note: This one is for backward compatibility. Please use onEnteringVRObservable directly
  75746. */
  75747. get: function () {
  75748. return this.onEnteringVRObservable;
  75749. },
  75750. enumerable: true,
  75751. configurable: true
  75752. });
  75753. Object.defineProperty(VRExperienceHelper.prototype, "onExitingVR", {
  75754. /** Return this.onExitingVRObservable
  75755. * Note: This one is for backward compatibility. Please use onExitingVRObservable directly
  75756. */
  75757. get: function () {
  75758. return this.onExitingVRObservable;
  75759. },
  75760. enumerable: true,
  75761. configurable: true
  75762. });
  75763. Object.defineProperty(VRExperienceHelper.prototype, "onControllerMeshLoaded", {
  75764. /** Return this.onControllerMeshLoadedObservable
  75765. * Note: This one is for backward compatibility. Please use onControllerMeshLoadedObservable directly
  75766. */
  75767. get: function () {
  75768. return this.onControllerMeshLoadedObservable;
  75769. },
  75770. enumerable: true,
  75771. configurable: true
  75772. });
  75773. Object.defineProperty(VRExperienceHelper.prototype, "teleportationTarget", {
  75774. /**
  75775. * The mesh used to display where the user is going to teleport.
  75776. */
  75777. get: function () {
  75778. return this._teleportationTarget;
  75779. },
  75780. /**
  75781. * Sets the mesh to be used to display where the user is going to teleport.
  75782. */
  75783. set: function (value) {
  75784. if (value) {
  75785. value.name = "teleportationTarget";
  75786. this._isDefaultTeleportationTarget = false;
  75787. this._teleportationTarget = value;
  75788. }
  75789. },
  75790. enumerable: true,
  75791. configurable: true
  75792. });
  75793. Object.defineProperty(VRExperienceHelper.prototype, "displayGaze", {
  75794. /**
  75795. * If the ray of the gaze should be displayed.
  75796. */
  75797. get: function () {
  75798. return this._displayGaze;
  75799. },
  75800. /**
  75801. * Sets if the ray of the gaze should be displayed.
  75802. */
  75803. set: function (value) {
  75804. this._displayGaze = value;
  75805. if (!value) {
  75806. this._gazeTracker.isVisible = false;
  75807. }
  75808. },
  75809. enumerable: true,
  75810. configurable: true
  75811. });
  75812. Object.defineProperty(VRExperienceHelper.prototype, "displayLaserPointer", {
  75813. /**
  75814. * If the ray of the LaserPointer should be displayed.
  75815. */
  75816. get: function () {
  75817. return this._displayLaserPointer;
  75818. },
  75819. /**
  75820. * Sets if the ray of the LaserPointer should be displayed.
  75821. */
  75822. set: function (value) {
  75823. this._displayLaserPointer = value;
  75824. if (!value) {
  75825. if (this._rightLaserPointer) {
  75826. this._rightLaserPointer.isVisible = false;
  75827. }
  75828. if (this._leftLaserPointer) {
  75829. this._leftLaserPointer.isVisible = false;
  75830. }
  75831. }
  75832. else {
  75833. if (this._rightLaserPointer) {
  75834. this._rightLaserPointer.isVisible = true;
  75835. }
  75836. else if (this._leftLaserPointer) {
  75837. this._leftLaserPointer.isVisible = true;
  75838. }
  75839. }
  75840. },
  75841. enumerable: true,
  75842. configurable: true
  75843. });
  75844. Object.defineProperty(VRExperienceHelper.prototype, "deviceOrientationCamera", {
  75845. /**
  75846. * The deviceOrientationCamera used as the camera when not in VR.
  75847. */
  75848. get: function () {
  75849. return this._deviceOrientationCamera;
  75850. },
  75851. enumerable: true,
  75852. configurable: true
  75853. });
  75854. Object.defineProperty(VRExperienceHelper.prototype, "currentVRCamera", {
  75855. /**
  75856. * Based on the current WebVR support, returns the current VR camera used.
  75857. */
  75858. get: function () {
  75859. if (this._webVRready) {
  75860. return this._webVRCamera;
  75861. }
  75862. else {
  75863. return this._scene.activeCamera;
  75864. }
  75865. },
  75866. enumerable: true,
  75867. configurable: true
  75868. });
  75869. Object.defineProperty(VRExperienceHelper.prototype, "webVRCamera", {
  75870. /**
  75871. * The webVRCamera which is used when in VR.
  75872. */
  75873. get: function () {
  75874. return this._webVRCamera;
  75875. },
  75876. enumerable: true,
  75877. configurable: true
  75878. });
  75879. Object.defineProperty(VRExperienceHelper.prototype, "vrDeviceOrientationCamera", {
  75880. /**
  75881. * The deviceOrientationCamera that is used as a fallback when vr device is not connected.
  75882. */
  75883. get: function () {
  75884. return this._vrDeviceOrientationCamera;
  75885. },
  75886. enumerable: true,
  75887. configurable: true
  75888. });
  75889. // Raised when one of the controller has loaded successfully its associated default mesh
  75890. VRExperienceHelper.prototype._onDefaultMeshLoaded = function (webVRController) {
  75891. this._tryEnableInteractionOnController(webVRController);
  75892. try {
  75893. this.onControllerMeshLoadedObservable.notifyObservers(webVRController);
  75894. }
  75895. catch (err) {
  75896. BABYLON.Tools.Warn("Error in your custom logic onControllerMeshLoaded: " + err);
  75897. }
  75898. };
  75899. Object.defineProperty(VRExperienceHelper.prototype, "isInVRMode", {
  75900. /**
  75901. * Gets a value indicating if we are currently in VR mode.
  75902. */
  75903. get: function () {
  75904. return this._webVRpresenting || this._fullscreenVRpresenting;
  75905. },
  75906. enumerable: true,
  75907. configurable: true
  75908. });
  75909. VRExperienceHelper.prototype.onVrDisplayPresentChange = function () {
  75910. var vrDisplay = this._scene.getEngine().getVRDevice();
  75911. if (vrDisplay) {
  75912. var wasPresenting = this._webVRpresenting;
  75913. // A VR display is connected
  75914. this._webVRpresenting = vrDisplay.isPresenting;
  75915. if (wasPresenting && !this._webVRpresenting)
  75916. this.exitVR();
  75917. }
  75918. else {
  75919. BABYLON.Tools.Warn('Detected VRDisplayPresentChange on an unknown VRDisplay. Did you can enterVR on the vrExperienceHelper?');
  75920. }
  75921. this.updateButtonVisibility();
  75922. };
  75923. VRExperienceHelper.prototype.onVRDisplayChanged = function (eventArgs) {
  75924. this._webVRsupported = eventArgs.vrSupported;
  75925. this._webVRready = !!eventArgs.vrDisplay;
  75926. this._webVRpresenting = eventArgs.vrDisplay && eventArgs.vrDisplay.isPresenting;
  75927. this.updateButtonVisibility();
  75928. };
  75929. VRExperienceHelper.prototype.moveButtonToBottomRight = function () {
  75930. if (this._canvas && !this._useCustomVRButton) {
  75931. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  75932. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  75933. }
  75934. };
  75935. VRExperienceHelper.prototype.displayVRButton = function () {
  75936. if (!this._useCustomVRButton && !this._btnVRDisplayed) {
  75937. document.body.appendChild(this._btnVR);
  75938. this._btnVRDisplayed = true;
  75939. }
  75940. };
  75941. VRExperienceHelper.prototype.updateButtonVisibility = function () {
  75942. if (!this._btnVR || this._useCustomVRButton) {
  75943. return;
  75944. }
  75945. this._btnVR.className = "babylonVRicon";
  75946. if (this.isInVRMode) {
  75947. this._btnVR.className += " vrdisplaypresenting";
  75948. }
  75949. else {
  75950. if (this._webVRready)
  75951. this._btnVR.className += " vrdisplayready";
  75952. if (this._webVRsupported)
  75953. this._btnVR.className += " vrdisplaysupported";
  75954. if (this._webVRrequesting)
  75955. this._btnVR.className += " vrdisplayrequesting";
  75956. }
  75957. };
  75958. /**
  75959. * Attempt to enter VR. If a headset is connected and ready, will request present on that.
  75960. * Otherwise, will use the fullscreen API.
  75961. */
  75962. VRExperienceHelper.prototype.enterVR = function () {
  75963. if (this.onEnteringVRObservable) {
  75964. try {
  75965. this.onEnteringVRObservable.notifyObservers(this);
  75966. }
  75967. catch (err) {
  75968. BABYLON.Tools.Warn("Error in your custom logic onEnteringVR: " + err);
  75969. }
  75970. }
  75971. if (this._scene.activeCamera) {
  75972. this._position = this._scene.activeCamera.position.clone();
  75973. // make sure that we return to the last active camera
  75974. this._existingCamera = this._scene.activeCamera;
  75975. }
  75976. if (this._webVRrequesting)
  75977. return;
  75978. // If WebVR is supported and a headset is connected
  75979. if (this._webVRready) {
  75980. if (!this._webVRpresenting) {
  75981. this._webVRCamera.position = this._position;
  75982. this._scene.activeCamera = this._webVRCamera;
  75983. }
  75984. }
  75985. else if (this._vrDeviceOrientationCamera) {
  75986. this._vrDeviceOrientationCamera.position = this._position;
  75987. this._scene.activeCamera = this._vrDeviceOrientationCamera;
  75988. this._scene.getEngine().switchFullscreen(true);
  75989. this.updateButtonVisibility();
  75990. }
  75991. if (this._scene.activeCamera && this._canvas) {
  75992. this._scene.activeCamera.attachControl(this._canvas);
  75993. }
  75994. if (this._interactionsEnabled) {
  75995. this._scene.registerBeforeRender(this.beforeRender);
  75996. }
  75997. };
  75998. /**
  75999. * Attempt to exit VR, or fullscreen.
  76000. */
  76001. VRExperienceHelper.prototype.exitVR = function () {
  76002. if (this.onExitingVRObservable) {
  76003. try {
  76004. this.onExitingVRObservable.notifyObservers(this);
  76005. }
  76006. catch (err) {
  76007. BABYLON.Tools.Warn("Error in your custom logic onExitingVR: " + err);
  76008. }
  76009. }
  76010. if (this._webVRpresenting) {
  76011. this._scene.getEngine().disableVR();
  76012. }
  76013. if (this._scene.activeCamera) {
  76014. this._position = this._scene.activeCamera.position.clone();
  76015. }
  76016. if (this._deviceOrientationCamera) {
  76017. this._deviceOrientationCamera.position = this._position;
  76018. this._scene.activeCamera = this._deviceOrientationCamera;
  76019. if (this._canvas) {
  76020. this._scene.activeCamera.attachControl(this._canvas);
  76021. }
  76022. }
  76023. else if (this._existingCamera) {
  76024. this._existingCamera.position = this._position;
  76025. this._scene.activeCamera = this._existingCamera;
  76026. }
  76027. this.updateButtonVisibility();
  76028. if (this._interactionsEnabled) {
  76029. this._scene.unregisterBeforeRender(this.beforeRender);
  76030. }
  76031. };
  76032. Object.defineProperty(VRExperienceHelper.prototype, "position", {
  76033. /**
  76034. * The position of the vr experience helper.
  76035. */
  76036. get: function () {
  76037. return this._position;
  76038. },
  76039. /**
  76040. * Sets the position of the vr experience helper.
  76041. */
  76042. set: function (value) {
  76043. this._position = value;
  76044. if (this._scene.activeCamera) {
  76045. this._scene.activeCamera.position = value;
  76046. }
  76047. },
  76048. enumerable: true,
  76049. configurable: true
  76050. });
  76051. /**
  76052. * Enables controllers and user interactions suck as selecting and object or clicking on an object.
  76053. */
  76054. VRExperienceHelper.prototype.enableInteractions = function () {
  76055. var _this = this;
  76056. if (!this._interactionsEnabled) {
  76057. this._interactionsRequested = true;
  76058. if (this._leftControllerReady && this._webVRCamera.leftController) {
  76059. this._enableInteractionOnController(this._webVRCamera.leftController);
  76060. }
  76061. if (this._rightControllerReady && this._webVRCamera.rightController) {
  76062. this._enableInteractionOnController(this._webVRCamera.rightController);
  76063. }
  76064. this._createGazeTracker();
  76065. this.raySelectionPredicate = function (mesh) {
  76066. return mesh.isVisible;
  76067. };
  76068. this.meshSelectionPredicate = function (mesh) {
  76069. return true;
  76070. };
  76071. this._raySelectionPredicate = function (mesh) {
  76072. if (_this._isTeleportationFloor(mesh) || (mesh.name.indexOf("gazeTracker") === -1
  76073. && mesh.name.indexOf("teleportationTarget") === -1
  76074. && mesh.name.indexOf("torusTeleportation") === -1
  76075. && mesh.name.indexOf("laserPointer") === -1)) {
  76076. return _this.raySelectionPredicate(mesh);
  76077. }
  76078. return false;
  76079. };
  76080. this._interactionsEnabled = true;
  76081. }
  76082. };
  76083. VRExperienceHelper.prototype._isTeleportationFloor = function (mesh) {
  76084. for (var i = 0; i < this._floorMeshesCollection.length; i++) {
  76085. if (this._floorMeshesCollection[i].id === mesh.id) {
  76086. return true;
  76087. }
  76088. }
  76089. if (this._floorMeshName && mesh.name === this._floorMeshName) {
  76090. return true;
  76091. }
  76092. return false;
  76093. };
  76094. /**
  76095. * Adds a floor mesh to be used for teleportation.
  76096. * @param floorMesh the mesh to be used for teleportation.
  76097. */
  76098. VRExperienceHelper.prototype.addFloorMesh = function (floorMesh) {
  76099. if (!this._floorMeshesCollection) {
  76100. return;
  76101. }
  76102. if (this._floorMeshesCollection.indexOf(floorMesh) > -1) {
  76103. return;
  76104. }
  76105. this._floorMeshesCollection.push(floorMesh);
  76106. };
  76107. /**
  76108. * Removes a floor mesh from being used for teleportation.
  76109. * @param floorMesh the mesh to be removed.
  76110. */
  76111. VRExperienceHelper.prototype.removeFloorMesh = function (floorMesh) {
  76112. if (!this._floorMeshesCollection) {
  76113. return;
  76114. }
  76115. var meshIndex = this._floorMeshesCollection.indexOf(floorMesh);
  76116. if (meshIndex !== -1) {
  76117. this._floorMeshesCollection.splice(meshIndex, 1);
  76118. }
  76119. };
  76120. /**
  76121. * Enables interactions and teleportation using the VR controllers and gaze.
  76122. * @param vrTeleportationOptions options to modify teleportation behavior.
  76123. */
  76124. VRExperienceHelper.prototype.enableTeleportation = function (vrTeleportationOptions) {
  76125. if (vrTeleportationOptions === void 0) { vrTeleportationOptions = {}; }
  76126. if (!this._teleportationInitialized) {
  76127. this._teleportationRequested = true;
  76128. this.enableInteractions();
  76129. if (vrTeleportationOptions.floorMeshName) {
  76130. this._floorMeshName = vrTeleportationOptions.floorMeshName;
  76131. }
  76132. if (vrTeleportationOptions.floorMeshes) {
  76133. this._floorMeshesCollection = vrTeleportationOptions.floorMeshes;
  76134. }
  76135. if (this._leftControllerReady && this._webVRCamera.leftController) {
  76136. this._enableTeleportationOnController(this._webVRCamera.leftController);
  76137. }
  76138. if (this._rightControllerReady && this._webVRCamera.rightController) {
  76139. this._enableTeleportationOnController(this._webVRCamera.rightController);
  76140. }
  76141. // Creates an image processing post process for the vignette not relying
  76142. // on the main scene configuration for image processing to reduce setup and spaces
  76143. // (gamma/linear) conflicts.
  76144. var imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  76145. imageProcessingConfiguration.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  76146. imageProcessingConfiguration.vignetteEnabled = true;
  76147. this._postProcessMove = new BABYLON.ImageProcessingPostProcess("postProcessMove", 1.0, this._webVRCamera, undefined, undefined, undefined, undefined, imageProcessingConfiguration);
  76148. this._webVRCamera.detachPostProcess(this._postProcessMove);
  76149. this._passProcessMove = new BABYLON.PassPostProcess("pass", 1.0, this._webVRCamera);
  76150. this._teleportationInitialized = true;
  76151. if (this._isDefaultTeleportationTarget) {
  76152. this._createTeleportationCircles();
  76153. }
  76154. }
  76155. };
  76156. VRExperienceHelper.prototype._enableInteractionOnController = function (webVRController) {
  76157. var _this = this;
  76158. var controllerMesh = webVRController.mesh;
  76159. if (controllerMesh) {
  76160. var makeNotPick = function (root) {
  76161. root.name += " laserPointer";
  76162. root.getChildMeshes().forEach(function (c) {
  76163. makeNotPick(c);
  76164. });
  76165. };
  76166. makeNotPick(controllerMesh);
  76167. var childMeshes = controllerMesh.getChildMeshes();
  76168. for (var i = 0; i < childMeshes.length; i++) {
  76169. if (childMeshes[i].name && childMeshes[i].name.indexOf("POINTING_POSE") >= 0) {
  76170. controllerMesh = childMeshes[i];
  76171. break;
  76172. }
  76173. }
  76174. var laserPointer = BABYLON.Mesh.CreateCylinder("laserPointer", 1, 0.004, 0.0002, 20, 1, this._scene, false);
  76175. var laserPointerMaterial = new BABYLON.StandardMaterial("laserPointerMat", this._scene);
  76176. laserPointerMaterial.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  76177. laserPointerMaterial.alpha = 0.6;
  76178. laserPointer.material = laserPointerMaterial;
  76179. laserPointer.rotation.x = Math.PI / 2;
  76180. laserPointer.parent = controllerMesh;
  76181. laserPointer.position.z = -0.5;
  76182. laserPointer.isVisible = false;
  76183. if (webVRController.hand === "left") {
  76184. this._leftLaserPointer = laserPointer;
  76185. this._interactionsEnabledOnLeftController = true;
  76186. if (!this._rightLaserPointer) {
  76187. this._leftLaserPointer.isVisible = true;
  76188. }
  76189. }
  76190. else {
  76191. this._rightLaserPointer = laserPointer;
  76192. this._interactionsEnabledOnRightController = true;
  76193. if (!this._leftLaserPointer) {
  76194. this._rightLaserPointer.isVisible = true;
  76195. }
  76196. }
  76197. webVRController.onMainButtonStateChangedObservable.add(function (stateObject) {
  76198. // Enabling / disabling laserPointer
  76199. if (_this._displayLaserPointer && stateObject.value === 1) {
  76200. laserPointer.isVisible = !laserPointer.isVisible;
  76201. // Laser pointer can only be active on left or right, not both at the same time
  76202. if (webVRController.hand === "left" && _this._rightLaserPointer) {
  76203. _this._rightLaserPointer.isVisible = false;
  76204. }
  76205. else if (_this._leftLaserPointer) {
  76206. _this._leftLaserPointer.isVisible = false;
  76207. }
  76208. }
  76209. });
  76210. webVRController.onTriggerStateChangedObservable.add(function (stateObject) {
  76211. if (!_this._pointerDownOnMeshAsked) {
  76212. if (stateObject.value > _this._padSensibilityUp) {
  76213. _this._selectionPointerDown();
  76214. }
  76215. }
  76216. else if (stateObject.value < _this._padSensibilityDown) {
  76217. _this._selectionPointerUp();
  76218. }
  76219. });
  76220. }
  76221. };
  76222. VRExperienceHelper.prototype._checkTeleportWithRay = function (stateObject, webVRController) {
  76223. if (webVRController === void 0) { webVRController = null; }
  76224. if (!this._teleportationRequestInitiated) {
  76225. if (stateObject.y < -this._padSensibilityUp && this._dpadPressed) {
  76226. if (webVRController) {
  76227. // If laser pointer wasn't enabled yet
  76228. if (this._displayLaserPointer && webVRController.hand === "left" && this._leftLaserPointer) {
  76229. this._leftLaserPointer.isVisible = true;
  76230. if (this._rightLaserPointer) {
  76231. this._rightLaserPointer.isVisible = false;
  76232. }
  76233. }
  76234. else if (this._displayLaserPointer && this._rightLaserPointer) {
  76235. this._rightLaserPointer.isVisible = true;
  76236. if (this._leftLaserPointer) {
  76237. this._leftLaserPointer.isVisible = false;
  76238. }
  76239. }
  76240. }
  76241. this._teleportationRequestInitiated = true;
  76242. }
  76243. }
  76244. else {
  76245. // Listening to the proper controller values changes to confirm teleportation
  76246. if (webVRController == null
  76247. || (webVRController.hand === "left" && this._leftLaserPointer && this._leftLaserPointer.isVisible)
  76248. || (webVRController.hand === "right" && this._rightLaserPointer && this._rightLaserPointer.isVisible)) {
  76249. if (Math.sqrt(stateObject.y * stateObject.y + stateObject.x * stateObject.x) < this._padSensibilityDown) {
  76250. if (this._teleportationAllowed) {
  76251. this._teleportationAllowed = false;
  76252. this._teleportCamera();
  76253. }
  76254. this._teleportationRequestInitiated = false;
  76255. }
  76256. }
  76257. }
  76258. };
  76259. VRExperienceHelper.prototype._selectionPointerDown = function () {
  76260. this._pointerDownOnMeshAsked = true;
  76261. if (this._currentMeshSelected && this._currentHit) {
  76262. this._scene.simulatePointerDown(this._currentHit);
  76263. }
  76264. };
  76265. VRExperienceHelper.prototype._selectionPointerUp = function () {
  76266. if (this._currentMeshSelected && this._currentHit) {
  76267. this._scene.simulatePointerUp(this._currentHit);
  76268. }
  76269. this._pointerDownOnMeshAsked = false;
  76270. };
  76271. VRExperienceHelper.prototype._checkRotate = function (stateObject) {
  76272. // Only rotate when user is not currently selecting a teleportation location
  76273. if (this._teleportationRequestInitiated) {
  76274. return;
  76275. }
  76276. if (!this._rotationLeftAsked) {
  76277. if (stateObject.x < -this._padSensibilityUp && this._dpadPressed) {
  76278. this._rotationLeftAsked = true;
  76279. if (this._rotationAllowed) {
  76280. this._rotateCamera(false);
  76281. }
  76282. }
  76283. }
  76284. else {
  76285. if (stateObject.x > -this._padSensibilityDown) {
  76286. this._rotationLeftAsked = false;
  76287. }
  76288. }
  76289. if (!this._rotationRightAsked) {
  76290. if (stateObject.x > this._padSensibilityUp && this._dpadPressed) {
  76291. this._rotationRightAsked = true;
  76292. if (this._rotationAllowed) {
  76293. this._rotateCamera(true);
  76294. }
  76295. }
  76296. }
  76297. else {
  76298. if (stateObject.x < this._padSensibilityDown) {
  76299. this._rotationRightAsked = false;
  76300. }
  76301. }
  76302. };
  76303. VRExperienceHelper.prototype._checkTeleportBackwards = function (stateObject) {
  76304. // Only teleport backwards when user is not currently selecting a teleportation location
  76305. if (this._teleportationRequestInitiated) {
  76306. return;
  76307. }
  76308. // Teleport backwards
  76309. if (stateObject.y > this._padSensibilityUp && this._dpadPressed) {
  76310. if (!this._teleportationBackRequestInitiated) {
  76311. if (!this.currentVRCamera) {
  76312. return;
  76313. }
  76314. // Get rotation and position of the current camera
  76315. var rotation = BABYLON.Quaternion.FromRotationMatrix(this.currentVRCamera.getWorldMatrix().getRotationMatrix());
  76316. var position = this.currentVRCamera.position;
  76317. // If the camera has device position, use that instead
  76318. if (this.currentVRCamera.devicePosition && this.currentVRCamera.deviceRotationQuaternion) {
  76319. rotation = this.currentVRCamera.deviceRotationQuaternion;
  76320. position = this.currentVRCamera.devicePosition;
  76321. }
  76322. // Get matrix with only the y rotation of the device rotation
  76323. rotation.toEulerAnglesToRef(this._workingVector);
  76324. this._workingVector.z = 0;
  76325. this._workingVector.x = 0;
  76326. BABYLON.Quaternion.RotationYawPitchRollToRef(this._workingVector.y, this._workingVector.x, this._workingVector.z, this._workingQuaternion);
  76327. this._workingQuaternion.toRotationMatrix(this._workingMatrix);
  76328. // Rotate backwards ray by device rotation to cast at the ground behind the user
  76329. BABYLON.Vector3.TransformCoordinatesToRef(this.teleportBackwardsVector, this._workingMatrix, this._workingVector);
  76330. // Teleport if ray hit the ground and is not to far away eg. backwards off a cliff
  76331. var ray = new BABYLON.Ray(position, this._workingVector);
  76332. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  76333. if (hit && hit.pickedPoint && hit.pickedMesh && this._isTeleportationFloor(hit.pickedMesh) && hit.distance < 5) {
  76334. this._teleportCamera(hit.pickedPoint);
  76335. }
  76336. this._teleportationBackRequestInitiated = true;
  76337. }
  76338. }
  76339. else {
  76340. this._teleportationBackRequestInitiated = false;
  76341. }
  76342. };
  76343. VRExperienceHelper.prototype._enableTeleportationOnController = function (webVRController) {
  76344. var _this = this;
  76345. var controllerMesh = webVRController.mesh;
  76346. if (controllerMesh) {
  76347. if (webVRController.hand === "left") {
  76348. if (!this._interactionsEnabledOnLeftController) {
  76349. this._enableInteractionOnController(webVRController);
  76350. }
  76351. this._teleportationEnabledOnLeftController = true;
  76352. }
  76353. else {
  76354. if (!this._interactionsEnabledOnRightController) {
  76355. this._enableInteractionOnController(webVRController);
  76356. }
  76357. this._teleportationEnabledOnRightController = true;
  76358. }
  76359. if (webVRController.controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  76360. this._dpadPressed = false;
  76361. webVRController.onPadStateChangedObservable.add(function (stateObject) {
  76362. _this._dpadPressed = stateObject.pressed;
  76363. if (!_this._dpadPressed) {
  76364. _this._rotationLeftAsked = false;
  76365. _this._rotationRightAsked = false;
  76366. _this._teleportationBackRequestInitiated = false;
  76367. }
  76368. });
  76369. }
  76370. webVRController.onPadValuesChangedObservable.add(function (stateObject) {
  76371. if (_this.teleportationEnabled) {
  76372. _this._checkTeleportBackwards(stateObject);
  76373. _this._checkTeleportWithRay(stateObject, webVRController);
  76374. }
  76375. _this._checkRotate(stateObject);
  76376. });
  76377. }
  76378. };
  76379. // Gaze support used to point to teleport or to interact with an object
  76380. VRExperienceHelper.prototype._createGazeTracker = function () {
  76381. this._gazeTracker = BABYLON.Mesh.CreateTorus("gazeTracker", 0.0035, 0.0025, 20, this._scene, false);
  76382. this._gazeTracker.bakeCurrentTransformIntoVertices();
  76383. this._gazeTracker.isPickable = false;
  76384. this._gazeTracker.isVisible = false;
  76385. var targetMat = new BABYLON.StandardMaterial("targetMat", this._scene);
  76386. targetMat.specularColor = BABYLON.Color3.Black();
  76387. targetMat.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  76388. targetMat.backFaceCulling = false;
  76389. this._gazeTracker.material = targetMat;
  76390. };
  76391. VRExperienceHelper.prototype._createTeleportationCircles = function () {
  76392. this._teleportationTarget = BABYLON.Mesh.CreateGround("teleportationTarget", 2, 2, 2, this._scene);
  76393. this._teleportationTarget.isPickable = false;
  76394. var length = 512;
  76395. var dynamicTexture = new BABYLON.DynamicTexture("DynamicTexture", length, this._scene, true);
  76396. dynamicTexture.hasAlpha = true;
  76397. var context = dynamicTexture.getContext();
  76398. var centerX = length / 2;
  76399. var centerY = length / 2;
  76400. var radius = 200;
  76401. context.beginPath();
  76402. context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
  76403. context.fillStyle = this._teleportationFillColor;
  76404. context.fill();
  76405. context.lineWidth = 10;
  76406. context.strokeStyle = this._teleportationBorderColor;
  76407. context.stroke();
  76408. context.closePath();
  76409. dynamicTexture.update();
  76410. var teleportationCircleMaterial = new BABYLON.StandardMaterial("TextPlaneMaterial", this._scene);
  76411. teleportationCircleMaterial.diffuseTexture = dynamicTexture;
  76412. this._teleportationTarget.material = teleportationCircleMaterial;
  76413. var torus = BABYLON.Mesh.CreateTorus("torusTeleportation", 0.75, 0.1, 25, this._scene, false);
  76414. torus.isPickable = false;
  76415. torus.parent = this._teleportationTarget;
  76416. var animationInnerCircle = new BABYLON.Animation("animationInnerCircle", "position.y", 30, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  76417. var keys = [];
  76418. keys.push({
  76419. frame: 0,
  76420. value: 0
  76421. });
  76422. keys.push({
  76423. frame: 30,
  76424. value: 0.4
  76425. });
  76426. keys.push({
  76427. frame: 60,
  76428. value: 0
  76429. });
  76430. animationInnerCircle.setKeys(keys);
  76431. var easingFunction = new BABYLON.SineEase();
  76432. easingFunction.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  76433. animationInnerCircle.setEasingFunction(easingFunction);
  76434. torus.animations = [];
  76435. torus.animations.push(animationInnerCircle);
  76436. this._scene.beginAnimation(torus, 0, 60, true);
  76437. this._hideTeleportationTarget();
  76438. };
  76439. VRExperienceHelper.prototype._displayTeleportationTarget = function () {
  76440. if (this._teleportationInitialized) {
  76441. this._teleportationTarget.isVisible = true;
  76442. if (this._isDefaultTeleportationTarget) {
  76443. this._teleportationTarget.getChildren()[0].isVisible = true;
  76444. }
  76445. }
  76446. };
  76447. VRExperienceHelper.prototype._hideTeleportationTarget = function () {
  76448. if (this._teleportationInitialized) {
  76449. this._teleportationTarget.isVisible = false;
  76450. if (this._isDefaultTeleportationTarget) {
  76451. this._teleportationTarget.getChildren()[0].isVisible = false;
  76452. }
  76453. }
  76454. };
  76455. VRExperienceHelper.prototype._rotateCamera = function (right) {
  76456. var _this = this;
  76457. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  76458. return;
  76459. }
  76460. if (right) {
  76461. this._rotationAngle++;
  76462. }
  76463. else {
  76464. this._rotationAngle--;
  76465. }
  76466. this.currentVRCamera.animations = [];
  76467. var target = BABYLON.Quaternion.FromRotationMatrix(BABYLON.Matrix.RotationY(Math.PI / 4 * this._rotationAngle));
  76468. var animationRotation = new BABYLON.Animation("animationRotation", "rotationQuaternion", 90, BABYLON.Animation.ANIMATIONTYPE_QUATERNION, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  76469. var animationRotationKeys = [];
  76470. animationRotationKeys.push({
  76471. frame: 0,
  76472. value: this.currentVRCamera.rotationQuaternion
  76473. });
  76474. animationRotationKeys.push({
  76475. frame: 6,
  76476. value: target
  76477. });
  76478. animationRotation.setKeys(animationRotationKeys);
  76479. animationRotation.setEasingFunction(this._circleEase);
  76480. this.currentVRCamera.animations.push(animationRotation);
  76481. this._postProcessMove.animations = [];
  76482. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  76483. var vignetteWeightKeys = [];
  76484. vignetteWeightKeys.push({
  76485. frame: 0,
  76486. value: 0
  76487. });
  76488. vignetteWeightKeys.push({
  76489. frame: 3,
  76490. value: 4
  76491. });
  76492. vignetteWeightKeys.push({
  76493. frame: 6,
  76494. value: 0
  76495. });
  76496. animationPP.setKeys(vignetteWeightKeys);
  76497. animationPP.setEasingFunction(this._circleEase);
  76498. this._postProcessMove.animations.push(animationPP);
  76499. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  76500. var vignetteStretchKeys = [];
  76501. vignetteStretchKeys.push({
  76502. frame: 0,
  76503. value: 0
  76504. });
  76505. vignetteStretchKeys.push({
  76506. frame: 3,
  76507. value: 10
  76508. });
  76509. vignetteStretchKeys.push({
  76510. frame: 6,
  76511. value: 0
  76512. });
  76513. animationPP2.setKeys(vignetteStretchKeys);
  76514. animationPP2.setEasingFunction(this._circleEase);
  76515. this._postProcessMove.animations.push(animationPP2);
  76516. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  76517. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  76518. this._webVRCamera.attachPostProcess(this._postProcessMove);
  76519. this._scene.beginAnimation(this._postProcessMove, 0, 6, false, 1, function () {
  76520. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  76521. });
  76522. this._scene.beginAnimation(this.currentVRCamera, 0, 6, false, 1);
  76523. };
  76524. VRExperienceHelper.prototype._moveTeleportationSelectorTo = function (hit) {
  76525. if (hit.pickedPoint) {
  76526. this._teleportationAllowed = true;
  76527. if (this._teleportationRequestInitiated) {
  76528. this._displayTeleportationTarget();
  76529. }
  76530. else {
  76531. this._hideTeleportationTarget();
  76532. }
  76533. this._haloCenter.copyFrom(hit.pickedPoint);
  76534. this._teleportationTarget.position.copyFrom(hit.pickedPoint);
  76535. var pickNormal = hit.getNormal(true, false);
  76536. if (pickNormal) {
  76537. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  76538. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  76539. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._teleportationTarget.rotation);
  76540. }
  76541. this._teleportationTarget.position.y += 0.1;
  76542. }
  76543. };
  76544. VRExperienceHelper.prototype._teleportCamera = function (location) {
  76545. var _this = this;
  76546. if (location === void 0) { location = null; }
  76547. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  76548. return;
  76549. }
  76550. if (!location) {
  76551. location = this._haloCenter;
  76552. }
  76553. // Teleport the hmd to where the user is looking by moving the anchor to where they are looking minus the
  76554. // offset of the headset from the anchor.
  76555. if (this.webVRCamera.leftCamera) {
  76556. this._workingVector.copyFrom(this.webVRCamera.leftCamera.globalPosition);
  76557. this._workingVector.subtractInPlace(this.webVRCamera.position);
  76558. location.subtractToRef(this._workingVector, this._workingVector);
  76559. }
  76560. else {
  76561. this._workingVector.copyFrom(location);
  76562. }
  76563. // Add height to account for user's height offset
  76564. if (this.isInVRMode) {
  76565. this._workingVector.y += this.webVRCamera.deviceDistanceToRoomGround();
  76566. }
  76567. else {
  76568. this._workingVector.y += this._defaultHeight;
  76569. }
  76570. this.onBeforeCameraTeleport.notifyObservers(this._workingVector);
  76571. // Create animation from the camera's position to the new location
  76572. this.currentVRCamera.animations = [];
  76573. var animationCameraTeleportation = new BABYLON.Animation("animationCameraTeleportation", "position", 90, BABYLON.Animation.ANIMATIONTYPE_VECTOR3, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  76574. var animationCameraTeleportationKeys = [{
  76575. frame: 0,
  76576. value: this.currentVRCamera.position
  76577. },
  76578. {
  76579. frame: 11,
  76580. value: this._workingVector
  76581. }
  76582. ];
  76583. animationCameraTeleportation.setKeys(animationCameraTeleportationKeys);
  76584. animationCameraTeleportation.setEasingFunction(this._circleEase);
  76585. this.currentVRCamera.animations.push(animationCameraTeleportation);
  76586. this._postProcessMove.animations = [];
  76587. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  76588. var vignetteWeightKeys = [];
  76589. vignetteWeightKeys.push({
  76590. frame: 0,
  76591. value: 0
  76592. });
  76593. vignetteWeightKeys.push({
  76594. frame: 5,
  76595. value: 8
  76596. });
  76597. vignetteWeightKeys.push({
  76598. frame: 11,
  76599. value: 0
  76600. });
  76601. animationPP.setKeys(vignetteWeightKeys);
  76602. this._postProcessMove.animations.push(animationPP);
  76603. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  76604. var vignetteStretchKeys = [];
  76605. vignetteStretchKeys.push({
  76606. frame: 0,
  76607. value: 0
  76608. });
  76609. vignetteStretchKeys.push({
  76610. frame: 5,
  76611. value: 10
  76612. });
  76613. vignetteStretchKeys.push({
  76614. frame: 11,
  76615. value: 0
  76616. });
  76617. animationPP2.setKeys(vignetteStretchKeys);
  76618. this._postProcessMove.animations.push(animationPP2);
  76619. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  76620. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  76621. this._webVRCamera.attachPostProcess(this._postProcessMove);
  76622. this._scene.beginAnimation(this._postProcessMove, 0, 11, false, 1, function () {
  76623. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  76624. });
  76625. this._scene.beginAnimation(this.currentVRCamera, 0, 11, false, 1, function () {
  76626. _this.onAfterCameraTeleport.notifyObservers(_this._workingVector);
  76627. });
  76628. };
  76629. VRExperienceHelper.prototype._castRayAndSelectObject = function () {
  76630. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  76631. return;
  76632. }
  76633. var ray;
  76634. if (this._leftLaserPointer && this._leftLaserPointer.isVisible && this.currentVRCamera.leftController) {
  76635. ray = this.currentVRCamera.leftController.getForwardRay(this._rayLength);
  76636. }
  76637. else if (this._rightLaserPointer && this._rightLaserPointer.isVisible && this.currentVRCamera.rightController) {
  76638. ray = this.currentVRCamera.rightController.getForwardRay(this._rayLength);
  76639. }
  76640. else {
  76641. ray = this.currentVRCamera.getForwardRay(this._rayLength);
  76642. }
  76643. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  76644. // Moving the gazeTracker on the mesh face targetted
  76645. if (hit && hit.pickedPoint) {
  76646. if (this._displayGaze) {
  76647. var multiplier = 1;
  76648. this._gazeTracker.isVisible = true;
  76649. if (this._isActionableMesh) {
  76650. multiplier = 3;
  76651. }
  76652. this._gazeTracker.scaling.x = hit.distance * multiplier;
  76653. this._gazeTracker.scaling.y = hit.distance * multiplier;
  76654. this._gazeTracker.scaling.z = hit.distance * multiplier;
  76655. var pickNormal = hit.getNormal();
  76656. // To avoid z-fighting
  76657. var deltaFighting = 0.002;
  76658. if (pickNormal) {
  76659. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  76660. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  76661. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._gazeTracker.rotation);
  76662. }
  76663. this._gazeTracker.position.copyFrom(hit.pickedPoint);
  76664. if (this._gazeTracker.position.x < 0) {
  76665. this._gazeTracker.position.x += deltaFighting;
  76666. }
  76667. else {
  76668. this._gazeTracker.position.x -= deltaFighting;
  76669. }
  76670. if (this._gazeTracker.position.y < 0) {
  76671. this._gazeTracker.position.y += deltaFighting;
  76672. }
  76673. else {
  76674. this._gazeTracker.position.y -= deltaFighting;
  76675. }
  76676. if (this._gazeTracker.position.z < 0) {
  76677. this._gazeTracker.position.z += deltaFighting;
  76678. }
  76679. else {
  76680. this._gazeTracker.position.z -= deltaFighting;
  76681. }
  76682. }
  76683. // Changing the size of the laser pointer based on the distance from the targetted point
  76684. if (this._rightLaserPointer && this._rightLaserPointer.isVisible) {
  76685. this._rightLaserPointer.scaling.y = hit.distance;
  76686. this._rightLaserPointer.position.z = -hit.distance / 2;
  76687. }
  76688. if (this._leftLaserPointer && this._leftLaserPointer.isVisible) {
  76689. this._leftLaserPointer.scaling.y = hit.distance;
  76690. this._leftLaserPointer.position.z = -hit.distance / 2;
  76691. }
  76692. }
  76693. else {
  76694. this._gazeTracker.isVisible = false;
  76695. }
  76696. if (hit && hit.pickedMesh) {
  76697. this._currentHit = hit;
  76698. if (this._pointerDownOnMeshAsked) {
  76699. this._scene.simulatePointerMove(this._currentHit);
  76700. }
  76701. // The object selected is the floor, we're in a teleportation scenario
  76702. if (this._teleportationInitialized && this._isTeleportationFloor(hit.pickedMesh) && hit.pickedPoint) {
  76703. // Moving the teleportation area to this targetted point
  76704. //Raise onSelectedMeshUnselected observable if ray collided floor mesh/meshes and a non floor mesh was previously selected
  76705. if (this._currentMeshSelected && !this._isTeleportationFloor(this._currentMeshSelected)) {
  76706. this._notifySelectedMeshUnselected();
  76707. }
  76708. this._currentMeshSelected = null;
  76709. this._moveTeleportationSelectorTo(hit);
  76710. return;
  76711. }
  76712. // If not, we're in a selection scenario
  76713. this._hideTeleportationTarget();
  76714. this._teleportationAllowed = false;
  76715. if (hit.pickedMesh !== this._currentMeshSelected) {
  76716. if (this.meshSelectionPredicate(hit.pickedMesh)) {
  76717. this.onNewMeshPicked.notifyObservers(hit);
  76718. this._currentMeshSelected = hit.pickedMesh;
  76719. if (hit.pickedMesh.isPickable && hit.pickedMesh.actionManager) {
  76720. this.changeGazeColor(new BABYLON.Color3(0, 0, 1));
  76721. this.changeLaserColor(new BABYLON.Color3(0.2, 0.2, 1));
  76722. this._isActionableMesh = true;
  76723. }
  76724. else {
  76725. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  76726. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  76727. this._isActionableMesh = false;
  76728. }
  76729. try {
  76730. this.onNewMeshSelected.notifyObservers(this._currentMeshSelected);
  76731. }
  76732. catch (err) {
  76733. BABYLON.Tools.Warn("Error in your custom logic onNewMeshSelected: " + err);
  76734. }
  76735. }
  76736. else {
  76737. this._notifySelectedMeshUnselected();
  76738. this._currentMeshSelected = null;
  76739. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  76740. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  76741. }
  76742. }
  76743. }
  76744. else {
  76745. this._currentHit = null;
  76746. this._notifySelectedMeshUnselected();
  76747. this._currentMeshSelected = null;
  76748. this._teleportationAllowed = false;
  76749. this._hideTeleportationTarget();
  76750. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  76751. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  76752. }
  76753. };
  76754. VRExperienceHelper.prototype._notifySelectedMeshUnselected = function () {
  76755. if (this._currentMeshSelected) {
  76756. this.onSelectedMeshUnselected.notifyObservers(this._currentMeshSelected);
  76757. }
  76758. };
  76759. /**
  76760. * Sets the color of the laser ray from the vr controllers.
  76761. * @param color new color for the ray.
  76762. */
  76763. VRExperienceHelper.prototype.changeLaserColor = function (color) {
  76764. if (this._leftLaserPointer && this._leftLaserPointer.material) {
  76765. this._leftLaserPointer.material.emissiveColor = color;
  76766. }
  76767. if (this._rightLaserPointer && this._rightLaserPointer.material) {
  76768. this._rightLaserPointer.material.emissiveColor = color;
  76769. }
  76770. };
  76771. /**
  76772. * Sets the color of the ray from the vr headsets gaze.
  76773. * @param color new color for the ray.
  76774. */
  76775. VRExperienceHelper.prototype.changeGazeColor = function (color) {
  76776. if (this._gazeTracker.material) {
  76777. this._gazeTracker.material.emissiveColor = color;
  76778. }
  76779. };
  76780. /**
  76781. * Exits VR and disposes of the vr experience helper
  76782. */
  76783. VRExperienceHelper.prototype.dispose = function () {
  76784. if (this.isInVRMode) {
  76785. this.exitVR();
  76786. }
  76787. if (this._passProcessMove) {
  76788. this._passProcessMove.dispose();
  76789. }
  76790. if (this._postProcessMove) {
  76791. this._postProcessMove.dispose();
  76792. }
  76793. if (this._webVRCamera) {
  76794. this._webVRCamera.dispose();
  76795. }
  76796. if (this._vrDeviceOrientationCamera) {
  76797. this._vrDeviceOrientationCamera.dispose();
  76798. }
  76799. if (!this._useCustomVRButton && this._btnVR.parentNode) {
  76800. document.body.removeChild(this._btnVR);
  76801. }
  76802. if (this._deviceOrientationCamera && (this._scene.activeCamera != this._deviceOrientationCamera)) {
  76803. this._deviceOrientationCamera.dispose();
  76804. }
  76805. if (this._gazeTracker) {
  76806. this._gazeTracker.dispose();
  76807. }
  76808. if (this._teleportationTarget) {
  76809. this._teleportationTarget.dispose();
  76810. }
  76811. this._floorMeshesCollection = [];
  76812. document.removeEventListener("keydown", this._onKeyDown);
  76813. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  76814. window.removeEventListener("resize", this._onResize);
  76815. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  76816. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  76817. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  76818. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  76819. this._scene.getEngine().onVRDisplayChangedObservable.removeCallback(this._onVRDisplayChanged);
  76820. this._scene.getEngine().onVRRequestPresentStart.removeCallback(this._onVRRequestPresentStart);
  76821. this._scene.getEngine().onVRRequestPresentComplete.removeCallback(this._onVRRequestPresentComplete);
  76822. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  76823. this._scene.gamepadManager.onGamepadConnectedObservable.removeCallback(this._onNewGamepadConnected);
  76824. this._scene.gamepadManager.onGamepadDisconnectedObservable.removeCallback(this._onNewGamepadDisconnected);
  76825. this._scene.unregisterBeforeRender(this.beforeRender);
  76826. };
  76827. /**
  76828. * Gets the name of the VRExperienceHelper class
  76829. * @returns "VRExperienceHelper"
  76830. */
  76831. VRExperienceHelper.prototype.getClassName = function () {
  76832. return "VRExperienceHelper";
  76833. };
  76834. return VRExperienceHelper;
  76835. }());
  76836. BABYLON.VRExperienceHelper = VRExperienceHelper;
  76837. })(BABYLON || (BABYLON = {}));
  76838. //# sourceMappingURL=babylon.vrExperienceHelper.js.map
  76839. // Mainly based on these 2 articles :
  76840. // 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
  76841. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  76842. var BABYLON;
  76843. (function (BABYLON) {
  76844. var JoystickAxis;
  76845. (function (JoystickAxis) {
  76846. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  76847. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  76848. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  76849. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  76850. var VirtualJoystick = /** @class */ (function () {
  76851. function VirtualJoystick(leftJoystick) {
  76852. var _this = this;
  76853. if (leftJoystick) {
  76854. this._leftJoystick = true;
  76855. }
  76856. else {
  76857. this._leftJoystick = false;
  76858. }
  76859. VirtualJoystick._globalJoystickIndex++;
  76860. // By default left & right arrow keys are moving the X
  76861. // and up & down keys are moving the Y
  76862. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  76863. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  76864. this.reverseLeftRight = false;
  76865. this.reverseUpDown = false;
  76866. // collections of pointers
  76867. this._touches = new BABYLON.StringDictionary();
  76868. this.deltaPosition = BABYLON.Vector3.Zero();
  76869. this._joystickSensibility = 25;
  76870. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  76871. this._onResize = function (evt) {
  76872. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  76873. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  76874. if (VirtualJoystick.vjCanvas) {
  76875. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  76876. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  76877. }
  76878. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  76879. };
  76880. // injecting a canvas element on top of the canvas 3D game
  76881. if (!VirtualJoystick.vjCanvas) {
  76882. window.addEventListener("resize", this._onResize, false);
  76883. VirtualJoystick.vjCanvas = document.createElement("canvas");
  76884. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  76885. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  76886. VirtualJoystick.vjCanvas.width = window.innerWidth;
  76887. VirtualJoystick.vjCanvas.height = window.innerHeight;
  76888. VirtualJoystick.vjCanvas.style.width = "100%";
  76889. VirtualJoystick.vjCanvas.style.height = "100%";
  76890. VirtualJoystick.vjCanvas.style.position = "absolute";
  76891. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  76892. VirtualJoystick.vjCanvas.style.top = "0px";
  76893. VirtualJoystick.vjCanvas.style.left = "0px";
  76894. VirtualJoystick.vjCanvas.style.zIndex = "5";
  76895. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  76896. // Support for jQuery PEP polyfill
  76897. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  76898. var context = VirtualJoystick.vjCanvas.getContext('2d');
  76899. if (!context) {
  76900. throw new Error("Unable to create canvas for virtual joystick");
  76901. }
  76902. VirtualJoystick.vjCanvasContext = context;
  76903. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  76904. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  76905. document.body.appendChild(VirtualJoystick.vjCanvas);
  76906. }
  76907. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  76908. this.pressed = false;
  76909. // default joystick color
  76910. this._joystickColor = "cyan";
  76911. this._joystickPointerID = -1;
  76912. // current joystick position
  76913. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  76914. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  76915. // origin joystick position
  76916. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  76917. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  76918. this._onPointerDownHandlerRef = function (evt) {
  76919. _this._onPointerDown(evt);
  76920. };
  76921. this._onPointerMoveHandlerRef = function (evt) {
  76922. _this._onPointerMove(evt);
  76923. };
  76924. this._onPointerUpHandlerRef = function (evt) {
  76925. _this._onPointerUp(evt);
  76926. };
  76927. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  76928. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  76929. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  76930. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  76931. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  76932. evt.preventDefault(); // Disables system menu
  76933. }, false);
  76934. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  76935. }
  76936. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  76937. this._joystickSensibility = newJoystickSensibility;
  76938. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  76939. };
  76940. VirtualJoystick.prototype._onPointerDown = function (e) {
  76941. var positionOnScreenCondition;
  76942. e.preventDefault();
  76943. if (this._leftJoystick === true) {
  76944. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  76945. }
  76946. else {
  76947. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  76948. }
  76949. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  76950. // First contact will be dedicated to the virtual joystick
  76951. this._joystickPointerID = e.pointerId;
  76952. this._joystickPointerStartPos.x = e.clientX;
  76953. this._joystickPointerStartPos.y = e.clientY;
  76954. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  76955. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  76956. this._deltaJoystickVector.x = 0;
  76957. this._deltaJoystickVector.y = 0;
  76958. this.pressed = true;
  76959. this._touches.add(e.pointerId.toString(), e);
  76960. }
  76961. else {
  76962. // You can only trigger the action buttons with a joystick declared
  76963. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  76964. this._action();
  76965. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  76966. }
  76967. }
  76968. };
  76969. VirtualJoystick.prototype._onPointerMove = function (e) {
  76970. // If the current pointer is the one associated to the joystick (first touch contact)
  76971. if (this._joystickPointerID == e.pointerId) {
  76972. this._joystickPointerPos.x = e.clientX;
  76973. this._joystickPointerPos.y = e.clientY;
  76974. this._deltaJoystickVector = this._joystickPointerPos.clone();
  76975. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  76976. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  76977. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  76978. switch (this._axisTargetedByLeftAndRight) {
  76979. case JoystickAxis.X:
  76980. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  76981. break;
  76982. case JoystickAxis.Y:
  76983. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  76984. break;
  76985. case JoystickAxis.Z:
  76986. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  76987. break;
  76988. }
  76989. var directionUpDown = this.reverseUpDown ? 1 : -1;
  76990. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  76991. switch (this._axisTargetedByUpAndDown) {
  76992. case JoystickAxis.X:
  76993. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  76994. break;
  76995. case JoystickAxis.Y:
  76996. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  76997. break;
  76998. case JoystickAxis.Z:
  76999. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  77000. break;
  77001. }
  77002. }
  77003. else {
  77004. var data = this._touches.get(e.pointerId.toString());
  77005. if (data) {
  77006. data.x = e.clientX;
  77007. data.y = e.clientY;
  77008. }
  77009. }
  77010. };
  77011. VirtualJoystick.prototype._onPointerUp = function (e) {
  77012. if (this._joystickPointerID == e.pointerId) {
  77013. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  77014. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  77015. this._joystickPointerID = -1;
  77016. this.pressed = false;
  77017. }
  77018. else {
  77019. var touch = this._touches.get(e.pointerId.toString());
  77020. if (touch) {
  77021. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  77022. }
  77023. }
  77024. this._deltaJoystickVector.x = 0;
  77025. this._deltaJoystickVector.y = 0;
  77026. this._touches.remove(e.pointerId.toString());
  77027. };
  77028. /**
  77029. * Change the color of the virtual joystick
  77030. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  77031. */
  77032. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  77033. this._joystickColor = newColor;
  77034. };
  77035. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  77036. this._action = action;
  77037. };
  77038. // Define which axis you'd like to control for left & right
  77039. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  77040. switch (axis) {
  77041. case JoystickAxis.X:
  77042. case JoystickAxis.Y:
  77043. case JoystickAxis.Z:
  77044. this._axisTargetedByLeftAndRight = axis;
  77045. break;
  77046. default:
  77047. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  77048. break;
  77049. }
  77050. };
  77051. // Define which axis you'd like to control for up & down
  77052. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  77053. switch (axis) {
  77054. case JoystickAxis.X:
  77055. case JoystickAxis.Y:
  77056. case JoystickAxis.Z:
  77057. this._axisTargetedByUpAndDown = axis;
  77058. break;
  77059. default:
  77060. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  77061. break;
  77062. }
  77063. };
  77064. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  77065. var _this = this;
  77066. if (this.pressed) {
  77067. this._touches.forEach(function (key, touch) {
  77068. if (touch.pointerId === _this._joystickPointerID) {
  77069. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  77070. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  77071. VirtualJoystick.vjCanvasContext.beginPath();
  77072. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  77073. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  77074. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  77075. VirtualJoystick.vjCanvasContext.stroke();
  77076. VirtualJoystick.vjCanvasContext.closePath();
  77077. VirtualJoystick.vjCanvasContext.beginPath();
  77078. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  77079. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  77080. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  77081. VirtualJoystick.vjCanvasContext.stroke();
  77082. VirtualJoystick.vjCanvasContext.closePath();
  77083. VirtualJoystick.vjCanvasContext.beginPath();
  77084. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  77085. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  77086. VirtualJoystick.vjCanvasContext.stroke();
  77087. VirtualJoystick.vjCanvasContext.closePath();
  77088. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  77089. }
  77090. else {
  77091. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  77092. VirtualJoystick.vjCanvasContext.beginPath();
  77093. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  77094. VirtualJoystick.vjCanvasContext.beginPath();
  77095. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  77096. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  77097. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  77098. VirtualJoystick.vjCanvasContext.stroke();
  77099. VirtualJoystick.vjCanvasContext.closePath();
  77100. touch.prevX = touch.x;
  77101. touch.prevY = touch.y;
  77102. }
  77103. ;
  77104. });
  77105. }
  77106. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  77107. };
  77108. VirtualJoystick.prototype.releaseCanvas = function () {
  77109. if (VirtualJoystick.vjCanvas) {
  77110. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  77111. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  77112. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  77113. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  77114. window.removeEventListener("resize", this._onResize);
  77115. document.body.removeChild(VirtualJoystick.vjCanvas);
  77116. VirtualJoystick.vjCanvas = null;
  77117. }
  77118. };
  77119. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  77120. VirtualJoystick._globalJoystickIndex = 0;
  77121. return VirtualJoystick;
  77122. }());
  77123. BABYLON.VirtualJoystick = VirtualJoystick;
  77124. })(BABYLON || (BABYLON = {}));
  77125. //# sourceMappingURL=babylon.virtualJoystick.js.map
  77126. var BABYLON;
  77127. (function (BABYLON) {
  77128. // We're mainly based on the logic defined into the FreeCamera code
  77129. var VirtualJoysticksCamera = /** @class */ (function (_super) {
  77130. __extends(VirtualJoysticksCamera, _super);
  77131. function VirtualJoysticksCamera(name, position, scene) {
  77132. var _this = _super.call(this, name, position, scene) || this;
  77133. _this.inputs.addVirtualJoystick();
  77134. return _this;
  77135. }
  77136. VirtualJoysticksCamera.prototype.getClassName = function () {
  77137. return "VirtualJoysticksCamera";
  77138. };
  77139. return VirtualJoysticksCamera;
  77140. }(BABYLON.FreeCamera));
  77141. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  77142. })(BABYLON || (BABYLON = {}));
  77143. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  77144. var BABYLON;
  77145. (function (BABYLON) {
  77146. var FreeCameraVirtualJoystickInput = /** @class */ (function () {
  77147. function FreeCameraVirtualJoystickInput() {
  77148. }
  77149. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  77150. return this._leftjoystick;
  77151. };
  77152. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  77153. return this._rightjoystick;
  77154. };
  77155. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  77156. if (this._leftjoystick) {
  77157. var camera = this.camera;
  77158. var speed = camera._computeLocalCameraSpeed() * 50;
  77159. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  77160. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  77161. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  77162. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  77163. if (!this._leftjoystick.pressed) {
  77164. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  77165. }
  77166. if (!this._rightjoystick.pressed) {
  77167. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  77168. }
  77169. }
  77170. };
  77171. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  77172. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  77173. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  77174. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  77175. this._leftjoystick.setJoystickSensibility(0.15);
  77176. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  77177. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  77178. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  77179. this._rightjoystick.reverseUpDown = true;
  77180. this._rightjoystick.setJoystickSensibility(0.05);
  77181. this._rightjoystick.setJoystickColor("yellow");
  77182. };
  77183. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  77184. this._leftjoystick.releaseCanvas();
  77185. this._rightjoystick.releaseCanvas();
  77186. };
  77187. FreeCameraVirtualJoystickInput.prototype.getClassName = function () {
  77188. return "FreeCameraVirtualJoystickInput";
  77189. };
  77190. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  77191. return "virtualJoystick";
  77192. };
  77193. return FreeCameraVirtualJoystickInput;
  77194. }());
  77195. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  77196. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  77197. })(BABYLON || (BABYLON = {}));
  77198. //# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map
  77199. var BABYLON;
  77200. (function (BABYLON) {
  77201. var SimplificationSettings = /** @class */ (function () {
  77202. function SimplificationSettings(quality, distance, optimizeMesh) {
  77203. this.quality = quality;
  77204. this.distance = distance;
  77205. this.optimizeMesh = optimizeMesh;
  77206. }
  77207. return SimplificationSettings;
  77208. }());
  77209. BABYLON.SimplificationSettings = SimplificationSettings;
  77210. var SimplificationQueue = /** @class */ (function () {
  77211. function SimplificationQueue() {
  77212. this.running = false;
  77213. this._simplificationArray = [];
  77214. }
  77215. SimplificationQueue.prototype.addTask = function (task) {
  77216. this._simplificationArray.push(task);
  77217. };
  77218. SimplificationQueue.prototype.executeNext = function () {
  77219. var task = this._simplificationArray.pop();
  77220. if (task) {
  77221. this.running = true;
  77222. this.runSimplification(task);
  77223. }
  77224. else {
  77225. this.running = false;
  77226. }
  77227. };
  77228. SimplificationQueue.prototype.runSimplification = function (task) {
  77229. var _this = this;
  77230. if (task.parallelProcessing) {
  77231. //parallel simplifier
  77232. task.settings.forEach(function (setting) {
  77233. var simplifier = _this.getSimplifier(task);
  77234. simplifier.simplify(setting, function (newMesh) {
  77235. task.mesh.addLODLevel(setting.distance, newMesh);
  77236. newMesh.isVisible = true;
  77237. //check if it is the last
  77238. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  77239. //all done, run the success callback.
  77240. task.successCallback();
  77241. }
  77242. _this.executeNext();
  77243. });
  77244. });
  77245. }
  77246. else {
  77247. //single simplifier.
  77248. var simplifier = this.getSimplifier(task);
  77249. var runDecimation = function (setting, callback) {
  77250. simplifier.simplify(setting, function (newMesh) {
  77251. task.mesh.addLODLevel(setting.distance, newMesh);
  77252. newMesh.isVisible = true;
  77253. //run the next quality level
  77254. callback();
  77255. });
  77256. };
  77257. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  77258. runDecimation(task.settings[loop.index], function () {
  77259. loop.executeNext();
  77260. });
  77261. }, function () {
  77262. //execution ended, run the success callback.
  77263. if (task.successCallback) {
  77264. task.successCallback();
  77265. }
  77266. _this.executeNext();
  77267. });
  77268. }
  77269. };
  77270. SimplificationQueue.prototype.getSimplifier = function (task) {
  77271. switch (task.simplificationType) {
  77272. case SimplificationType.QUADRATIC:
  77273. default:
  77274. return new QuadraticErrorSimplification(task.mesh);
  77275. }
  77276. };
  77277. return SimplificationQueue;
  77278. }());
  77279. BABYLON.SimplificationQueue = SimplificationQueue;
  77280. /**
  77281. * The implemented types of simplification.
  77282. * At the moment only Quadratic Error Decimation is implemented.
  77283. */
  77284. var SimplificationType;
  77285. (function (SimplificationType) {
  77286. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  77287. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  77288. var DecimationTriangle = /** @class */ (function () {
  77289. function DecimationTriangle(vertices) {
  77290. this.vertices = vertices;
  77291. this.error = new Array(4);
  77292. this.deleted = false;
  77293. this.isDirty = false;
  77294. this.deletePending = false;
  77295. this.borderFactor = 0;
  77296. }
  77297. return DecimationTriangle;
  77298. }());
  77299. BABYLON.DecimationTriangle = DecimationTriangle;
  77300. var DecimationVertex = /** @class */ (function () {
  77301. function DecimationVertex(position, id) {
  77302. this.position = position;
  77303. this.id = id;
  77304. this.isBorder = true;
  77305. this.q = new QuadraticMatrix();
  77306. this.triangleCount = 0;
  77307. this.triangleStart = 0;
  77308. this.originalOffsets = [];
  77309. }
  77310. DecimationVertex.prototype.updatePosition = function (newPosition) {
  77311. this.position.copyFrom(newPosition);
  77312. };
  77313. return DecimationVertex;
  77314. }());
  77315. BABYLON.DecimationVertex = DecimationVertex;
  77316. var QuadraticMatrix = /** @class */ (function () {
  77317. function QuadraticMatrix(data) {
  77318. this.data = new Array(10);
  77319. for (var i = 0; i < 10; ++i) {
  77320. if (data && data[i]) {
  77321. this.data[i] = data[i];
  77322. }
  77323. else {
  77324. this.data[i] = 0;
  77325. }
  77326. }
  77327. }
  77328. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  77329. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  77330. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  77331. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  77332. return det;
  77333. };
  77334. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  77335. for (var i = 0; i < 10; ++i) {
  77336. this.data[i] += matrix.data[i];
  77337. }
  77338. };
  77339. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  77340. for (var i = 0; i < 10; ++i) {
  77341. this.data[i] += data[i];
  77342. }
  77343. };
  77344. QuadraticMatrix.prototype.add = function (matrix) {
  77345. var m = new QuadraticMatrix();
  77346. for (var i = 0; i < 10; ++i) {
  77347. m.data[i] = this.data[i] + matrix.data[i];
  77348. }
  77349. return m;
  77350. };
  77351. QuadraticMatrix.FromData = function (a, b, c, d) {
  77352. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  77353. };
  77354. //returning an array to avoid garbage collection
  77355. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  77356. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  77357. };
  77358. return QuadraticMatrix;
  77359. }());
  77360. BABYLON.QuadraticMatrix = QuadraticMatrix;
  77361. var Reference = /** @class */ (function () {
  77362. function Reference(vertexId, triangleId) {
  77363. this.vertexId = vertexId;
  77364. this.triangleId = triangleId;
  77365. }
  77366. return Reference;
  77367. }());
  77368. BABYLON.Reference = Reference;
  77369. /**
  77370. * An implementation of the Quadratic Error simplification algorithm.
  77371. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  77372. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  77373. * @author RaananW
  77374. */
  77375. var QuadraticErrorSimplification = /** @class */ (function () {
  77376. function QuadraticErrorSimplification(_mesh) {
  77377. this._mesh = _mesh;
  77378. this.syncIterations = 5000;
  77379. this.aggressiveness = 7;
  77380. this.decimationIterations = 100;
  77381. this.boundingBoxEpsilon = BABYLON.Epsilon;
  77382. }
  77383. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  77384. var _this = this;
  77385. this.initDecimatedMesh();
  77386. //iterating through the submeshes array, one after the other.
  77387. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  77388. _this.initWithMesh(loop.index, function () {
  77389. _this.runDecimation(settings, loop.index, function () {
  77390. loop.executeNext();
  77391. });
  77392. }, settings.optimizeMesh);
  77393. }, function () {
  77394. setTimeout(function () {
  77395. successCallback(_this._reconstructedMesh);
  77396. }, 0);
  77397. });
  77398. };
  77399. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  77400. var _this = this;
  77401. var targetCount = ~~(this.triangles.length * settings.quality);
  77402. var deletedTriangles = 0;
  77403. var triangleCount = this.triangles.length;
  77404. var iterationFunction = function (iteration, callback) {
  77405. setTimeout(function () {
  77406. if (iteration % 5 === 0) {
  77407. _this.updateMesh(iteration === 0);
  77408. }
  77409. for (var i = 0; i < _this.triangles.length; ++i) {
  77410. _this.triangles[i].isDirty = false;
  77411. }
  77412. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  77413. var trianglesIterator = function (i) {
  77414. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  77415. var t = _this.triangles[tIdx];
  77416. if (!t)
  77417. return;
  77418. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  77419. return;
  77420. }
  77421. for (var j = 0; j < 3; ++j) {
  77422. if (t.error[j] < threshold) {
  77423. var deleted0 = [];
  77424. var deleted1 = [];
  77425. var v0 = t.vertices[j];
  77426. var v1 = t.vertices[(j + 1) % 3];
  77427. if (v0.isBorder || v1.isBorder)
  77428. continue;
  77429. var p = BABYLON.Vector3.Zero();
  77430. var n = BABYLON.Vector3.Zero();
  77431. var uv = BABYLON.Vector2.Zero();
  77432. var color = new BABYLON.Color4(0, 0, 0, 1);
  77433. _this.calculateError(v0, v1, p, n, uv, color);
  77434. var delTr = new Array();
  77435. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  77436. continue;
  77437. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  77438. continue;
  77439. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  77440. continue;
  77441. var uniqueArray = new Array();
  77442. delTr.forEach(function (deletedT) {
  77443. if (uniqueArray.indexOf(deletedT) === -1) {
  77444. deletedT.deletePending = true;
  77445. uniqueArray.push(deletedT);
  77446. }
  77447. });
  77448. if (uniqueArray.length % 2 !== 0) {
  77449. continue;
  77450. }
  77451. v0.q = v1.q.add(v0.q);
  77452. v0.updatePosition(p);
  77453. var tStart = _this.references.length;
  77454. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  77455. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  77456. var tCount = _this.references.length - tStart;
  77457. if (tCount <= v0.triangleCount) {
  77458. if (tCount) {
  77459. for (var c = 0; c < tCount; c++) {
  77460. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  77461. }
  77462. }
  77463. }
  77464. else {
  77465. v0.triangleStart = tStart;
  77466. }
  77467. v0.triangleCount = tCount;
  77468. break;
  77469. }
  77470. }
  77471. };
  77472. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  77473. }, 0);
  77474. };
  77475. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  77476. if (triangleCount - deletedTriangles <= targetCount)
  77477. loop.breakLoop();
  77478. else {
  77479. iterationFunction(loop.index, function () {
  77480. loop.executeNext();
  77481. });
  77482. }
  77483. }, function () {
  77484. setTimeout(function () {
  77485. //reconstruct this part of the mesh
  77486. _this.reconstructMesh(submeshIndex);
  77487. successCallback();
  77488. }, 0);
  77489. });
  77490. };
  77491. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  77492. var _this = this;
  77493. this.vertices = [];
  77494. this.triangles = [];
  77495. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  77496. var indices = this._mesh.getIndices();
  77497. var submesh = this._mesh.subMeshes[submeshIndex];
  77498. var findInVertices = function (positionToSearch) {
  77499. if (optimizeMesh) {
  77500. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  77501. if (_this.vertices[ii].position.equals(positionToSearch)) {
  77502. return _this.vertices[ii];
  77503. }
  77504. }
  77505. }
  77506. return null;
  77507. };
  77508. var vertexReferences = [];
  77509. var vertexInit = function (i) {
  77510. if (!positionData) {
  77511. return;
  77512. }
  77513. var offset = i + submesh.verticesStart;
  77514. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  77515. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  77516. vertex.originalOffsets.push(offset);
  77517. if (vertex.id === _this.vertices.length) {
  77518. _this.vertices.push(vertex);
  77519. }
  77520. vertexReferences.push(vertex.id);
  77521. };
  77522. //var totalVertices = mesh.getTotalVertices();
  77523. var totalVertices = submesh.verticesCount;
  77524. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  77525. var indicesInit = function (i) {
  77526. if (!indices) {
  77527. return;
  77528. }
  77529. var offset = (submesh.indexStart / 3) + i;
  77530. var pos = (offset * 3);
  77531. var i0 = indices[pos + 0];
  77532. var i1 = indices[pos + 1];
  77533. var i2 = indices[pos + 2];
  77534. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  77535. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  77536. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  77537. var triangle = new DecimationTriangle([v0, v1, v2]);
  77538. triangle.originalOffset = pos;
  77539. _this.triangles.push(triangle);
  77540. };
  77541. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  77542. _this.init(callback);
  77543. });
  77544. });
  77545. };
  77546. QuadraticErrorSimplification.prototype.init = function (callback) {
  77547. var _this = this;
  77548. var triangleInit1 = function (i) {
  77549. var t = _this.triangles[i];
  77550. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  77551. for (var j = 0; j < 3; j++) {
  77552. 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))));
  77553. }
  77554. };
  77555. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  77556. var triangleInit2 = function (i) {
  77557. var t = _this.triangles[i];
  77558. for (var j = 0; j < 3; ++j) {
  77559. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  77560. }
  77561. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  77562. };
  77563. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  77564. callback();
  77565. });
  77566. });
  77567. };
  77568. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  77569. var newTriangles = [];
  77570. var i;
  77571. for (i = 0; i < this.vertices.length; ++i) {
  77572. this.vertices[i].triangleCount = 0;
  77573. }
  77574. var t;
  77575. var j;
  77576. for (i = 0; i < this.triangles.length; ++i) {
  77577. if (!this.triangles[i].deleted) {
  77578. t = this.triangles[i];
  77579. for (j = 0; j < 3; ++j) {
  77580. t.vertices[j].triangleCount = 1;
  77581. }
  77582. newTriangles.push(t);
  77583. }
  77584. }
  77585. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  77586. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  77587. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  77588. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  77589. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  77590. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  77591. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  77592. var vertexCount = 0;
  77593. for (i = 0; i < this.vertices.length; ++i) {
  77594. var vertex = this.vertices[i];
  77595. vertex.id = vertexCount;
  77596. if (vertex.triangleCount) {
  77597. vertex.originalOffsets.forEach(function (originalOffset) {
  77598. if (!normalData) {
  77599. return;
  77600. }
  77601. newPositionData.push(vertex.position.x);
  77602. newPositionData.push(vertex.position.y);
  77603. newPositionData.push(vertex.position.z);
  77604. newNormalData.push(normalData[originalOffset * 3]);
  77605. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  77606. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  77607. if (uvs && uvs.length) {
  77608. newUVsData.push(uvs[(originalOffset * 2)]);
  77609. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  77610. }
  77611. else if (colorsData && colorsData.length) {
  77612. newColorsData.push(colorsData[(originalOffset * 4)]);
  77613. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  77614. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  77615. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  77616. }
  77617. ++vertexCount;
  77618. });
  77619. }
  77620. }
  77621. var startingIndex = this._reconstructedMesh.getTotalIndices();
  77622. var startingVertex = this._reconstructedMesh.getTotalVertices();
  77623. var submeshesArray = this._reconstructedMesh.subMeshes;
  77624. this._reconstructedMesh.subMeshes = [];
  77625. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  77626. var originalIndices = this._mesh.getIndices();
  77627. for (i = 0; i < newTriangles.length; ++i) {
  77628. t = newTriangles[i]; //now get the new referencing point for each vertex
  77629. [0, 1, 2].forEach(function (idx) {
  77630. var id = originalIndices[t.originalOffset + idx];
  77631. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  77632. if (offset < 0)
  77633. offset = 0;
  77634. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  77635. });
  77636. }
  77637. //overwriting the old vertex buffers and indices.
  77638. this._reconstructedMesh.setIndices(newIndicesArray);
  77639. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  77640. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  77641. if (newUVsData.length > 0)
  77642. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  77643. if (newColorsData.length > 0)
  77644. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  77645. //create submesh
  77646. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  77647. if (submeshIndex > 0) {
  77648. this._reconstructedMesh.subMeshes = [];
  77649. submeshesArray.forEach(function (submesh) {
  77650. BABYLON.SubMesh.AddToMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  77651. });
  77652. BABYLON.SubMesh.AddToMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  77653. }
  77654. };
  77655. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  77656. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  77657. this._reconstructedMesh.material = this._mesh.material;
  77658. this._reconstructedMesh.parent = this._mesh.parent;
  77659. this._reconstructedMesh.isVisible = false;
  77660. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  77661. };
  77662. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  77663. for (var i = 0; i < vertex1.triangleCount; ++i) {
  77664. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  77665. if (t.deleted)
  77666. continue;
  77667. var s = this.references[vertex1.triangleStart + i].vertexId;
  77668. var v1 = t.vertices[(s + 1) % 3];
  77669. var v2 = t.vertices[(s + 2) % 3];
  77670. if ((v1 === vertex2 || v2 === vertex2)) {
  77671. deletedArray[i] = true;
  77672. delTr.push(t);
  77673. continue;
  77674. }
  77675. var d1 = v1.position.subtract(point);
  77676. d1 = d1.normalize();
  77677. var d2 = v2.position.subtract(point);
  77678. d2 = d2.normalize();
  77679. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  77680. return true;
  77681. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  77682. deletedArray[i] = false;
  77683. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  77684. return true;
  77685. }
  77686. return false;
  77687. };
  77688. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  77689. var newDeleted = deletedTriangles;
  77690. for (var i = 0; i < vertex.triangleCount; ++i) {
  77691. var ref = this.references[vertex.triangleStart + i];
  77692. var t = this.triangles[ref.triangleId];
  77693. if (t.deleted)
  77694. continue;
  77695. if (deletedArray[i] && t.deletePending) {
  77696. t.deleted = true;
  77697. newDeleted++;
  77698. continue;
  77699. }
  77700. t.vertices[ref.vertexId] = origVertex;
  77701. t.isDirty = true;
  77702. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  77703. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  77704. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  77705. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  77706. this.references.push(ref);
  77707. }
  77708. return newDeleted;
  77709. };
  77710. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  77711. for (var i = 0; i < this.vertices.length; ++i) {
  77712. var vCount = [];
  77713. var vId = [];
  77714. var v = this.vertices[i];
  77715. var j;
  77716. for (j = 0; j < v.triangleCount; ++j) {
  77717. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  77718. for (var ii = 0; ii < 3; ii++) {
  77719. var ofs = 0;
  77720. var vv = triangle.vertices[ii];
  77721. while (ofs < vCount.length) {
  77722. if (vId[ofs] === vv.id)
  77723. break;
  77724. ++ofs;
  77725. }
  77726. if (ofs === vCount.length) {
  77727. vCount.push(1);
  77728. vId.push(vv.id);
  77729. }
  77730. else {
  77731. vCount[ofs]++;
  77732. }
  77733. }
  77734. }
  77735. for (j = 0; j < vCount.length; ++j) {
  77736. if (vCount[j] === 1) {
  77737. this.vertices[vId[j]].isBorder = true;
  77738. }
  77739. else {
  77740. this.vertices[vId[j]].isBorder = false;
  77741. }
  77742. }
  77743. }
  77744. };
  77745. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  77746. if (identifyBorders === void 0) { identifyBorders = false; }
  77747. var i;
  77748. if (!identifyBorders) {
  77749. var newTrianglesVector = [];
  77750. for (i = 0; i < this.triangles.length; ++i) {
  77751. if (!this.triangles[i].deleted) {
  77752. newTrianglesVector.push(this.triangles[i]);
  77753. }
  77754. }
  77755. this.triangles = newTrianglesVector;
  77756. }
  77757. for (i = 0; i < this.vertices.length; ++i) {
  77758. this.vertices[i].triangleCount = 0;
  77759. this.vertices[i].triangleStart = 0;
  77760. }
  77761. var t;
  77762. var j;
  77763. var v;
  77764. for (i = 0; i < this.triangles.length; ++i) {
  77765. t = this.triangles[i];
  77766. for (j = 0; j < 3; ++j) {
  77767. v = t.vertices[j];
  77768. v.triangleCount++;
  77769. }
  77770. }
  77771. var tStart = 0;
  77772. for (i = 0; i < this.vertices.length; ++i) {
  77773. this.vertices[i].triangleStart = tStart;
  77774. tStart += this.vertices[i].triangleCount;
  77775. this.vertices[i].triangleCount = 0;
  77776. }
  77777. var newReferences = new Array(this.triangles.length * 3);
  77778. for (i = 0; i < this.triangles.length; ++i) {
  77779. t = this.triangles[i];
  77780. for (j = 0; j < 3; ++j) {
  77781. v = t.vertices[j];
  77782. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  77783. v.triangleCount++;
  77784. }
  77785. }
  77786. this.references = newReferences;
  77787. if (identifyBorders) {
  77788. this.identifyBorder();
  77789. }
  77790. };
  77791. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  77792. var x = point.x;
  77793. var y = point.y;
  77794. var z = point.z;
  77795. 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
  77796. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  77797. };
  77798. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  77799. var q = vertex1.q.add(vertex2.q);
  77800. var border = vertex1.isBorder && vertex2.isBorder;
  77801. var error = 0;
  77802. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  77803. if (qDet !== 0 && !border) {
  77804. if (!pointResult) {
  77805. pointResult = BABYLON.Vector3.Zero();
  77806. }
  77807. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  77808. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  77809. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  77810. error = this.vertexError(q, pointResult);
  77811. }
  77812. else {
  77813. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  77814. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  77815. var error1 = this.vertexError(q, vertex1.position);
  77816. var error2 = this.vertexError(q, vertex2.position);
  77817. var error3 = this.vertexError(q, p3);
  77818. error = Math.min(error1, error2, error3);
  77819. if (error === error1) {
  77820. if (pointResult) {
  77821. pointResult.copyFrom(vertex1.position);
  77822. }
  77823. }
  77824. else if (error === error2) {
  77825. if (pointResult) {
  77826. pointResult.copyFrom(vertex2.position);
  77827. }
  77828. }
  77829. else {
  77830. if (pointResult) {
  77831. pointResult.copyFrom(p3);
  77832. }
  77833. }
  77834. }
  77835. return error;
  77836. };
  77837. return QuadraticErrorSimplification;
  77838. }());
  77839. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  77840. })(BABYLON || (BABYLON = {}));
  77841. //# sourceMappingURL=babylon.meshSimplification.js.map
  77842. var BABYLON;
  77843. (function (BABYLON) {
  77844. var MeshLODLevel = /** @class */ (function () {
  77845. function MeshLODLevel(distance, mesh) {
  77846. this.distance = distance;
  77847. this.mesh = mesh;
  77848. }
  77849. return MeshLODLevel;
  77850. }());
  77851. BABYLON.MeshLODLevel = MeshLODLevel;
  77852. })(BABYLON || (BABYLON = {}));
  77853. //# sourceMappingURL=babylon.meshLODLevel.js.map
  77854. var BABYLON;
  77855. (function (BABYLON) {
  77856. /**
  77857. * Defines the root class used to create scene optimization to use with SceneOptimizer
  77858. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  77859. */
  77860. var SceneOptimization = /** @class */ (function () {
  77861. /**
  77862. * Creates the SceneOptimization object
  77863. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  77864. * @param desc defines the description associated with the optimization
  77865. */
  77866. function SceneOptimization(
  77867. /**
  77868. * Defines the priority of this optimization (0 by default which means first in the list)
  77869. */
  77870. priority) {
  77871. if (priority === void 0) { priority = 0; }
  77872. this.priority = priority;
  77873. }
  77874. /**
  77875. * Gets a string describing the action executed by the current optimization
  77876. * @returns description string
  77877. */
  77878. SceneOptimization.prototype.getDescription = function () {
  77879. return "";
  77880. };
  77881. /**
  77882. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  77883. * @param scene defines the current scene where to apply this optimization
  77884. * @param optimizer defines the current optimizer
  77885. * @returns true if everything that can be done was applied
  77886. */
  77887. SceneOptimization.prototype.apply = function (scene, optimizer) {
  77888. return true;
  77889. };
  77890. ;
  77891. return SceneOptimization;
  77892. }());
  77893. BABYLON.SceneOptimization = SceneOptimization;
  77894. /**
  77895. * Defines an optimization used to reduce the size of render target textures
  77896. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  77897. */
  77898. var TextureOptimization = /** @class */ (function (_super) {
  77899. __extends(TextureOptimization, _super);
  77900. /**
  77901. * Creates the TextureOptimization object
  77902. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  77903. * @param maximumSize defines the maximum sized allowed for textures (1024 is the default value). If a texture is bigger, it will be scaled down using a factor defined by the step parameter
  77904. * @param step defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  77905. */
  77906. function TextureOptimization(
  77907. /**
  77908. * Defines the priority of this optimization (0 by default which means first in the list)
  77909. */
  77910. priority,
  77911. /**
  77912. * Defines the maximum sized allowed for textures (1024 is the default value). If a texture is bigger, it will be scaled down using a factor defined by the step parameter
  77913. */
  77914. maximumSize,
  77915. /**
  77916. * Defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  77917. */
  77918. step) {
  77919. if (priority === void 0) { priority = 0; }
  77920. if (maximumSize === void 0) { maximumSize = 1024; }
  77921. if (step === void 0) { step = 0.5; }
  77922. var _this = _super.call(this, priority) || this;
  77923. _this.priority = priority;
  77924. _this.maximumSize = maximumSize;
  77925. _this.step = step;
  77926. return _this;
  77927. }
  77928. /**
  77929. * Gets a string describing the action executed by the current optimization
  77930. * @returns description string
  77931. */
  77932. TextureOptimization.prototype.getDescription = function () {
  77933. return "Reducing render target texture size to " + this.maximumSize;
  77934. };
  77935. /**
  77936. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  77937. * @param scene defines the current scene where to apply this optimization
  77938. * @param optimizer defines the current optimizer
  77939. * @returns true if everything that can be done was applied
  77940. */
  77941. TextureOptimization.prototype.apply = function (scene, optimizer) {
  77942. var allDone = true;
  77943. for (var index = 0; index < scene.textures.length; index++) {
  77944. var texture = scene.textures[index];
  77945. if (!texture.canRescale || texture.getContext) {
  77946. continue;
  77947. }
  77948. var currentSize = texture.getSize();
  77949. var maxDimension = Math.max(currentSize.width, currentSize.height);
  77950. if (maxDimension > this.maximumSize) {
  77951. texture.scale(this.step);
  77952. allDone = false;
  77953. }
  77954. }
  77955. return allDone;
  77956. };
  77957. return TextureOptimization;
  77958. }(SceneOptimization));
  77959. BABYLON.TextureOptimization = TextureOptimization;
  77960. /**
  77961. * Defines an optimization used to increase or decrease the rendering resolution
  77962. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  77963. */
  77964. var HardwareScalingOptimization = /** @class */ (function (_super) {
  77965. __extends(HardwareScalingOptimization, _super);
  77966. /**
  77967. * Creates the HardwareScalingOptimization object
  77968. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  77969. * @param maximumScale defines the maximum scale to use (2 by default)
  77970. * @param step defines the step to use between two passes (0.5 by default)
  77971. */
  77972. function HardwareScalingOptimization(
  77973. /**
  77974. * Defines the priority of this optimization (0 by default which means first in the list)
  77975. */
  77976. priority,
  77977. /**
  77978. * Defines the maximum scale to use (2 by default)
  77979. */
  77980. maximumScale,
  77981. /**
  77982. * Defines the step to use between two passes (0.5 by default)
  77983. */
  77984. step) {
  77985. if (priority === void 0) { priority = 0; }
  77986. if (maximumScale === void 0) { maximumScale = 2; }
  77987. if (step === void 0) { step = 0.25; }
  77988. var _this = _super.call(this, priority) || this;
  77989. _this.priority = priority;
  77990. _this.maximumScale = maximumScale;
  77991. _this.step = step;
  77992. _this._currentScale = -1;
  77993. _this._directionOffset = 1;
  77994. return _this;
  77995. }
  77996. /**
  77997. * Gets a string describing the action executed by the current optimization
  77998. * @return description string
  77999. */
  78000. HardwareScalingOptimization.prototype.getDescription = function () {
  78001. return "Setting hardware scaling level to " + this._currentScale;
  78002. };
  78003. /**
  78004. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  78005. * @param scene defines the current scene where to apply this optimization
  78006. * @param optimizer defines the current optimizer
  78007. * @returns true if everything that can be done was applied
  78008. */
  78009. HardwareScalingOptimization.prototype.apply = function (scene, optimizer) {
  78010. if (this._currentScale === -1) {
  78011. this._currentScale = scene.getEngine().getHardwareScalingLevel();
  78012. if (this._currentScale > this.maximumScale) {
  78013. this._directionOffset = -1;
  78014. }
  78015. }
  78016. this._currentScale += this._directionOffset * this.step;
  78017. scene.getEngine().setHardwareScalingLevel(this._currentScale);
  78018. return this._directionOffset === 1 ? this._currentScale >= this.maximumScale : this._currentScale <= this.maximumScale;
  78019. };
  78020. ;
  78021. return HardwareScalingOptimization;
  78022. }(SceneOptimization));
  78023. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  78024. /**
  78025. * Defines an optimization used to remove shadows
  78026. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  78027. */
  78028. var ShadowsOptimization = /** @class */ (function (_super) {
  78029. __extends(ShadowsOptimization, _super);
  78030. function ShadowsOptimization() {
  78031. return _super !== null && _super.apply(this, arguments) || this;
  78032. }
  78033. /**
  78034. * Gets a string describing the action executed by the current optimization
  78035. * @return description string
  78036. */
  78037. ShadowsOptimization.prototype.getDescription = function () {
  78038. return "Turning shadows on/off";
  78039. };
  78040. /**
  78041. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  78042. * @param scene defines the current scene where to apply this optimization
  78043. * @param optimizer defines the current optimizer
  78044. * @returns true if everything that can be done was applied
  78045. */
  78046. ShadowsOptimization.prototype.apply = function (scene, optimizer) {
  78047. scene.shadowsEnabled = optimizer.isInImprovementMode;
  78048. return true;
  78049. };
  78050. ;
  78051. return ShadowsOptimization;
  78052. }(SceneOptimization));
  78053. BABYLON.ShadowsOptimization = ShadowsOptimization;
  78054. /**
  78055. * Defines an optimization used to turn post-processes off
  78056. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  78057. */
  78058. var PostProcessesOptimization = /** @class */ (function (_super) {
  78059. __extends(PostProcessesOptimization, _super);
  78060. function PostProcessesOptimization() {
  78061. return _super !== null && _super.apply(this, arguments) || this;
  78062. }
  78063. /**
  78064. * Gets a string describing the action executed by the current optimization
  78065. * @return description string
  78066. */
  78067. PostProcessesOptimization.prototype.getDescription = function () {
  78068. return "Turning post-processes on/off";
  78069. };
  78070. /**
  78071. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  78072. * @param scene defines the current scene where to apply this optimization
  78073. * @param optimizer defines the current optimizer
  78074. * @returns true if everything that can be done was applied
  78075. */
  78076. PostProcessesOptimization.prototype.apply = function (scene, optimizer) {
  78077. scene.postProcessesEnabled = optimizer.isInImprovementMode;
  78078. return true;
  78079. };
  78080. ;
  78081. return PostProcessesOptimization;
  78082. }(SceneOptimization));
  78083. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  78084. /**
  78085. * Defines an optimization used to turn lens flares off
  78086. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  78087. */
  78088. var LensFlaresOptimization = /** @class */ (function (_super) {
  78089. __extends(LensFlaresOptimization, _super);
  78090. function LensFlaresOptimization() {
  78091. return _super !== null && _super.apply(this, arguments) || this;
  78092. }
  78093. /**
  78094. * Gets a string describing the action executed by the current optimization
  78095. * @return description string
  78096. */
  78097. LensFlaresOptimization.prototype.getDescription = function () {
  78098. return "Turning lens flares on/off";
  78099. };
  78100. /**
  78101. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  78102. * @param scene defines the current scene where to apply this optimization
  78103. * @param optimizer defines the current optimizer
  78104. * @returns true if everything that can be done was applied
  78105. */
  78106. LensFlaresOptimization.prototype.apply = function (scene, optimizer) {
  78107. scene.lensFlaresEnabled = optimizer.isInImprovementMode;
  78108. return true;
  78109. };
  78110. ;
  78111. return LensFlaresOptimization;
  78112. }(SceneOptimization));
  78113. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  78114. /**
  78115. * Defines an optimization based on user defined callback.
  78116. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  78117. */
  78118. var CustomOptimization = /** @class */ (function (_super) {
  78119. __extends(CustomOptimization, _super);
  78120. function CustomOptimization() {
  78121. return _super !== null && _super.apply(this, arguments) || this;
  78122. }
  78123. /**
  78124. * Gets a string describing the action executed by the current optimization
  78125. * @returns description string
  78126. */
  78127. CustomOptimization.prototype.getDescription = function () {
  78128. if (this.onGetDescription) {
  78129. return this.onGetDescription();
  78130. }
  78131. return "Running user defined callback";
  78132. };
  78133. /**
  78134. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  78135. * @param scene defines the current scene where to apply this optimization
  78136. * @param optimizer defines the current optimizer
  78137. * @returns true if everything that can be done was applied
  78138. */
  78139. CustomOptimization.prototype.apply = function (scene, optimizer) {
  78140. if (this.onApply) {
  78141. return this.onApply(scene, optimizer);
  78142. }
  78143. return true;
  78144. };
  78145. ;
  78146. return CustomOptimization;
  78147. }(SceneOptimization));
  78148. BABYLON.CustomOptimization = CustomOptimization;
  78149. /**
  78150. * Defines an optimization used to turn particles off
  78151. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  78152. */
  78153. var ParticlesOptimization = /** @class */ (function (_super) {
  78154. __extends(ParticlesOptimization, _super);
  78155. function ParticlesOptimization() {
  78156. return _super !== null && _super.apply(this, arguments) || this;
  78157. }
  78158. /**
  78159. * Gets a string describing the action executed by the current optimization
  78160. * @return description string
  78161. */
  78162. ParticlesOptimization.prototype.getDescription = function () {
  78163. return "Turning particles on/off";
  78164. };
  78165. /**
  78166. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  78167. * @param scene defines the current scene where to apply this optimization
  78168. * @param optimizer defines the current optimizer
  78169. * @returns true if everything that can be done was applied
  78170. */
  78171. ParticlesOptimization.prototype.apply = function (scene, optimizer) {
  78172. scene.particlesEnabled = optimizer.isInImprovementMode;
  78173. return true;
  78174. };
  78175. ;
  78176. return ParticlesOptimization;
  78177. }(SceneOptimization));
  78178. BABYLON.ParticlesOptimization = ParticlesOptimization;
  78179. /**
  78180. * Defines an optimization used to turn render targets off
  78181. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  78182. */
  78183. var RenderTargetsOptimization = /** @class */ (function (_super) {
  78184. __extends(RenderTargetsOptimization, _super);
  78185. function RenderTargetsOptimization() {
  78186. return _super !== null && _super.apply(this, arguments) || this;
  78187. }
  78188. /**
  78189. * Gets a string describing the action executed by the current optimization
  78190. * @return description string
  78191. */
  78192. RenderTargetsOptimization.prototype.getDescription = function () {
  78193. return "Turning render targets off";
  78194. };
  78195. /**
  78196. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  78197. * @param scene defines the current scene where to apply this optimization
  78198. * @param optimizer defines the current optimizer
  78199. * @returns true if everything that can be done was applied
  78200. */
  78201. RenderTargetsOptimization.prototype.apply = function (scene, optimizer) {
  78202. scene.renderTargetsEnabled = optimizer.isInImprovementMode;
  78203. return true;
  78204. };
  78205. ;
  78206. return RenderTargetsOptimization;
  78207. }(SceneOptimization));
  78208. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  78209. /**
  78210. * Defines an optimization used to merge meshes with compatible materials
  78211. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  78212. */
  78213. var MergeMeshesOptimization = /** @class */ (function (_super) {
  78214. __extends(MergeMeshesOptimization, _super);
  78215. function MergeMeshesOptimization() {
  78216. var _this = _super !== null && _super.apply(this, arguments) || this;
  78217. _this._canBeMerged = function (abstractMesh) {
  78218. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  78219. return false;
  78220. }
  78221. var mesh = abstractMesh;
  78222. if (!mesh.isVisible || !mesh.isEnabled()) {
  78223. return false;
  78224. }
  78225. if (mesh.instances.length > 0) {
  78226. return false;
  78227. }
  78228. if (mesh.skeleton || mesh.hasLODLevels) {
  78229. return false;
  78230. }
  78231. if (mesh.parent) {
  78232. return false;
  78233. }
  78234. return true;
  78235. };
  78236. return _this;
  78237. }
  78238. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  78239. /**
  78240. * Gets or sets a boolean which defines if optimization octree has to be updated
  78241. */
  78242. get: function () {
  78243. return MergeMeshesOptimization._UpdateSelectionTree;
  78244. },
  78245. /**
  78246. * Gets or sets a boolean which defines if optimization octree has to be updated
  78247. */
  78248. set: function (value) {
  78249. MergeMeshesOptimization._UpdateSelectionTree = value;
  78250. },
  78251. enumerable: true,
  78252. configurable: true
  78253. });
  78254. /**
  78255. * Gets a string describing the action executed by the current optimization
  78256. * @return description string
  78257. */
  78258. MergeMeshesOptimization.prototype.getDescription = function () {
  78259. return "Merging similar meshes together";
  78260. };
  78261. /**
  78262. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  78263. * @param scene defines the current scene where to apply this optimization
  78264. * @param optimizer defines the current optimizer
  78265. * @param updateSelectionTree defines that the selection octree has to be updated (false by default)
  78266. * @returns true if everything that can be done was applied
  78267. */
  78268. MergeMeshesOptimization.prototype.apply = function (scene, optimizer, updateSelectionTree) {
  78269. var globalPool = scene.meshes.slice(0);
  78270. var globalLength = globalPool.length;
  78271. for (var index = 0; index < globalLength; index++) {
  78272. var currentPool = new Array();
  78273. var current = globalPool[index];
  78274. // Checks
  78275. if (!this._canBeMerged(current)) {
  78276. continue;
  78277. }
  78278. currentPool.push(current);
  78279. // Find compatible meshes
  78280. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  78281. var otherMesh = globalPool[subIndex];
  78282. if (!this._canBeMerged(otherMesh)) {
  78283. continue;
  78284. }
  78285. if (otherMesh.material !== current.material) {
  78286. continue;
  78287. }
  78288. if (otherMesh.checkCollisions !== current.checkCollisions) {
  78289. continue;
  78290. }
  78291. currentPool.push(otherMesh);
  78292. globalLength--;
  78293. globalPool.splice(subIndex, 1);
  78294. subIndex--;
  78295. }
  78296. if (currentPool.length < 2) {
  78297. continue;
  78298. }
  78299. // Merge meshes
  78300. BABYLON.Mesh.MergeMeshes(currentPool);
  78301. }
  78302. if (updateSelectionTree != undefined) {
  78303. if (updateSelectionTree) {
  78304. scene.createOrUpdateSelectionOctree();
  78305. }
  78306. }
  78307. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  78308. scene.createOrUpdateSelectionOctree();
  78309. }
  78310. return true;
  78311. };
  78312. ;
  78313. MergeMeshesOptimization._UpdateSelectionTree = false;
  78314. return MergeMeshesOptimization;
  78315. }(SceneOptimization));
  78316. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  78317. /**
  78318. * Defines a list of options used by SceneOptimizer
  78319. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  78320. */
  78321. var SceneOptimizerOptions = /** @class */ (function () {
  78322. /**
  78323. * Creates a new list of options used by SceneOptimizer
  78324. * @param targetFrameRate defines the target frame rate to reach (60 by default)
  78325. * @param trackerDuration defines the interval between two checkes (2000ms by default)
  78326. */
  78327. function SceneOptimizerOptions(
  78328. /**
  78329. * Defines the target frame rate to reach (60 by default)
  78330. */
  78331. targetFrameRate,
  78332. /**
  78333. * Defines the interval between two checkes (2000ms by default)
  78334. */
  78335. trackerDuration) {
  78336. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  78337. if (trackerDuration === void 0) { trackerDuration = 2000; }
  78338. this.targetFrameRate = targetFrameRate;
  78339. this.trackerDuration = trackerDuration;
  78340. /**
  78341. * Gets the list of optimizations to apply
  78342. */
  78343. this.optimizations = new Array();
  78344. }
  78345. /**
  78346. * Add a new optimization
  78347. * @param optimization defines the SceneOptimization to add to the list of active optimizations
  78348. * @returns the current SceneOptimizerOptions
  78349. */
  78350. SceneOptimizerOptions.prototype.addOptimization = function (optimization) {
  78351. this.optimizations.push(optimization);
  78352. return this;
  78353. };
  78354. /**
  78355. * Add a new custom optimization
  78356. * @param onApply defines the callback called to apply the custom optimization (true if everything that can be done was applied)
  78357. * @param onGetDescription defines the callback called to get the description attached with the optimization.
  78358. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  78359. * @returns the current SceneOptimizerOptions
  78360. */
  78361. SceneOptimizerOptions.prototype.addCustomOptimization = function (onApply, onGetDescription, priority) {
  78362. if (priority === void 0) { priority = 0; }
  78363. var optimization = new CustomOptimization(priority);
  78364. optimization.onApply = onApply;
  78365. optimization.onGetDescription = onGetDescription;
  78366. this.optimizations.push(optimization);
  78367. return this;
  78368. };
  78369. /**
  78370. * Creates a list of pre-defined optimizations aimed to reduce the visual impact on the scene
  78371. * @param targetFrameRate defines the target frame rate (60 by default)
  78372. * @returns a SceneOptimizerOptions object
  78373. */
  78374. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  78375. var result = new SceneOptimizerOptions(targetFrameRate);
  78376. var priority = 0;
  78377. result.addOptimization(new MergeMeshesOptimization(priority));
  78378. result.addOptimization(new ShadowsOptimization(priority));
  78379. result.addOptimization(new LensFlaresOptimization(priority));
  78380. // Next priority
  78381. priority++;
  78382. result.addOptimization(new PostProcessesOptimization(priority));
  78383. result.addOptimization(new ParticlesOptimization(priority));
  78384. // Next priority
  78385. priority++;
  78386. result.addOptimization(new TextureOptimization(priority, 1024));
  78387. return result;
  78388. };
  78389. /**
  78390. * Creates a list of pre-defined optimizations aimed to have a moderate impact on the scene visual
  78391. * @param targetFrameRate defines the target frame rate (60 by default)
  78392. * @returns a SceneOptimizerOptions object
  78393. */
  78394. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  78395. var result = new SceneOptimizerOptions(targetFrameRate);
  78396. var priority = 0;
  78397. result.addOptimization(new MergeMeshesOptimization(priority));
  78398. result.addOptimization(new ShadowsOptimization(priority));
  78399. result.addOptimization(new LensFlaresOptimization(priority));
  78400. // Next priority
  78401. priority++;
  78402. result.addOptimization(new PostProcessesOptimization(priority));
  78403. result.addOptimization(new ParticlesOptimization(priority));
  78404. // Next priority
  78405. priority++;
  78406. result.addOptimization(new TextureOptimization(priority, 512));
  78407. // Next priority
  78408. priority++;
  78409. result.addOptimization(new RenderTargetsOptimization(priority));
  78410. // Next priority
  78411. priority++;
  78412. result.addOptimization(new HardwareScalingOptimization(priority, 2));
  78413. return result;
  78414. };
  78415. /**
  78416. * Creates a list of pre-defined optimizations aimed to have a big impact on the scene visual
  78417. * @param targetFrameRate defines the target frame rate (60 by default)
  78418. * @returns a SceneOptimizerOptions object
  78419. */
  78420. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  78421. var result = new SceneOptimizerOptions(targetFrameRate);
  78422. var priority = 0;
  78423. result.addOptimization(new MergeMeshesOptimization(priority));
  78424. result.addOptimization(new ShadowsOptimization(priority));
  78425. result.addOptimization(new LensFlaresOptimization(priority));
  78426. // Next priority
  78427. priority++;
  78428. result.addOptimization(new PostProcessesOptimization(priority));
  78429. result.addOptimization(new ParticlesOptimization(priority));
  78430. // Next priority
  78431. priority++;
  78432. result.addOptimization(new TextureOptimization(priority, 256));
  78433. // Next priority
  78434. priority++;
  78435. result.addOptimization(new RenderTargetsOptimization(priority));
  78436. // Next priority
  78437. priority++;
  78438. result.addOptimization(new HardwareScalingOptimization(priority, 4));
  78439. return result;
  78440. };
  78441. return SceneOptimizerOptions;
  78442. }());
  78443. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  78444. /**
  78445. * Class used to run optimizations in order to reach a target frame rate
  78446. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  78447. */
  78448. var SceneOptimizer = /** @class */ (function () {
  78449. /**
  78450. * Creates a new SceneOptimizer
  78451. * @param scene defines the scene to work on
  78452. * @param options defines the options to use with the SceneOptimizer
  78453. * @param autoGeneratePriorities defines if priorities must be generated and not read from SceneOptimization property (true by default)
  78454. * @param improvementMode defines if the scene optimizer must run the maximum optimization while staying over a target frame instead of trying to reach the target framerate (false by default)
  78455. */
  78456. function SceneOptimizer(scene, options, autoGeneratePriorities, improvementMode) {
  78457. if (autoGeneratePriorities === void 0) { autoGeneratePriorities = true; }
  78458. if (improvementMode === void 0) { improvementMode = false; }
  78459. var _this = this;
  78460. this._isRunning = false;
  78461. this._currentPriorityLevel = 0;
  78462. this._targetFrameRate = 60;
  78463. this._trackerDuration = 2000;
  78464. this._currentFrameRate = 0;
  78465. this._improvementMode = false;
  78466. /**
  78467. * Defines an observable called when the optimizer reaches the target frame rate
  78468. */
  78469. this.onSuccessObservable = new BABYLON.Observable();
  78470. /**
  78471. * Defines an observable called when the optimizer enables an optimization
  78472. */
  78473. this.onNewOptimizationAppliedObservable = new BABYLON.Observable();
  78474. /**
  78475. * Defines an observable called when the optimizer is not able to reach the target frame rate
  78476. */
  78477. this.onFailureObservable = new BABYLON.Observable();
  78478. if (!options) {
  78479. this._options = new SceneOptimizerOptions();
  78480. }
  78481. else {
  78482. this._options = options;
  78483. }
  78484. if (this._options.targetFrameRate) {
  78485. this._targetFrameRate = this._options.targetFrameRate;
  78486. }
  78487. if (this._options.trackerDuration) {
  78488. this._trackerDuration = this._options.trackerDuration;
  78489. }
  78490. if (autoGeneratePriorities) {
  78491. var priority = 0;
  78492. for (var _i = 0, _a = this._options.optimizations; _i < _a.length; _i++) {
  78493. var optim = _a[_i];
  78494. optim.priority = priority++;
  78495. }
  78496. }
  78497. this._improvementMode = improvementMode;
  78498. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  78499. this._sceneDisposeObserver = this._scene.onDisposeObservable.add(function () {
  78500. _this._sceneDisposeObserver = null;
  78501. _this.dispose();
  78502. });
  78503. }
  78504. Object.defineProperty(SceneOptimizer.prototype, "isInImprovementMode", {
  78505. /**
  78506. * Gets a boolean indicating if the optimizer is in improvement mode
  78507. */
  78508. get: function () {
  78509. return this._improvementMode;
  78510. },
  78511. enumerable: true,
  78512. configurable: true
  78513. });
  78514. Object.defineProperty(SceneOptimizer.prototype, "currentPriorityLevel", {
  78515. /**
  78516. * Gets the current priority level (0 at start)
  78517. */
  78518. get: function () {
  78519. return this._currentPriorityLevel;
  78520. },
  78521. enumerable: true,
  78522. configurable: true
  78523. });
  78524. Object.defineProperty(SceneOptimizer.prototype, "currentFrameRate", {
  78525. /**
  78526. * Gets the current frame rate checked by the SceneOptimizer
  78527. */
  78528. get: function () {
  78529. return this._currentFrameRate;
  78530. },
  78531. enumerable: true,
  78532. configurable: true
  78533. });
  78534. Object.defineProperty(SceneOptimizer.prototype, "targetFrameRate", {
  78535. /**
  78536. * Gets or sets the current target frame rate (60 by default)
  78537. */
  78538. get: function () {
  78539. return this._targetFrameRate;
  78540. },
  78541. /**
  78542. * Gets or sets the current target frame rate (60 by default)
  78543. */
  78544. set: function (value) {
  78545. this._targetFrameRate = value;
  78546. },
  78547. enumerable: true,
  78548. configurable: true
  78549. });
  78550. Object.defineProperty(SceneOptimizer.prototype, "trackerDuration", {
  78551. /**
  78552. * Gets or sets the current interval between two checks (every 2000ms by default)
  78553. */
  78554. get: function () {
  78555. return this._trackerDuration;
  78556. },
  78557. /**
  78558. * Gets or sets the current interval between two checks (every 2000ms by default)
  78559. */
  78560. set: function (value) {
  78561. this._trackerDuration = value;
  78562. },
  78563. enumerable: true,
  78564. configurable: true
  78565. });
  78566. Object.defineProperty(SceneOptimizer.prototype, "optimizations", {
  78567. /**
  78568. * Gets the list of active optimizations
  78569. */
  78570. get: function () {
  78571. return this._options.optimizations;
  78572. },
  78573. enumerable: true,
  78574. configurable: true
  78575. });
  78576. /**
  78577. * Stops the current optimizer
  78578. */
  78579. SceneOptimizer.prototype.stop = function () {
  78580. this._isRunning = false;
  78581. };
  78582. /**
  78583. * Reset the optimizer to initial step (current priority level = 0)
  78584. */
  78585. SceneOptimizer.prototype.reset = function () {
  78586. this._currentPriorityLevel = 0;
  78587. };
  78588. /**
  78589. * Start the optimizer. By default it will try to reach a specific framerate
  78590. * but if the optimizer is set with improvementMode === true then it will run all optimiatiation while frame rate is above the target frame rate
  78591. */
  78592. SceneOptimizer.prototype.start = function () {
  78593. var _this = this;
  78594. if (this._isRunning) {
  78595. return;
  78596. }
  78597. this._isRunning = true;
  78598. // Let's wait for the scene to be ready before running our check
  78599. this._scene.executeWhenReady(function () {
  78600. setTimeout(function () {
  78601. _this._checkCurrentState();
  78602. }, _this._trackerDuration);
  78603. });
  78604. };
  78605. SceneOptimizer.prototype._checkCurrentState = function () {
  78606. var _this = this;
  78607. if (!this._isRunning) {
  78608. return;
  78609. }
  78610. var scene = this._scene;
  78611. var options = this._options;
  78612. this._currentFrameRate = Math.round(scene.getEngine().getFps());
  78613. if (this._improvementMode && this._currentFrameRate <= this._targetFrameRate ||
  78614. !this._improvementMode && this._currentFrameRate >= this._targetFrameRate) {
  78615. this._isRunning = false;
  78616. this.onSuccessObservable.notifyObservers(this);
  78617. return;
  78618. }
  78619. // Apply current level of optimizations
  78620. var allDone = true;
  78621. var noOptimizationApplied = true;
  78622. for (var index = 0; index < options.optimizations.length; index++) {
  78623. var optimization = options.optimizations[index];
  78624. if (optimization.priority === this._currentPriorityLevel) {
  78625. noOptimizationApplied = false;
  78626. allDone = allDone && optimization.apply(scene, this);
  78627. this.onNewOptimizationAppliedObservable.notifyObservers(optimization);
  78628. }
  78629. }
  78630. // If no optimization was applied, this is a failure :(
  78631. if (noOptimizationApplied) {
  78632. this._isRunning = false;
  78633. this.onFailureObservable.notifyObservers(this);
  78634. return;
  78635. }
  78636. // If all optimizations were done, move to next level
  78637. if (allDone) {
  78638. this._currentPriorityLevel++;
  78639. }
  78640. // Let's the system running for a specific amount of time before checking FPS
  78641. scene.executeWhenReady(function () {
  78642. setTimeout(function () {
  78643. _this._checkCurrentState();
  78644. }, _this._trackerDuration);
  78645. });
  78646. };
  78647. /**
  78648. * Release all resources
  78649. */
  78650. SceneOptimizer.prototype.dispose = function () {
  78651. this.stop();
  78652. this.onSuccessObservable.clear();
  78653. this.onFailureObservable.clear();
  78654. this.onNewOptimizationAppliedObservable.clear();
  78655. if (this._sceneDisposeObserver) {
  78656. this._scene.onDisposeObservable.remove(this._sceneDisposeObserver);
  78657. }
  78658. };
  78659. /**
  78660. * Helper function to create a SceneOptimizer with one single line of code
  78661. * @param scene defines the scene to work on
  78662. * @param options defines the options to use with the SceneOptimizer
  78663. * @param onSuccess defines a callback to call on success
  78664. * @param onFailure defines a callback to call on failure
  78665. * @returns the new SceneOptimizer object
  78666. */
  78667. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  78668. var optimizer = new SceneOptimizer(scene, options || SceneOptimizerOptions.ModerateDegradationAllowed(), false);
  78669. if (onSuccess) {
  78670. optimizer.onSuccessObservable.add(function () {
  78671. onSuccess();
  78672. });
  78673. }
  78674. if (onFailure) {
  78675. optimizer.onFailureObservable.add(function () {
  78676. onFailure();
  78677. });
  78678. }
  78679. optimizer.start();
  78680. return optimizer;
  78681. };
  78682. return SceneOptimizer;
  78683. }());
  78684. BABYLON.SceneOptimizer = SceneOptimizer;
  78685. })(BABYLON || (BABYLON = {}));
  78686. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  78687. var BABYLON;
  78688. (function (BABYLON) {
  78689. var OutlineRenderer = /** @class */ (function () {
  78690. function OutlineRenderer(scene) {
  78691. this.zOffset = 1;
  78692. this._scene = scene;
  78693. }
  78694. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  78695. var _this = this;
  78696. if (useOverlay === void 0) { useOverlay = false; }
  78697. var scene = this._scene;
  78698. var engine = this._scene.getEngine();
  78699. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  78700. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  78701. return;
  78702. }
  78703. var mesh = subMesh.getRenderingMesh();
  78704. var material = subMesh.getMaterial();
  78705. if (!material || !scene.activeCamera) {
  78706. return;
  78707. }
  78708. engine.enableEffect(this._effect);
  78709. // Logarithmic depth
  78710. if (material.useLogarithmicDepth) {
  78711. this._effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  78712. }
  78713. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  78714. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : material.alpha);
  78715. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  78716. // Bones
  78717. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  78718. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  78719. }
  78720. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  78721. // Alpha test
  78722. if (material && material.needAlphaTesting()) {
  78723. var alphaTexture = material.getAlphaTestTexture();
  78724. if (alphaTexture) {
  78725. this._effect.setTexture("diffuseSampler", alphaTexture);
  78726. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  78727. }
  78728. }
  78729. engine.setZOffset(-this.zOffset);
  78730. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  78731. engine.setZOffset(0);
  78732. };
  78733. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  78734. var defines = [];
  78735. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  78736. var mesh = subMesh.getMesh();
  78737. var material = subMesh.getMaterial();
  78738. if (material) {
  78739. // Alpha test
  78740. if (material.needAlphaTesting()) {
  78741. defines.push("#define ALPHATEST");
  78742. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  78743. attribs.push(BABYLON.VertexBuffer.UVKind);
  78744. defines.push("#define UV1");
  78745. }
  78746. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  78747. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  78748. defines.push("#define UV2");
  78749. }
  78750. }
  78751. //Logarithmic depth
  78752. if (material.useLogarithmicDepth) {
  78753. defines.push("#define LOGARITHMICDEPTH");
  78754. }
  78755. }
  78756. // Bones
  78757. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  78758. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  78759. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  78760. if (mesh.numBoneInfluencers > 4) {
  78761. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  78762. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  78763. }
  78764. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  78765. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  78766. }
  78767. else {
  78768. defines.push("#define NUM_BONE_INFLUENCERS 0");
  78769. }
  78770. // Instances
  78771. if (useInstances) {
  78772. defines.push("#define INSTANCES");
  78773. attribs.push("world0");
  78774. attribs.push("world1");
  78775. attribs.push("world2");
  78776. attribs.push("world3");
  78777. }
  78778. // Get correct effect
  78779. var join = defines.join("\n");
  78780. if (this._cachedDefines !== join) {
  78781. this._cachedDefines = join;
  78782. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color", "logarithmicDepthConstant"], ["diffuseSampler"], join);
  78783. }
  78784. return this._effect.isReady();
  78785. };
  78786. return OutlineRenderer;
  78787. }());
  78788. BABYLON.OutlineRenderer = OutlineRenderer;
  78789. })(BABYLON || (BABYLON = {}));
  78790. //# sourceMappingURL=babylon.outlineRenderer.js.map
  78791. var BABYLON;
  78792. (function (BABYLON) {
  78793. var FaceAdjacencies = /** @class */ (function () {
  78794. function FaceAdjacencies() {
  78795. this.edges = new Array();
  78796. this.edgesConnectedCount = 0;
  78797. }
  78798. return FaceAdjacencies;
  78799. }());
  78800. var EdgesRenderer = /** @class */ (function () {
  78801. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  78802. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  78803. if (epsilon === void 0) { epsilon = 0.95; }
  78804. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  78805. this.edgesWidthScalerForOrthographic = 1000.0;
  78806. this.edgesWidthScalerForPerspective = 50.0;
  78807. this._linesPositions = new Array();
  78808. this._linesNormals = new Array();
  78809. this._linesIndices = new Array();
  78810. this._buffers = {};
  78811. this._checkVerticesInsteadOfIndices = false;
  78812. this._source = source;
  78813. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  78814. this._epsilon = epsilon;
  78815. this._prepareRessources();
  78816. this._generateEdgesLines();
  78817. }
  78818. EdgesRenderer.prototype._prepareRessources = function () {
  78819. if (this._lineShader) {
  78820. return;
  78821. }
  78822. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  78823. attributes: ["position", "normal"],
  78824. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  78825. });
  78826. this._lineShader.disableDepthWrite = true;
  78827. this._lineShader.backFaceCulling = false;
  78828. };
  78829. EdgesRenderer.prototype._rebuild = function () {
  78830. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  78831. if (buffer) {
  78832. buffer._rebuild();
  78833. }
  78834. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  78835. if (buffer) {
  78836. buffer._rebuild();
  78837. }
  78838. var scene = this._source.getScene();
  78839. var engine = scene.getEngine();
  78840. this._ib = engine.createIndexBuffer(this._linesIndices);
  78841. };
  78842. EdgesRenderer.prototype.dispose = function () {
  78843. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  78844. if (buffer) {
  78845. buffer.dispose();
  78846. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  78847. }
  78848. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  78849. if (buffer) {
  78850. buffer.dispose();
  78851. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  78852. }
  78853. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  78854. this._lineShader.dispose();
  78855. };
  78856. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  78857. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  78858. return 0;
  78859. }
  78860. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  78861. return 1;
  78862. }
  78863. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  78864. return 2;
  78865. }
  78866. return -1;
  78867. };
  78868. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  78869. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  78870. return 0;
  78871. }
  78872. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  78873. return 1;
  78874. }
  78875. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  78876. return 2;
  78877. }
  78878. return -1;
  78879. };
  78880. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  78881. var needToCreateLine;
  78882. if (edge === undefined) {
  78883. needToCreateLine = true;
  78884. }
  78885. else {
  78886. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  78887. needToCreateLine = dotProduct < this._epsilon;
  78888. }
  78889. if (needToCreateLine) {
  78890. var offset = this._linesPositions.length / 3;
  78891. var normal = p0.subtract(p1);
  78892. normal.normalize();
  78893. // Positions
  78894. this._linesPositions.push(p0.x);
  78895. this._linesPositions.push(p0.y);
  78896. this._linesPositions.push(p0.z);
  78897. this._linesPositions.push(p0.x);
  78898. this._linesPositions.push(p0.y);
  78899. this._linesPositions.push(p0.z);
  78900. this._linesPositions.push(p1.x);
  78901. this._linesPositions.push(p1.y);
  78902. this._linesPositions.push(p1.z);
  78903. this._linesPositions.push(p1.x);
  78904. this._linesPositions.push(p1.y);
  78905. this._linesPositions.push(p1.z);
  78906. // Normals
  78907. this._linesNormals.push(p1.x);
  78908. this._linesNormals.push(p1.y);
  78909. this._linesNormals.push(p1.z);
  78910. this._linesNormals.push(-1);
  78911. this._linesNormals.push(p1.x);
  78912. this._linesNormals.push(p1.y);
  78913. this._linesNormals.push(p1.z);
  78914. this._linesNormals.push(1);
  78915. this._linesNormals.push(p0.x);
  78916. this._linesNormals.push(p0.y);
  78917. this._linesNormals.push(p0.z);
  78918. this._linesNormals.push(-1);
  78919. this._linesNormals.push(p0.x);
  78920. this._linesNormals.push(p0.y);
  78921. this._linesNormals.push(p0.z);
  78922. this._linesNormals.push(1);
  78923. // Indices
  78924. this._linesIndices.push(offset);
  78925. this._linesIndices.push(offset + 1);
  78926. this._linesIndices.push(offset + 2);
  78927. this._linesIndices.push(offset);
  78928. this._linesIndices.push(offset + 2);
  78929. this._linesIndices.push(offset + 3);
  78930. }
  78931. };
  78932. EdgesRenderer.prototype._generateEdgesLines = function () {
  78933. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  78934. var indices = this._source.getIndices();
  78935. if (!indices || !positions) {
  78936. return;
  78937. }
  78938. // First let's find adjacencies
  78939. var adjacencies = new Array();
  78940. var faceNormals = new Array();
  78941. var index;
  78942. var faceAdjacencies;
  78943. // Prepare faces
  78944. for (index = 0; index < indices.length; index += 3) {
  78945. faceAdjacencies = new FaceAdjacencies();
  78946. var p0Index = indices[index];
  78947. var p1Index = indices[index + 1];
  78948. var p2Index = indices[index + 2];
  78949. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  78950. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  78951. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  78952. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  78953. faceNormal.normalize();
  78954. faceNormals.push(faceNormal);
  78955. adjacencies.push(faceAdjacencies);
  78956. }
  78957. // Scan
  78958. for (index = 0; index < adjacencies.length; index++) {
  78959. faceAdjacencies = adjacencies[index];
  78960. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  78961. var otherFaceAdjacencies = adjacencies[otherIndex];
  78962. if (faceAdjacencies.edgesConnectedCount === 3) {
  78963. break;
  78964. }
  78965. if (otherFaceAdjacencies.edgesConnectedCount === 3) {
  78966. continue;
  78967. }
  78968. var otherP0 = indices[otherIndex * 3];
  78969. var otherP1 = indices[otherIndex * 3 + 1];
  78970. var otherP2 = indices[otherIndex * 3 + 2];
  78971. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  78972. var otherEdgeIndex = 0;
  78973. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  78974. continue;
  78975. }
  78976. switch (edgeIndex) {
  78977. case 0:
  78978. if (this._checkVerticesInsteadOfIndices) {
  78979. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  78980. }
  78981. else {
  78982. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  78983. }
  78984. break;
  78985. case 1:
  78986. if (this._checkVerticesInsteadOfIndices) {
  78987. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  78988. }
  78989. else {
  78990. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  78991. }
  78992. break;
  78993. case 2:
  78994. if (this._checkVerticesInsteadOfIndices) {
  78995. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  78996. }
  78997. else {
  78998. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  78999. }
  79000. break;
  79001. }
  79002. if (otherEdgeIndex === -1) {
  79003. continue;
  79004. }
  79005. faceAdjacencies.edges[edgeIndex] = otherIndex;
  79006. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  79007. faceAdjacencies.edgesConnectedCount++;
  79008. otherFaceAdjacencies.edgesConnectedCount++;
  79009. if (faceAdjacencies.edgesConnectedCount === 3) {
  79010. break;
  79011. }
  79012. }
  79013. }
  79014. }
  79015. // Create lines
  79016. for (index = 0; index < adjacencies.length; index++) {
  79017. // 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
  79018. var current = adjacencies[index];
  79019. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  79020. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  79021. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  79022. }
  79023. // Merge into a single mesh
  79024. var engine = this._source.getScene().getEngine();
  79025. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  79026. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  79027. this._ib = engine.createIndexBuffer(this._linesIndices);
  79028. this._indicesCount = this._linesIndices.length;
  79029. };
  79030. EdgesRenderer.prototype.render = function () {
  79031. var scene = this._source.getScene();
  79032. if (!this._lineShader.isReady() || !scene.activeCamera) {
  79033. return;
  79034. }
  79035. var engine = scene.getEngine();
  79036. this._lineShader._preBind();
  79037. // VBOs
  79038. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  79039. scene.resetCachedMaterial();
  79040. this._lineShader.setColor4("color", this._source.edgesColor);
  79041. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  79042. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  79043. }
  79044. else {
  79045. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  79046. }
  79047. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  79048. this._lineShader.bind(this._source.getWorldMatrix());
  79049. // Draw order
  79050. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._indicesCount);
  79051. this._lineShader.unbind();
  79052. engine.setDepthWrite(true);
  79053. };
  79054. return EdgesRenderer;
  79055. }());
  79056. BABYLON.EdgesRenderer = EdgesRenderer;
  79057. })(BABYLON || (BABYLON = {}));
  79058. //# sourceMappingURL=babylon.edgesRenderer.js.map
  79059. var BABYLON;
  79060. (function (BABYLON) {
  79061. /**
  79062. * Special Glow Blur post process only blurring the alpha channel
  79063. * It enforces keeping the most luminous color in the color channel.
  79064. */
  79065. var GlowBlurPostProcess = /** @class */ (function (_super) {
  79066. __extends(GlowBlurPostProcess, _super);
  79067. function GlowBlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable) {
  79068. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  79069. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  79070. _this.direction = direction;
  79071. _this.kernel = kernel;
  79072. _this.onApplyObservable.add(function (effect) {
  79073. effect.setFloat2("screenSize", _this.width, _this.height);
  79074. effect.setVector2("direction", _this.direction);
  79075. effect.setFloat("blurWidth", _this.kernel);
  79076. });
  79077. return _this;
  79078. }
  79079. return GlowBlurPostProcess;
  79080. }(BABYLON.PostProcess));
  79081. /**
  79082. * The highlight layer Helps adding a glow effect around a mesh.
  79083. *
  79084. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  79085. * glowy meshes to your scene.
  79086. *
  79087. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  79088. */
  79089. var HighlightLayer = /** @class */ (function () {
  79090. /**
  79091. * Instantiates a new highlight Layer and references it to the scene..
  79092. * @param name The name of the layer
  79093. * @param scene The scene to use the layer in
  79094. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  79095. */
  79096. function HighlightLayer(name, scene, options) {
  79097. this.name = name;
  79098. this._vertexBuffers = {};
  79099. this._mainTextureDesiredSize = { width: 0, height: 0 };
  79100. this._meshes = {};
  79101. this._maxSize = 0;
  79102. this._shouldRender = false;
  79103. this._instanceGlowingMeshStencilReference = HighlightLayer.glowingMeshStencilReference++;
  79104. this._excludedMeshes = {};
  79105. /**
  79106. * Specifies whether or not the inner glow is ACTIVE in the layer.
  79107. */
  79108. this.innerGlow = true;
  79109. /**
  79110. * Specifies whether or not the outer glow is ACTIVE in the layer.
  79111. */
  79112. this.outerGlow = true;
  79113. /**
  79114. * Specifies wether the highlight layer is enabled or not.
  79115. */
  79116. this.isEnabled = true;
  79117. /**
  79118. * An event triggered when the highlight layer has been disposed.
  79119. * @type {BABYLON.Observable}
  79120. */
  79121. this.onDisposeObservable = new BABYLON.Observable();
  79122. /**
  79123. * An event triggered when the highlight layer is about rendering the main texture with the glowy parts.
  79124. * @type {BABYLON.Observable}
  79125. */
  79126. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  79127. /**
  79128. * An event triggered when the highlight layer is being blurred.
  79129. * @type {BABYLON.Observable}
  79130. */
  79131. this.onBeforeBlurObservable = new BABYLON.Observable();
  79132. /**
  79133. * An event triggered when the highlight layer has been blurred.
  79134. * @type {BABYLON.Observable}
  79135. */
  79136. this.onAfterBlurObservable = new BABYLON.Observable();
  79137. /**
  79138. * An event triggered when the glowing blurred texture is being merged in the scene.
  79139. * @type {BABYLON.Observable}
  79140. */
  79141. this.onBeforeComposeObservable = new BABYLON.Observable();
  79142. /**
  79143. * An event triggered when the glowing blurred texture has been merged in the scene.
  79144. * @type {BABYLON.Observable}
  79145. */
  79146. this.onAfterComposeObservable = new BABYLON.Observable();
  79147. /**
  79148. * An event triggered when the highlight layer changes its size.
  79149. * @type {BABYLON.Observable}
  79150. */
  79151. this.onSizeChangedObservable = new BABYLON.Observable();
  79152. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  79153. var engine = scene.getEngine();
  79154. this._engine = engine;
  79155. this._maxSize = this._engine.getCaps().maxTextureSize;
  79156. this._scene.highlightLayers.push(this);
  79157. // Warn on stencil.
  79158. if (!this._engine.isStencilEnable) {
  79159. 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 }");
  79160. }
  79161. // Adapt options
  79162. this._options = options || {
  79163. mainTextureRatio: 0.5,
  79164. blurTextureSizeRatio: 0.5,
  79165. blurHorizontalSize: 1.0,
  79166. blurVerticalSize: 1.0,
  79167. alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE,
  79168. camera: null
  79169. };
  79170. this._options.mainTextureRatio = this._options.mainTextureRatio || 0.5;
  79171. this._options.blurTextureSizeRatio = this._options.blurTextureSizeRatio || 1.0;
  79172. this._options.blurHorizontalSize = this._options.blurHorizontalSize || 1;
  79173. this._options.blurVerticalSize = this._options.blurVerticalSize || 1;
  79174. this._options.alphaBlendingMode = this._options.alphaBlendingMode || BABYLON.Engine.ALPHA_COMBINE;
  79175. // VBO
  79176. var vertices = [];
  79177. vertices.push(1, 1);
  79178. vertices.push(-1, 1);
  79179. vertices.push(-1, -1);
  79180. vertices.push(1, -1);
  79181. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  79182. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  79183. this._createIndexBuffer();
  79184. // Effect
  79185. this._glowMapMergeEffect = engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], this._options.isStroke ? "#define STROKE \n" : undefined);
  79186. // Render target
  79187. this.setMainTextureSize();
  79188. // Create Textures and post processes
  79189. this.createTextureAndPostProcesses();
  79190. }
  79191. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  79192. /**
  79193. * Gets the horizontal size of the blur.
  79194. */
  79195. get: function () {
  79196. return this._horizontalBlurPostprocess.kernel;
  79197. },
  79198. /**
  79199. * Specifies the horizontal size of the blur.
  79200. */
  79201. set: function (value) {
  79202. this._horizontalBlurPostprocess.kernel = value;
  79203. },
  79204. enumerable: true,
  79205. configurable: true
  79206. });
  79207. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  79208. /**
  79209. * Gets the vertical size of the blur.
  79210. */
  79211. get: function () {
  79212. return this._verticalBlurPostprocess.kernel;
  79213. },
  79214. /**
  79215. * Specifies the vertical size of the blur.
  79216. */
  79217. set: function (value) {
  79218. this._verticalBlurPostprocess.kernel = value;
  79219. },
  79220. enumerable: true,
  79221. configurable: true
  79222. });
  79223. Object.defineProperty(HighlightLayer.prototype, "camera", {
  79224. /**
  79225. * Gets the camera attached to the layer.
  79226. */
  79227. get: function () {
  79228. return this._options.camera;
  79229. },
  79230. enumerable: true,
  79231. configurable: true
  79232. });
  79233. HighlightLayer.prototype._createIndexBuffer = function () {
  79234. var engine = this._scene.getEngine();
  79235. // Indices
  79236. var indices = [];
  79237. indices.push(0);
  79238. indices.push(1);
  79239. indices.push(2);
  79240. indices.push(0);
  79241. indices.push(2);
  79242. indices.push(3);
  79243. this._indexBuffer = engine.createIndexBuffer(indices);
  79244. };
  79245. HighlightLayer.prototype._rebuild = function () {
  79246. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  79247. if (vb) {
  79248. vb._rebuild();
  79249. }
  79250. this._createIndexBuffer();
  79251. };
  79252. /**
  79253. * Creates the render target textures and post processes used in the highlight layer.
  79254. */
  79255. HighlightLayer.prototype.createTextureAndPostProcesses = function () {
  79256. var _this = this;
  79257. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  79258. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  79259. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  79260. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  79261. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  79262. width: this._mainTextureDesiredSize.width,
  79263. height: this._mainTextureDesiredSize.height
  79264. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  79265. this._mainTexture.activeCamera = this._options.camera;
  79266. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  79267. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  79268. this._mainTexture.anisotropicFilteringLevel = 1;
  79269. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  79270. this._mainTexture.renderParticles = false;
  79271. this._mainTexture.renderList = null;
  79272. this._mainTexture.ignoreCameraViewport = true;
  79273. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  79274. width: blurTextureWidth,
  79275. height: blurTextureHeight
  79276. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  79277. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  79278. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  79279. this._blurTexture.anisotropicFilteringLevel = 16;
  79280. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  79281. this._blurTexture.renderParticles = false;
  79282. this._blurTexture.ignoreCameraViewport = true;
  79283. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  79284. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  79285. effect.setTexture("textureSampler", _this._mainTexture);
  79286. });
  79287. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  79288. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  79289. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  79290. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  79291. });
  79292. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  79293. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  79294. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  79295. });
  79296. }
  79297. else {
  79298. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  79299. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  79300. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  79301. });
  79302. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  79303. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  79304. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  79305. });
  79306. }
  79307. this._mainTexture.onAfterUnbindObservable.add(function () {
  79308. _this.onBeforeBlurObservable.notifyObservers(_this);
  79309. var internalTexture = _this._blurTexture.getInternalTexture();
  79310. if (internalTexture) {
  79311. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._horizontalBlurPostprocess, _this._verticalBlurPostprocess], internalTexture, true);
  79312. }
  79313. _this.onAfterBlurObservable.notifyObservers(_this);
  79314. });
  79315. // Custom render function
  79316. var renderSubMesh = function (subMesh) {
  79317. if (!_this._meshes) {
  79318. return;
  79319. }
  79320. var material = subMesh.getMaterial();
  79321. var mesh = subMesh.getRenderingMesh();
  79322. var scene = _this._scene;
  79323. var engine = scene.getEngine();
  79324. if (!material) {
  79325. return;
  79326. }
  79327. // Do not block in blend mode.
  79328. if (material.needAlphaBlendingForMesh(mesh)) {
  79329. return;
  79330. }
  79331. // Culling
  79332. engine.setState(material.backFaceCulling);
  79333. // Managing instances
  79334. var batch = mesh._getInstancesRenderList(subMesh._id);
  79335. if (batch.mustReturn) {
  79336. return;
  79337. }
  79338. // Excluded Mesh
  79339. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  79340. return;
  79341. }
  79342. ;
  79343. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  79344. var highlightLayerMesh = _this._meshes[mesh.uniqueId];
  79345. var emissiveTexture = null;
  79346. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  79347. emissiveTexture = material.emissiveTexture;
  79348. }
  79349. if (_this._isReady(subMesh, hardwareInstancedRendering, emissiveTexture)) {
  79350. engine.enableEffect(_this._glowMapGenerationEffect);
  79351. mesh._bind(subMesh, _this._glowMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  79352. _this._glowMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  79353. if (highlightLayerMesh) {
  79354. _this._glowMapGenerationEffect.setFloat4("color", highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  79355. }
  79356. else {
  79357. _this._glowMapGenerationEffect.setFloat4("color", HighlightLayer.neutralColor.r, HighlightLayer.neutralColor.g, HighlightLayer.neutralColor.b, HighlightLayer.neutralColor.a);
  79358. }
  79359. // Alpha test
  79360. if (material && material.needAlphaTesting()) {
  79361. var alphaTexture = material.getAlphaTestTexture();
  79362. if (alphaTexture) {
  79363. _this._glowMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  79364. var textureMatrix = alphaTexture.getTextureMatrix();
  79365. if (textureMatrix) {
  79366. _this._glowMapGenerationEffect.setMatrix("diffuseMatrix", textureMatrix);
  79367. }
  79368. }
  79369. }
  79370. // Glow emissive only
  79371. if (emissiveTexture) {
  79372. _this._glowMapGenerationEffect.setTexture("emissiveSampler", emissiveTexture);
  79373. _this._glowMapGenerationEffect.setMatrix("emissiveMatrix", emissiveTexture.getTextureMatrix());
  79374. }
  79375. // Bones
  79376. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  79377. _this._glowMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  79378. }
  79379. // Draw
  79380. mesh._processRendering(subMesh, _this._glowMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._glowMapGenerationEffect.setMatrix("world", world); });
  79381. }
  79382. else {
  79383. // Need to reset refresh rate of the shadowMap
  79384. _this._mainTexture.resetRefreshCounter();
  79385. }
  79386. };
  79387. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  79388. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  79389. var index;
  79390. var engine = _this._scene.getEngine();
  79391. if (depthOnlySubMeshes.length) {
  79392. engine.setColorWrite(false);
  79393. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  79394. renderSubMesh(depthOnlySubMeshes.data[index]);
  79395. }
  79396. engine.setColorWrite(true);
  79397. }
  79398. for (index = 0; index < opaqueSubMeshes.length; index++) {
  79399. renderSubMesh(opaqueSubMeshes.data[index]);
  79400. }
  79401. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  79402. renderSubMesh(alphaTestSubMeshes.data[index]);
  79403. }
  79404. for (index = 0; index < transparentSubMeshes.length; index++) {
  79405. renderSubMesh(transparentSubMeshes.data[index]);
  79406. }
  79407. };
  79408. this._mainTexture.onClearObservable.add(function (engine) {
  79409. engine.clear(HighlightLayer.neutralColor, true, true, true);
  79410. });
  79411. };
  79412. /**
  79413. * Checks for the readiness of the element composing the layer.
  79414. * @param subMesh the mesh to check for
  79415. * @param useInstances specify wether or not to use instances to render the mesh
  79416. * @param emissiveTexture the associated emissive texture used to generate the glow
  79417. * @return true if ready otherwise, false
  79418. */
  79419. HighlightLayer.prototype.isReady = function (subMesh, useInstances) {
  79420. var material = subMesh.getMaterial();
  79421. var mesh = subMesh.getRenderingMesh();
  79422. if (!material || !mesh || !this._meshes) {
  79423. return false;
  79424. }
  79425. var emissiveTexture = null;
  79426. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  79427. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  79428. emissiveTexture = material.emissiveTexture;
  79429. }
  79430. return this._isReady(subMesh, useInstances, emissiveTexture);
  79431. };
  79432. /**
  79433. * Checks for the readiness of the element composing the layer.
  79434. * @param subMesh the mesh to check for
  79435. * @param useInstances specify wether or not to use instances to render the mesh
  79436. * @param emissiveTexture the associated emissive texture used to generate the glow
  79437. * @return true if ready otherwise, false
  79438. */
  79439. HighlightLayer.prototype._isReady = function (subMesh, useInstances, emissiveTexture) {
  79440. var material = subMesh.getMaterial();
  79441. if (!material) {
  79442. return false;
  79443. }
  79444. if (!material.isReady(subMesh.getMesh(), useInstances)) {
  79445. return false;
  79446. }
  79447. var defines = [];
  79448. var attribs = [BABYLON.VertexBuffer.PositionKind];
  79449. var mesh = subMesh.getMesh();
  79450. var uv1 = false;
  79451. var uv2 = false;
  79452. // Alpha test
  79453. if (material && material.needAlphaTesting()) {
  79454. var alphaTexture = material.getAlphaTestTexture();
  79455. if (alphaTexture) {
  79456. defines.push("#define ALPHATEST");
  79457. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  79458. alphaTexture.coordinatesIndex === 1) {
  79459. defines.push("#define DIFFUSEUV2");
  79460. uv2 = true;
  79461. }
  79462. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  79463. defines.push("#define DIFFUSEUV1");
  79464. uv1 = true;
  79465. }
  79466. }
  79467. }
  79468. // Emissive
  79469. if (emissiveTexture) {
  79470. defines.push("#define EMISSIVE");
  79471. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  79472. emissiveTexture.coordinatesIndex === 1) {
  79473. defines.push("#define EMISSIVEUV2");
  79474. uv2 = true;
  79475. }
  79476. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  79477. defines.push("#define EMISSIVEUV1");
  79478. uv1 = true;
  79479. }
  79480. }
  79481. if (uv1) {
  79482. attribs.push(BABYLON.VertexBuffer.UVKind);
  79483. defines.push("#define UV1");
  79484. }
  79485. if (uv2) {
  79486. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  79487. defines.push("#define UV2");
  79488. }
  79489. // Bones
  79490. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  79491. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  79492. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  79493. if (mesh.numBoneInfluencers > 4) {
  79494. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  79495. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  79496. }
  79497. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  79498. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  79499. }
  79500. else {
  79501. defines.push("#define NUM_BONE_INFLUENCERS 0");
  79502. }
  79503. // Instances
  79504. if (useInstances) {
  79505. defines.push("#define INSTANCES");
  79506. attribs.push("world0");
  79507. attribs.push("world1");
  79508. attribs.push("world2");
  79509. attribs.push("world3");
  79510. }
  79511. // Get correct effect
  79512. var join = defines.join("\n");
  79513. if (this._cachedDefines !== join) {
  79514. this._cachedDefines = join;
  79515. this._glowMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix"], ["diffuseSampler", "emissiveSampler"], join);
  79516. }
  79517. return this._glowMapGenerationEffect.isReady();
  79518. };
  79519. /**
  79520. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  79521. */
  79522. HighlightLayer.prototype.render = function () {
  79523. var currentEffect = this._glowMapMergeEffect;
  79524. // Check
  79525. if (!currentEffect.isReady() || !this._blurTexture.isReady())
  79526. return;
  79527. var engine = this._scene.getEngine();
  79528. this.onBeforeComposeObservable.notifyObservers(this);
  79529. // Render
  79530. engine.enableEffect(currentEffect);
  79531. engine.setState(false);
  79532. // Cache
  79533. var previousStencilBuffer = engine.getStencilBuffer();
  79534. var previousStencilFunction = engine.getStencilFunction();
  79535. var previousStencilMask = engine.getStencilMask();
  79536. var previousStencilOperationPass = engine.getStencilOperationPass();
  79537. var previousStencilOperationFail = engine.getStencilOperationFail();
  79538. var previousStencilOperationDepthFail = engine.getStencilOperationDepthFail();
  79539. var previousAlphaMode = engine.getAlphaMode();
  79540. // Texture
  79541. currentEffect.setTexture("textureSampler", this._blurTexture);
  79542. // VBOs
  79543. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  79544. // Stencil operations
  79545. engine.setStencilOperationPass(BABYLON.Engine.REPLACE);
  79546. engine.setStencilOperationFail(BABYLON.Engine.KEEP);
  79547. engine.setStencilOperationDepthFail(BABYLON.Engine.KEEP);
  79548. // Draw order
  79549. engine.setAlphaMode(this._options.alphaBlendingMode);
  79550. engine.setStencilMask(0x00);
  79551. engine.setStencilBuffer(true);
  79552. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  79553. if (this.outerGlow) {
  79554. currentEffect.setFloat("offset", 0);
  79555. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  79556. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  79557. }
  79558. if (this.innerGlow) {
  79559. currentEffect.setFloat("offset", 1);
  79560. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  79561. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  79562. }
  79563. // Restore Cache
  79564. engine.setStencilFunction(previousStencilFunction);
  79565. engine.setStencilMask(previousStencilMask);
  79566. engine.setAlphaMode(previousAlphaMode);
  79567. engine.setStencilBuffer(previousStencilBuffer);
  79568. engine.setStencilOperationPass(previousStencilOperationPass);
  79569. engine.setStencilOperationFail(previousStencilOperationFail);
  79570. engine.setStencilOperationDepthFail(previousStencilOperationDepthFail);
  79571. engine._stencilState.reset();
  79572. this.onAfterComposeObservable.notifyObservers(this);
  79573. // Handle size changes.
  79574. var size = this._mainTexture.getSize();
  79575. this.setMainTextureSize();
  79576. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  79577. // Recreate RTT and post processes on size change.
  79578. this.onSizeChangedObservable.notifyObservers(this);
  79579. this.disposeTextureAndPostProcesses();
  79580. this.createTextureAndPostProcesses();
  79581. }
  79582. };
  79583. /**
  79584. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  79585. * @param mesh The mesh to exclude from the highlight layer
  79586. */
  79587. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  79588. if (!this._excludedMeshes) {
  79589. return;
  79590. }
  79591. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  79592. if (!meshExcluded) {
  79593. this._excludedMeshes[mesh.uniqueId] = {
  79594. mesh: mesh,
  79595. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  79596. mesh.getEngine().setStencilBuffer(false);
  79597. }),
  79598. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  79599. mesh.getEngine().setStencilBuffer(true);
  79600. }),
  79601. };
  79602. }
  79603. };
  79604. /**
  79605. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  79606. * @param mesh The mesh to highlight
  79607. */
  79608. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  79609. if (!this._excludedMeshes) {
  79610. return;
  79611. }
  79612. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  79613. if (meshExcluded) {
  79614. if (meshExcluded.beforeRender) {
  79615. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  79616. }
  79617. if (meshExcluded.afterRender) {
  79618. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  79619. }
  79620. }
  79621. this._excludedMeshes[mesh.uniqueId] = null;
  79622. };
  79623. /**
  79624. * Determine if a given mesh will be highlighted by the current HighlightLayer
  79625. * @param mesh mesh to test
  79626. * @returns true if the mesh will be highlighted by the current HighlightLayer
  79627. */
  79628. HighlightLayer.prototype.hasMesh = function (mesh) {
  79629. if (!this._meshes) {
  79630. return false;
  79631. }
  79632. return this._meshes[mesh.uniqueId] !== undefined && this._meshes[mesh.uniqueId] !== null;
  79633. };
  79634. /**
  79635. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  79636. * @param mesh The mesh to highlight
  79637. * @param color The color of the highlight
  79638. * @param glowEmissiveOnly Extract the glow from the emissive texture
  79639. */
  79640. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  79641. var _this = this;
  79642. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  79643. if (!this._meshes) {
  79644. return;
  79645. }
  79646. var meshHighlight = this._meshes[mesh.uniqueId];
  79647. if (meshHighlight) {
  79648. meshHighlight.color = color;
  79649. }
  79650. else {
  79651. this._meshes[mesh.uniqueId] = {
  79652. mesh: mesh,
  79653. color: color,
  79654. // Lambda required for capture due to Observable this context
  79655. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  79656. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  79657. _this.defaultStencilReference(mesh);
  79658. }
  79659. else {
  79660. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  79661. }
  79662. }),
  79663. observerDefault: mesh.onAfterRenderObservable.add(this.defaultStencilReference),
  79664. glowEmissiveOnly: glowEmissiveOnly
  79665. };
  79666. }
  79667. this._shouldRender = true;
  79668. };
  79669. /**
  79670. * Remove a mesh from the highlight layer in order to make it stop glowing.
  79671. * @param mesh The mesh to highlight
  79672. */
  79673. HighlightLayer.prototype.removeMesh = function (mesh) {
  79674. if (!this._meshes) {
  79675. return;
  79676. }
  79677. var meshHighlight = this._meshes[mesh.uniqueId];
  79678. if (meshHighlight) {
  79679. if (meshHighlight.observerHighlight) {
  79680. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  79681. }
  79682. if (meshHighlight.observerDefault) {
  79683. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  79684. }
  79685. delete this._meshes[mesh.uniqueId];
  79686. }
  79687. this._shouldRender = false;
  79688. for (var meshHighlightToCheck in this._meshes) {
  79689. if (this._meshes[meshHighlightToCheck]) {
  79690. this._shouldRender = true;
  79691. break;
  79692. }
  79693. }
  79694. };
  79695. /**
  79696. * Returns true if the layer contains information to display, otherwise false.
  79697. */
  79698. HighlightLayer.prototype.shouldRender = function () {
  79699. return this.isEnabled && this._shouldRender;
  79700. };
  79701. /**
  79702. * Sets the main texture desired size which is the closest power of two
  79703. * of the engine canvas size.
  79704. */
  79705. HighlightLayer.prototype.setMainTextureSize = function () {
  79706. if (this._options.mainTextureFixedSize) {
  79707. this._mainTextureDesiredSize.width = this._options.mainTextureFixedSize;
  79708. this._mainTextureDesiredSize.height = this._options.mainTextureFixedSize;
  79709. }
  79710. else {
  79711. this._mainTextureDesiredSize.width = this._engine.getRenderWidth() * this._options.mainTextureRatio;
  79712. this._mainTextureDesiredSize.height = this._engine.getRenderHeight() * this._options.mainTextureRatio;
  79713. this._mainTextureDesiredSize.width = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) : this._mainTextureDesiredSize.width;
  79714. this._mainTextureDesiredSize.height = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize) : this._mainTextureDesiredSize.height;
  79715. }
  79716. };
  79717. /**
  79718. * Force the stencil to the normal expected value for none glowing parts
  79719. */
  79720. HighlightLayer.prototype.defaultStencilReference = function (mesh) {
  79721. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.normalMeshStencilReference);
  79722. };
  79723. /**
  79724. * Dispose only the render target textures and post process.
  79725. */
  79726. HighlightLayer.prototype.disposeTextureAndPostProcesses = function () {
  79727. this._blurTexture.dispose();
  79728. this._mainTexture.dispose();
  79729. this._downSamplePostprocess.dispose();
  79730. this._horizontalBlurPostprocess.dispose();
  79731. this._verticalBlurPostprocess.dispose();
  79732. };
  79733. /**
  79734. * Dispose the highlight layer and free resources.
  79735. */
  79736. HighlightLayer.prototype.dispose = function () {
  79737. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  79738. if (vertexBuffer) {
  79739. vertexBuffer.dispose();
  79740. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  79741. }
  79742. if (this._indexBuffer) {
  79743. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  79744. this._indexBuffer = null;
  79745. }
  79746. // Clean textures and post processes
  79747. this.disposeTextureAndPostProcesses();
  79748. if (this._meshes) {
  79749. // Clean mesh references
  79750. for (var id in this._meshes) {
  79751. var meshHighlight = this._meshes[id];
  79752. if (meshHighlight && meshHighlight.mesh) {
  79753. if (meshHighlight.observerHighlight) {
  79754. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  79755. }
  79756. if (meshHighlight.observerDefault) {
  79757. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  79758. }
  79759. }
  79760. }
  79761. this._meshes = null;
  79762. }
  79763. if (this._excludedMeshes) {
  79764. for (var id in this._excludedMeshes) {
  79765. var meshHighlight = this._excludedMeshes[id];
  79766. if (meshHighlight) {
  79767. if (meshHighlight.beforeRender) {
  79768. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  79769. }
  79770. if (meshHighlight.afterRender) {
  79771. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  79772. }
  79773. }
  79774. }
  79775. this._excludedMeshes = null;
  79776. }
  79777. // Remove from scene
  79778. var index = this._scene.highlightLayers.indexOf(this, 0);
  79779. if (index > -1) {
  79780. this._scene.highlightLayers.splice(index, 1);
  79781. }
  79782. // Callback
  79783. this.onDisposeObservable.notifyObservers(this);
  79784. this.onDisposeObservable.clear();
  79785. this.onBeforeRenderMainTextureObservable.clear();
  79786. this.onBeforeBlurObservable.clear();
  79787. this.onBeforeComposeObservable.clear();
  79788. this.onAfterComposeObservable.clear();
  79789. this.onSizeChangedObservable.clear();
  79790. };
  79791. /**
  79792. * The neutral color used during the preparation of the glow effect.
  79793. * This is black by default as the blend operation is a blend operation.
  79794. */
  79795. HighlightLayer.neutralColor = new BABYLON.Color4(0, 0, 0, 0);
  79796. /**
  79797. * Stencil value used for glowing meshes.
  79798. */
  79799. HighlightLayer.glowingMeshStencilReference = 0x02;
  79800. /**
  79801. * Stencil value used for the other meshes in the scene.
  79802. */
  79803. HighlightLayer.normalMeshStencilReference = 0x01;
  79804. return HighlightLayer;
  79805. }());
  79806. BABYLON.HighlightLayer = HighlightLayer;
  79807. })(BABYLON || (BABYLON = {}));
  79808. //# sourceMappingURL=babylon.highlightlayer.js.map
  79809. var BABYLON;
  79810. (function (BABYLON) {
  79811. /**
  79812. * Defines the list of states available for a task inside a {BABYLON.AssetsManager}
  79813. */
  79814. var AssetTaskState;
  79815. (function (AssetTaskState) {
  79816. /**
  79817. * Initialization
  79818. */
  79819. AssetTaskState[AssetTaskState["INIT"] = 0] = "INIT";
  79820. /**
  79821. * Running
  79822. */
  79823. AssetTaskState[AssetTaskState["RUNNING"] = 1] = "RUNNING";
  79824. /**
  79825. * Done
  79826. */
  79827. AssetTaskState[AssetTaskState["DONE"] = 2] = "DONE";
  79828. /**
  79829. * Error
  79830. */
  79831. AssetTaskState[AssetTaskState["ERROR"] = 3] = "ERROR";
  79832. })(AssetTaskState = BABYLON.AssetTaskState || (BABYLON.AssetTaskState = {}));
  79833. /**
  79834. * Define an abstract asset task used with a {BABYLON.AssetsManager} class to load assets into a scene
  79835. */
  79836. var AbstractAssetTask = /** @class */ (function () {
  79837. /**
  79838. * Creates a new {BABYLON.AssetsManager}
  79839. * @param name defines the name of the task
  79840. */
  79841. function AbstractAssetTask(
  79842. /**
  79843. * Task name
  79844. */ name) {
  79845. this.name = name;
  79846. this._isCompleted = false;
  79847. this._taskState = AssetTaskState.INIT;
  79848. }
  79849. Object.defineProperty(AbstractAssetTask.prototype, "isCompleted", {
  79850. /**
  79851. * Get if the task is completed
  79852. */
  79853. get: function () {
  79854. return this._isCompleted;
  79855. },
  79856. enumerable: true,
  79857. configurable: true
  79858. });
  79859. Object.defineProperty(AbstractAssetTask.prototype, "taskState", {
  79860. /**
  79861. * Gets the current state of the task
  79862. */
  79863. get: function () {
  79864. return this._taskState;
  79865. },
  79866. enumerable: true,
  79867. configurable: true
  79868. });
  79869. Object.defineProperty(AbstractAssetTask.prototype, "errorObject", {
  79870. /**
  79871. * Gets the current error object (if task is in error)
  79872. */
  79873. get: function () {
  79874. return this._errorObject;
  79875. },
  79876. enumerable: true,
  79877. configurable: true
  79878. });
  79879. /**
  79880. * Internal only
  79881. * @ignore
  79882. */
  79883. AbstractAssetTask.prototype._setErrorObject = function (message, exception) {
  79884. if (this._errorObject) {
  79885. return;
  79886. }
  79887. this._errorObject = {
  79888. message: message,
  79889. exception: exception
  79890. };
  79891. };
  79892. /**
  79893. * Execute the current task
  79894. * @param scene defines the scene where you want your assets to be loaded
  79895. * @param onSuccess is a callback called when the task is successfully executed
  79896. * @param onError is a callback called if an error occurs
  79897. */
  79898. AbstractAssetTask.prototype.run = function (scene, onSuccess, onError) {
  79899. var _this = this;
  79900. this._taskState = AssetTaskState.RUNNING;
  79901. this.runTask(scene, function () {
  79902. _this.onDoneCallback(onSuccess, onError);
  79903. }, function (msg, exception) {
  79904. _this.onErrorCallback(onError, msg, exception);
  79905. });
  79906. };
  79907. /**
  79908. * Execute the current task
  79909. * @param scene defines the scene where you want your assets to be loaded
  79910. * @param onSuccess is a callback called when the task is successfully executed
  79911. * @param onError is a callback called if an error occurs
  79912. */
  79913. AbstractAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  79914. throw new Error("runTask is not implemented");
  79915. };
  79916. AbstractAssetTask.prototype.onErrorCallback = function (onError, message, exception) {
  79917. this._taskState = AssetTaskState.ERROR;
  79918. this._errorObject = {
  79919. message: message,
  79920. exception: exception
  79921. };
  79922. if (this.onError) {
  79923. this.onError(this, message, exception);
  79924. }
  79925. onError();
  79926. };
  79927. AbstractAssetTask.prototype.onDoneCallback = function (onSuccess, onError) {
  79928. try {
  79929. this._taskState = AssetTaskState.DONE;
  79930. this._isCompleted = true;
  79931. if (this.onSuccess) {
  79932. this.onSuccess(this);
  79933. }
  79934. onSuccess();
  79935. }
  79936. catch (e) {
  79937. this.onErrorCallback(onError, "Task is done, error executing success callback(s)", e);
  79938. }
  79939. };
  79940. return AbstractAssetTask;
  79941. }());
  79942. BABYLON.AbstractAssetTask = AbstractAssetTask;
  79943. /**
  79944. * Class used to share progress information about assets loading
  79945. */
  79946. var AssetsProgressEvent = /** @class */ (function () {
  79947. /**
  79948. * Creates a {BABYLON.AssetsProgressEvent}
  79949. * @param remainingCount defines the number of remaining tasks to process
  79950. * @param totalCount defines the total number of tasks
  79951. * @param task defines the task that was just processed
  79952. */
  79953. function AssetsProgressEvent(remainingCount, totalCount, task) {
  79954. this.remainingCount = remainingCount;
  79955. this.totalCount = totalCount;
  79956. this.task = task;
  79957. }
  79958. return AssetsProgressEvent;
  79959. }());
  79960. BABYLON.AssetsProgressEvent = AssetsProgressEvent;
  79961. /**
  79962. * Define a task used by {BABYLON.AssetsManager} to load meshes
  79963. */
  79964. var MeshAssetTask = /** @class */ (function (_super) {
  79965. __extends(MeshAssetTask, _super);
  79966. /**
  79967. * Creates a new {BABYLON.MeshAssetTask}
  79968. * @param name defines the name of the task
  79969. * @param meshesNames defines the list of mesh's names you want to load
  79970. * @param rootUrl defines the root url to use as a base to load your meshes and associated resources
  79971. * @param sceneFilename defines the filename of the scene to load from
  79972. */
  79973. function MeshAssetTask(
  79974. /**
  79975. * Defines the name of the task
  79976. */
  79977. name,
  79978. /**
  79979. * Defines the list of mesh's names you want to load
  79980. */
  79981. meshesNames,
  79982. /**
  79983. * Defines the root url to use as a base to load your meshes and associated resources
  79984. */
  79985. rootUrl,
  79986. /**
  79987. * Defines the filename of the scene to load from
  79988. */
  79989. sceneFilename) {
  79990. var _this = _super.call(this, name) || this;
  79991. _this.name = name;
  79992. _this.meshesNames = meshesNames;
  79993. _this.rootUrl = rootUrl;
  79994. _this.sceneFilename = sceneFilename;
  79995. return _this;
  79996. }
  79997. /**
  79998. * Execute the current task
  79999. * @param scene defines the scene where you want your assets to be loaded
  80000. * @param onSuccess is a callback called when the task is successfully executed
  80001. * @param onError is a callback called if an error occurs
  80002. */
  80003. MeshAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  80004. var _this = this;
  80005. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  80006. _this.loadedMeshes = meshes;
  80007. _this.loadedParticleSystems = particleSystems;
  80008. _this.loadedSkeletons = skeletons;
  80009. onSuccess();
  80010. }, null, function (scene, message, exception) {
  80011. onError(message, exception);
  80012. });
  80013. };
  80014. return MeshAssetTask;
  80015. }(AbstractAssetTask));
  80016. BABYLON.MeshAssetTask = MeshAssetTask;
  80017. /**
  80018. * Define a task used by {BABYLON.AssetsManager} to load text content
  80019. */
  80020. var TextFileAssetTask = /** @class */ (function (_super) {
  80021. __extends(TextFileAssetTask, _super);
  80022. /**
  80023. * Creates a new TextFileAssetTask object
  80024. * @param name defines the name of the task
  80025. * @param url defines the location of the file to load
  80026. */
  80027. function TextFileAssetTask(
  80028. /**
  80029. * Defines the name of the task
  80030. */
  80031. name,
  80032. /**
  80033. * Defines the location of the file to load
  80034. */
  80035. url) {
  80036. var _this = _super.call(this, name) || this;
  80037. _this.name = name;
  80038. _this.url = url;
  80039. return _this;
  80040. }
  80041. /**
  80042. * Execute the current task
  80043. * @param scene defines the scene where you want your assets to be loaded
  80044. * @param onSuccess is a callback called when the task is successfully executed
  80045. * @param onError is a callback called if an error occurs
  80046. */
  80047. TextFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  80048. var _this = this;
  80049. scene._loadFile(this.url, function (data) {
  80050. _this.text = data;
  80051. onSuccess();
  80052. }, undefined, false, true, function (request, exception) {
  80053. if (request) {
  80054. onError(request.status + " " + request.statusText, exception);
  80055. }
  80056. });
  80057. };
  80058. return TextFileAssetTask;
  80059. }(AbstractAssetTask));
  80060. BABYLON.TextFileAssetTask = TextFileAssetTask;
  80061. /**
  80062. * Define a task used by {BABYLON.AssetsManager} to load binary data
  80063. */
  80064. var BinaryFileAssetTask = /** @class */ (function (_super) {
  80065. __extends(BinaryFileAssetTask, _super);
  80066. /**
  80067. * Creates a new BinaryFileAssetTask object
  80068. * @param name defines the name of the new task
  80069. * @param url defines the location of the file to load
  80070. */
  80071. function BinaryFileAssetTask(
  80072. /**
  80073. * Defines the name of the task
  80074. */
  80075. name,
  80076. /**
  80077. * Defines the location of the file to load
  80078. */
  80079. url) {
  80080. var _this = _super.call(this, name) || this;
  80081. _this.name = name;
  80082. _this.url = url;
  80083. return _this;
  80084. }
  80085. /**
  80086. * Execute the current task
  80087. * @param scene defines the scene where you want your assets to be loaded
  80088. * @param onSuccess is a callback called when the task is successfully executed
  80089. * @param onError is a callback called if an error occurs
  80090. */
  80091. BinaryFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  80092. var _this = this;
  80093. scene._loadFile(this.url, function (data) {
  80094. _this.data = data;
  80095. onSuccess();
  80096. }, undefined, true, true, function (request, exception) {
  80097. if (request) {
  80098. onError(request.status + " " + request.statusText, exception);
  80099. }
  80100. });
  80101. };
  80102. return BinaryFileAssetTask;
  80103. }(AbstractAssetTask));
  80104. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  80105. /**
  80106. * Define a task used by {BABYLON.AssetsManager} to load images
  80107. */
  80108. var ImageAssetTask = /** @class */ (function (_super) {
  80109. __extends(ImageAssetTask, _super);
  80110. /**
  80111. * Creates a new ImageAssetTask
  80112. * @param name defines the name of the task
  80113. * @param url defines the location of the image to load
  80114. */
  80115. function ImageAssetTask(
  80116. /**
  80117. * Defines the name of the task
  80118. */
  80119. name,
  80120. /**
  80121. * Defines the location of the image to load
  80122. */
  80123. url) {
  80124. var _this = _super.call(this, name) || this;
  80125. _this.name = name;
  80126. _this.url = url;
  80127. return _this;
  80128. }
  80129. /**
  80130. * Execute the current task
  80131. * @param scene defines the scene where you want your assets to be loaded
  80132. * @param onSuccess is a callback called when the task is successfully executed
  80133. * @param onError is a callback called if an error occurs
  80134. */
  80135. ImageAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  80136. var _this = this;
  80137. var img = new Image();
  80138. BABYLON.Tools.SetCorsBehavior(this.url, img);
  80139. img.onload = function () {
  80140. _this.image = img;
  80141. onSuccess();
  80142. };
  80143. img.onerror = function (err) {
  80144. onError("Error loading image", err);
  80145. };
  80146. img.src = this.url;
  80147. };
  80148. return ImageAssetTask;
  80149. }(AbstractAssetTask));
  80150. BABYLON.ImageAssetTask = ImageAssetTask;
  80151. /**
  80152. * Define a task used by {BABYLON.AssetsManager} to load 2D textures
  80153. */
  80154. var TextureAssetTask = /** @class */ (function (_super) {
  80155. __extends(TextureAssetTask, _super);
  80156. /**
  80157. * Creates a new TextureAssetTask object
  80158. * @param name defines the name of the task
  80159. * @param url defines the location of the file to load
  80160. * @param noMipmap defines if mipmap should not be generated (default is false)
  80161. * @param invertY defines if texture must be inverted on Y axis (default is false)
  80162. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  80163. */
  80164. function TextureAssetTask(
  80165. /**
  80166. * Defines the name of the task
  80167. */
  80168. name,
  80169. /**
  80170. * Defines the location of the file to load
  80171. */
  80172. url,
  80173. /**
  80174. * Defines if mipmap should not be generated (default is false)
  80175. */
  80176. noMipmap,
  80177. /**
  80178. * Defines if texture must be inverted on Y axis (default is false)
  80179. */
  80180. invertY,
  80181. /**
  80182. * Defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  80183. */
  80184. samplingMode) {
  80185. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  80186. var _this = _super.call(this, name) || this;
  80187. _this.name = name;
  80188. _this.url = url;
  80189. _this.noMipmap = noMipmap;
  80190. _this.invertY = invertY;
  80191. _this.samplingMode = samplingMode;
  80192. return _this;
  80193. }
  80194. /**
  80195. * Execute the current task
  80196. * @param scene defines the scene where you want your assets to be loaded
  80197. * @param onSuccess is a callback called when the task is successfully executed
  80198. * @param onError is a callback called if an error occurs
  80199. */
  80200. TextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  80201. var onload = function () {
  80202. onSuccess();
  80203. };
  80204. var onerror = function (message, exception) {
  80205. onError(message, exception);
  80206. };
  80207. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  80208. };
  80209. return TextureAssetTask;
  80210. }(AbstractAssetTask));
  80211. BABYLON.TextureAssetTask = TextureAssetTask;
  80212. /**
  80213. * Define a task used by {BABYLON.AssetsManager} to load cube textures
  80214. */
  80215. var CubeTextureAssetTask = /** @class */ (function (_super) {
  80216. __extends(CubeTextureAssetTask, _super);
  80217. /**
  80218. * Creates a new CubeTextureAssetTask
  80219. * @param name defines the name of the task
  80220. * @param url defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  80221. * @param extensions defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  80222. * @param noMipmap defines if mipmaps should not be generated (default is false)
  80223. * @param files defines the explicit list of files (undefined by default)
  80224. */
  80225. function CubeTextureAssetTask(
  80226. /**
  80227. * Defines the name of the task
  80228. */
  80229. name,
  80230. /**
  80231. * Defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  80232. */
  80233. url,
  80234. /**
  80235. * Defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  80236. */
  80237. extensions,
  80238. /**
  80239. * Defines if mipmaps should not be generated (default is false)
  80240. */
  80241. noMipmap,
  80242. /**
  80243. * Defines the explicit list of files (undefined by default)
  80244. */
  80245. files) {
  80246. var _this = _super.call(this, name) || this;
  80247. _this.name = name;
  80248. _this.url = url;
  80249. _this.extensions = extensions;
  80250. _this.noMipmap = noMipmap;
  80251. _this.files = files;
  80252. return _this;
  80253. }
  80254. /**
  80255. * Execute the current task
  80256. * @param scene defines the scene where you want your assets to be loaded
  80257. * @param onSuccess is a callback called when the task is successfully executed
  80258. * @param onError is a callback called if an error occurs
  80259. */
  80260. CubeTextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  80261. var onload = function () {
  80262. onSuccess();
  80263. };
  80264. var onerror = function (message, exception) {
  80265. onError(message, exception);
  80266. };
  80267. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  80268. };
  80269. return CubeTextureAssetTask;
  80270. }(AbstractAssetTask));
  80271. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  80272. /**
  80273. * Define a task used by {BABYLON.AssetsManager} to load HDR cube textures
  80274. */
  80275. var HDRCubeTextureAssetTask = /** @class */ (function (_super) {
  80276. __extends(HDRCubeTextureAssetTask, _super);
  80277. /**
  80278. * Creates a new HDRCubeTextureAssetTask object
  80279. * @param name defines the name of the task
  80280. * @param url defines the location of the file to load
  80281. * @param size defines the desired size (the more it increases the longer the generation will be) If the size is omitted this implies you are using a preprocessed cubemap.
  80282. * @param noMipmap defines if mipmaps should not be generated (default is false)
  80283. * @param generateHarmonics specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  80284. * @param useInGammaSpace specifies if the texture will be use in gamma or linear space (the PBR material requires those texture in linear space, but the standard material would require them in Gamma space) (default is false)
  80285. * @param usePMREMGenerator specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time (default is false)
  80286. */
  80287. function HDRCubeTextureAssetTask(
  80288. /**
  80289. * Defines the name of the task
  80290. */
  80291. name,
  80292. /**
  80293. * Defines the location of the file to load
  80294. */
  80295. url,
  80296. /**
  80297. * Defines the desired size (the more it increases the longer the generation will be) If the size is omitted this implies you are using a preprocessed cubemap.
  80298. */
  80299. size,
  80300. /**
  80301. * Defines if mipmaps should not be generated (default is false)
  80302. */
  80303. noMipmap,
  80304. /**
  80305. * Specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  80306. */
  80307. generateHarmonics,
  80308. /**
  80309. * Specifies if the texture will be use in gamma or linear space (the PBR material requires those texture in linear space, but the standard material would require them in Gamma space) (default is false)
  80310. */
  80311. useInGammaSpace,
  80312. /**
  80313. * Specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time (default is false)
  80314. */
  80315. usePMREMGenerator) {
  80316. if (noMipmap === void 0) { noMipmap = false; }
  80317. if (generateHarmonics === void 0) { generateHarmonics = true; }
  80318. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  80319. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  80320. var _this = _super.call(this, name) || this;
  80321. _this.name = name;
  80322. _this.url = url;
  80323. _this.size = size;
  80324. _this.noMipmap = noMipmap;
  80325. _this.generateHarmonics = generateHarmonics;
  80326. _this.useInGammaSpace = useInGammaSpace;
  80327. _this.usePMREMGenerator = usePMREMGenerator;
  80328. return _this;
  80329. }
  80330. /**
  80331. * Execute the current task
  80332. * @param scene defines the scene where you want your assets to be loaded
  80333. * @param onSuccess is a callback called when the task is successfully executed
  80334. * @param onError is a callback called if an error occurs
  80335. */
  80336. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  80337. var onload = function () {
  80338. onSuccess();
  80339. };
  80340. var onerror = function (message, exception) {
  80341. onError(message, exception);
  80342. };
  80343. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.useInGammaSpace, this.usePMREMGenerator, onload, onerror);
  80344. };
  80345. return HDRCubeTextureAssetTask;
  80346. }(AbstractAssetTask));
  80347. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  80348. /**
  80349. * This class can be used to easily import assets into a scene
  80350. * @see http://doc.babylonjs.com/how_to/how_to_use_assetsmanager
  80351. */
  80352. var AssetsManager = /** @class */ (function () {
  80353. /**
  80354. * Creates a new AssetsManager
  80355. * @param scene defines the scene to work on
  80356. */
  80357. function AssetsManager(scene) {
  80358. this._isLoading = false;
  80359. this._tasks = new Array();
  80360. this._waitingTasksCount = 0;
  80361. this._totalTasksCount = 0;
  80362. /**
  80363. * Observable called when all tasks are processed
  80364. */
  80365. this.onTaskSuccessObservable = new BABYLON.Observable();
  80366. /**
  80367. * Observable called when a task had an error
  80368. */
  80369. this.onTaskErrorObservable = new BABYLON.Observable();
  80370. /**
  80371. * Observable called when a task is successful
  80372. */
  80373. this.onTasksDoneObservable = new BABYLON.Observable();
  80374. /**
  80375. * Observable called when a task is done (whatever the result is)
  80376. */
  80377. this.onProgressObservable = new BABYLON.Observable();
  80378. /**
  80379. * Gets or sets a boolean defining if the {BABYLON.AssetsManager} should use the default loading screen
  80380. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  80381. */
  80382. this.useDefaultLoadingScreen = true;
  80383. this._scene = scene;
  80384. }
  80385. /**
  80386. * Add a {BABYLON.MeshAssetTask} to the list of active tasks
  80387. * @param taskName defines the name of the new task
  80388. * @param meshesNames defines the name of meshes to load
  80389. * @param rootUrl defines the root url to use to locate files
  80390. * @param sceneFilename defines the filename of the scene file
  80391. * @returns a new {BABYLON.MeshAssetTask} object
  80392. */
  80393. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  80394. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  80395. this._tasks.push(task);
  80396. return task;
  80397. };
  80398. /**
  80399. * Add a {BABYLON.TextFileAssetTask} to the list of active tasks
  80400. * @param taskName defines the name of the new task
  80401. * @param url defines the url of the file to load
  80402. * @returns a new {BABYLON.TextFileAssetTask} object
  80403. */
  80404. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  80405. var task = new TextFileAssetTask(taskName, url);
  80406. this._tasks.push(task);
  80407. return task;
  80408. };
  80409. /**
  80410. * Add a {BABYLON.BinaryFileAssetTask} to the list of active tasks
  80411. * @param taskName defines the name of the new task
  80412. * @param url defines the url of the file to load
  80413. * @returns a new {BABYLON.BinaryFileAssetTask} object
  80414. */
  80415. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  80416. var task = new BinaryFileAssetTask(taskName, url);
  80417. this._tasks.push(task);
  80418. return task;
  80419. };
  80420. /**
  80421. * Add a {BABYLON.ImageAssetTask} to the list of active tasks
  80422. * @param taskName defines the name of the new task
  80423. * @param url defines the url of the file to load
  80424. * @returns a new {BABYLON.ImageAssetTask} object
  80425. */
  80426. AssetsManager.prototype.addImageTask = function (taskName, url) {
  80427. var task = new ImageAssetTask(taskName, url);
  80428. this._tasks.push(task);
  80429. return task;
  80430. };
  80431. /**
  80432. * Add a {BABYLON.TextureAssetTask} to the list of active tasks
  80433. * @param taskName defines the name of the new task
  80434. * @param url defines the url of the file to load
  80435. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  80436. * @param invertY defines if you want to invert Y axis of the loaded texture (false by default)
  80437. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  80438. * @returns a new {BABYLON.TextureAssetTask} object
  80439. */
  80440. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  80441. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  80442. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  80443. this._tasks.push(task);
  80444. return task;
  80445. };
  80446. /**
  80447. * Add a {BABYLON.CubeTextureAssetTask} to the list of active tasks
  80448. * @param taskName defines the name of the new task
  80449. * @param url defines the url of the file to load
  80450. * @param extensions defines the extension to use to load the cube map (can be null)
  80451. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  80452. * @param files defines the list of files to load (can be null)
  80453. * @returns a new {BABYLON.CubeTextureAssetTask} object
  80454. */
  80455. AssetsManager.prototype.addCubeTextureTask = function (taskName, url, extensions, noMipmap, files) {
  80456. var task = new CubeTextureAssetTask(taskName, url, extensions, noMipmap, files);
  80457. this._tasks.push(task);
  80458. return task;
  80459. };
  80460. /**
  80461. *
  80462. * Add a {BABYLON.HDRCubeTextureAssetTask} to the list of active tasks
  80463. * @param taskName defines the name of the new task
  80464. * @param url defines the url of the file to load
  80465. * @param size defines the size you want for the cubemap (can be null)
  80466. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  80467. * @param generateHarmonics defines if you want to automatically generate (true by default)
  80468. * @param useInGammaSpace defines if the texture must be considered in gamma space (false by default)
  80469. * @param usePMREMGenerator is a reserved parameter and must be set to false or ignored
  80470. * @returns a new {BABYLON.HDRCubeTextureAssetTask} object
  80471. */
  80472. AssetsManager.prototype.addHDRCubeTextureTask = function (taskName, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  80473. if (noMipmap === void 0) { noMipmap = false; }
  80474. if (generateHarmonics === void 0) { generateHarmonics = true; }
  80475. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  80476. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  80477. var task = new HDRCubeTextureAssetTask(taskName, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator);
  80478. this._tasks.push(task);
  80479. return task;
  80480. };
  80481. AssetsManager.prototype._decreaseWaitingTasksCount = function (task) {
  80482. var _this = this;
  80483. this._waitingTasksCount--;
  80484. try {
  80485. if (task.taskState === AssetTaskState.DONE) {
  80486. // Let's remove successfull tasks
  80487. BABYLON.Tools.SetImmediate(function () {
  80488. var index = _this._tasks.indexOf(task);
  80489. if (index > -1) {
  80490. _this._tasks.splice(index, 1);
  80491. }
  80492. });
  80493. }
  80494. if (this.onProgress) {
  80495. this.onProgress(this._waitingTasksCount, this._totalTasksCount, task);
  80496. }
  80497. this.onProgressObservable.notifyObservers(new AssetsProgressEvent(this._waitingTasksCount, this._totalTasksCount, task));
  80498. }
  80499. catch (e) {
  80500. BABYLON.Tools.Error("Error running progress callbacks.");
  80501. console.log(e);
  80502. }
  80503. if (this._waitingTasksCount === 0) {
  80504. try {
  80505. if (this.onFinish) {
  80506. this.onFinish(this._tasks);
  80507. }
  80508. this.onTasksDoneObservable.notifyObservers(this._tasks);
  80509. }
  80510. catch (e) {
  80511. BABYLON.Tools.Error("Error running tasks-done callbacks.");
  80512. console.log(e);
  80513. }
  80514. this._isLoading = false;
  80515. this._scene.getEngine().hideLoadingUI();
  80516. }
  80517. };
  80518. AssetsManager.prototype._runTask = function (task) {
  80519. var _this = this;
  80520. var done = function () {
  80521. try {
  80522. if (_this.onTaskSuccess) {
  80523. _this.onTaskSuccess(task);
  80524. }
  80525. _this.onTaskSuccessObservable.notifyObservers(task);
  80526. _this._decreaseWaitingTasksCount(task);
  80527. }
  80528. catch (e) {
  80529. error("Error executing task success callbacks", e);
  80530. }
  80531. };
  80532. var error = function (message, exception) {
  80533. task._setErrorObject(message, exception);
  80534. if (_this.onTaskError) {
  80535. _this.onTaskError(task);
  80536. }
  80537. _this.onTaskErrorObservable.notifyObservers(task);
  80538. _this._decreaseWaitingTasksCount(task);
  80539. };
  80540. task.run(this._scene, done, error);
  80541. };
  80542. /**
  80543. * Reset the {BABYLON.AssetsManager} and remove all tasks
  80544. * @return the current instance of the {BABYLON.AssetsManager}
  80545. */
  80546. AssetsManager.prototype.reset = function () {
  80547. this._isLoading = false;
  80548. this._tasks = new Array();
  80549. return this;
  80550. };
  80551. /**
  80552. * Start the loading process
  80553. * @return the current instance of the {BABYLON.AssetsManager}
  80554. */
  80555. AssetsManager.prototype.load = function () {
  80556. if (this._isLoading) {
  80557. return this;
  80558. }
  80559. this._isLoading = true;
  80560. this._waitingTasksCount = this._tasks.length;
  80561. this._totalTasksCount = this._tasks.length;
  80562. if (this._waitingTasksCount === 0) {
  80563. if (this.onFinish) {
  80564. this.onFinish(this._tasks);
  80565. }
  80566. this.onTasksDoneObservable.notifyObservers(this._tasks);
  80567. return this;
  80568. }
  80569. if (this.useDefaultLoadingScreen) {
  80570. this._scene.getEngine().displayLoadingUI();
  80571. }
  80572. for (var index = 0; index < this._tasks.length; index++) {
  80573. var task = this._tasks[index];
  80574. this._runTask(task);
  80575. }
  80576. return this;
  80577. };
  80578. return AssetsManager;
  80579. }());
  80580. BABYLON.AssetsManager = AssetsManager;
  80581. })(BABYLON || (BABYLON = {}));
  80582. //# sourceMappingURL=babylon.assetsManager.js.map
  80583. var BABYLON;
  80584. (function (BABYLON) {
  80585. var serializedGeometries = [];
  80586. var serializeGeometry = function (geometry, serializationGeometries) {
  80587. if (serializedGeometries[geometry.id]) {
  80588. return;
  80589. }
  80590. if (geometry.doNotSerialize) {
  80591. return;
  80592. }
  80593. if (geometry instanceof BABYLON.BoxGeometry) {
  80594. serializationGeometries.boxes.push(geometry.serialize());
  80595. }
  80596. else if (geometry instanceof BABYLON.SphereGeometry) {
  80597. serializationGeometries.spheres.push(geometry.serialize());
  80598. }
  80599. else if (geometry instanceof BABYLON.CylinderGeometry) {
  80600. serializationGeometries.cylinders.push(geometry.serialize());
  80601. }
  80602. else if (geometry instanceof BABYLON.TorusGeometry) {
  80603. serializationGeometries.toruses.push(geometry.serialize());
  80604. }
  80605. else if (geometry instanceof BABYLON.GroundGeometry) {
  80606. serializationGeometries.grounds.push(geometry.serialize());
  80607. }
  80608. else if (geometry instanceof BABYLON.Plane) {
  80609. serializationGeometries.planes.push(geometry.serialize());
  80610. }
  80611. else if (geometry instanceof BABYLON.TorusKnotGeometry) {
  80612. serializationGeometries.torusKnots.push(geometry.serialize());
  80613. }
  80614. else if (geometry instanceof BABYLON._PrimitiveGeometry) {
  80615. throw new Error("Unknown primitive type");
  80616. }
  80617. else {
  80618. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  80619. }
  80620. serializedGeometries[geometry.id] = true;
  80621. };
  80622. var serializeMesh = function (mesh, serializationScene) {
  80623. var serializationObject = {};
  80624. // Geometry
  80625. var geometry = mesh._geometry;
  80626. if (geometry) {
  80627. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  80628. // 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
  80629. serializeGeometry(geometry, serializationScene.geometries);
  80630. }
  80631. }
  80632. // Custom
  80633. if (mesh.serialize) {
  80634. mesh.serialize(serializationObject);
  80635. }
  80636. return serializationObject;
  80637. };
  80638. var finalizeSingleMesh = function (mesh, serializationObject) {
  80639. //only works if the mesh is already loaded
  80640. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  80641. //serialize material
  80642. if (mesh.material) {
  80643. if (mesh.material instanceof BABYLON.StandardMaterial) {
  80644. serializationObject.materials = serializationObject.materials || [];
  80645. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  80646. serializationObject.materials.push(mesh.material.serialize());
  80647. }
  80648. }
  80649. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  80650. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  80651. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  80652. serializationObject.multiMaterials.push(mesh.material.serialize());
  80653. }
  80654. }
  80655. }
  80656. //serialize geometry
  80657. var geometry = mesh._geometry;
  80658. if (geometry) {
  80659. if (!serializationObject.geometries) {
  80660. serializationObject.geometries = {};
  80661. serializationObject.geometries.boxes = [];
  80662. serializationObject.geometries.spheres = [];
  80663. serializationObject.geometries.cylinders = [];
  80664. serializationObject.geometries.toruses = [];
  80665. serializationObject.geometries.grounds = [];
  80666. serializationObject.geometries.planes = [];
  80667. serializationObject.geometries.torusKnots = [];
  80668. serializationObject.geometries.vertexData = [];
  80669. }
  80670. serializeGeometry(geometry, serializationObject.geometries);
  80671. }
  80672. // Skeletons
  80673. if (mesh.skeleton) {
  80674. serializationObject.skeletons = serializationObject.skeletons || [];
  80675. serializationObject.skeletons.push(mesh.skeleton.serialize());
  80676. }
  80677. //serialize the actual mesh
  80678. serializationObject.meshes = serializationObject.meshes || [];
  80679. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  80680. }
  80681. };
  80682. var SceneSerializer = /** @class */ (function () {
  80683. function SceneSerializer() {
  80684. }
  80685. SceneSerializer.ClearCache = function () {
  80686. serializedGeometries = [];
  80687. };
  80688. SceneSerializer.Serialize = function (scene) {
  80689. var serializationObject = {};
  80690. SceneSerializer.ClearCache();
  80691. // Scene
  80692. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  80693. serializationObject.autoClear = scene.autoClear;
  80694. serializationObject.clearColor = scene.clearColor.asArray();
  80695. serializationObject.ambientColor = scene.ambientColor.asArray();
  80696. serializationObject.gravity = scene.gravity.asArray();
  80697. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  80698. serializationObject.workerCollisions = scene.workerCollisions;
  80699. // Fog
  80700. if (scene.fogMode && scene.fogMode !== 0) {
  80701. serializationObject.fogMode = scene.fogMode;
  80702. serializationObject.fogColor = scene.fogColor.asArray();
  80703. serializationObject.fogStart = scene.fogStart;
  80704. serializationObject.fogEnd = scene.fogEnd;
  80705. serializationObject.fogDensity = scene.fogDensity;
  80706. }
  80707. //Physics
  80708. if (scene.isPhysicsEnabled()) {
  80709. var physicEngine = scene.getPhysicsEngine();
  80710. if (physicEngine) {
  80711. serializationObject.physicsEnabled = true;
  80712. serializationObject.physicsGravity = physicEngine.gravity.asArray();
  80713. serializationObject.physicsEngine = physicEngine.getPhysicsPluginName();
  80714. }
  80715. }
  80716. // Metadata
  80717. if (scene.metadata) {
  80718. serializationObject.metadata = scene.metadata;
  80719. }
  80720. // Morph targets
  80721. serializationObject.morphTargetManagers = [];
  80722. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  80723. var abstractMesh = _a[_i];
  80724. var manager = abstractMesh.morphTargetManager;
  80725. if (manager) {
  80726. serializationObject.morphTargetManagers.push(manager.serialize());
  80727. }
  80728. }
  80729. // Lights
  80730. serializationObject.lights = [];
  80731. var index;
  80732. var light;
  80733. for (index = 0; index < scene.lights.length; index++) {
  80734. light = scene.lights[index];
  80735. if (!light.doNotSerialize) {
  80736. serializationObject.lights.push(light.serialize());
  80737. }
  80738. }
  80739. // Cameras
  80740. serializationObject.cameras = [];
  80741. for (index = 0; index < scene.cameras.length; index++) {
  80742. var camera = scene.cameras[index];
  80743. if (!camera.doNotSerialize) {
  80744. serializationObject.cameras.push(camera.serialize());
  80745. }
  80746. }
  80747. if (scene.activeCamera) {
  80748. serializationObject.activeCameraID = scene.activeCamera.id;
  80749. }
  80750. // Animations
  80751. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  80752. // Materials
  80753. serializationObject.materials = [];
  80754. serializationObject.multiMaterials = [];
  80755. var material;
  80756. for (index = 0; index < scene.materials.length; index++) {
  80757. material = scene.materials[index];
  80758. if (!material.doNotSerialize) {
  80759. serializationObject.materials.push(material.serialize());
  80760. }
  80761. }
  80762. // MultiMaterials
  80763. serializationObject.multiMaterials = [];
  80764. for (index = 0; index < scene.multiMaterials.length; index++) {
  80765. var multiMaterial = scene.multiMaterials[index];
  80766. serializationObject.multiMaterials.push(multiMaterial.serialize());
  80767. }
  80768. // Environment texture
  80769. if (scene.environmentTexture) {
  80770. serializationObject.environmentTexture = scene.environmentTexture.name;
  80771. }
  80772. // Skeletons
  80773. serializationObject.skeletons = [];
  80774. for (index = 0; index < scene.skeletons.length; index++) {
  80775. serializationObject.skeletons.push(scene.skeletons[index].serialize());
  80776. }
  80777. // Transform nodes
  80778. serializationObject.transformNodes = [];
  80779. for (index = 0; index < scene.transformNodes.length; index++) {
  80780. serializationObject.transformNodes.push(scene.transformNodes[index].serialize());
  80781. }
  80782. // Geometries
  80783. serializationObject.geometries = {};
  80784. serializationObject.geometries.boxes = [];
  80785. serializationObject.geometries.spheres = [];
  80786. serializationObject.geometries.cylinders = [];
  80787. serializationObject.geometries.toruses = [];
  80788. serializationObject.geometries.grounds = [];
  80789. serializationObject.geometries.planes = [];
  80790. serializationObject.geometries.torusKnots = [];
  80791. serializationObject.geometries.vertexData = [];
  80792. serializedGeometries = [];
  80793. var geometries = scene.getGeometries();
  80794. for (index = 0; index < geometries.length; index++) {
  80795. var geometry = geometries[index];
  80796. if (geometry.isReady()) {
  80797. serializeGeometry(geometry, serializationObject.geometries);
  80798. }
  80799. }
  80800. // Meshes
  80801. serializationObject.meshes = [];
  80802. for (index = 0; index < scene.meshes.length; index++) {
  80803. var abstractMesh = scene.meshes[index];
  80804. if (abstractMesh instanceof BABYLON.Mesh) {
  80805. var mesh = abstractMesh;
  80806. if (!mesh.doNotSerialize) {
  80807. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  80808. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  80809. }
  80810. }
  80811. }
  80812. }
  80813. // Particles Systems
  80814. serializationObject.particleSystems = [];
  80815. for (index = 0; index < scene.particleSystems.length; index++) {
  80816. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  80817. }
  80818. // Lens flares
  80819. serializationObject.lensFlareSystems = [];
  80820. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  80821. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  80822. }
  80823. // Shadows
  80824. serializationObject.shadowGenerators = [];
  80825. for (index = 0; index < scene.lights.length; index++) {
  80826. light = scene.lights[index];
  80827. var shadowGenerator = light.getShadowGenerator();
  80828. if (shadowGenerator) {
  80829. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  80830. }
  80831. }
  80832. // Action Manager
  80833. if (scene.actionManager) {
  80834. serializationObject.actions = scene.actionManager.serialize("scene");
  80835. }
  80836. // Audio
  80837. serializationObject.sounds = [];
  80838. for (index = 0; index < scene.soundTracks.length; index++) {
  80839. var soundtrack = scene.soundTracks[index];
  80840. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  80841. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  80842. }
  80843. }
  80844. return serializationObject;
  80845. };
  80846. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  80847. if (withParents === void 0) { withParents = false; }
  80848. if (withChildren === void 0) { withChildren = false; }
  80849. var serializationObject = {};
  80850. SceneSerializer.ClearCache();
  80851. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  80852. if (withParents || withChildren) {
  80853. //deliberate for loop! not for each, appended should be processed as well.
  80854. for (var i = 0; i < toSerialize.length; ++i) {
  80855. if (withChildren) {
  80856. toSerialize[i].getDescendants().forEach(function (node) {
  80857. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  80858. toSerialize.push(node);
  80859. }
  80860. });
  80861. }
  80862. //make sure the array doesn't contain the object already
  80863. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  80864. toSerialize.push(toSerialize[i].parent);
  80865. }
  80866. }
  80867. }
  80868. toSerialize.forEach(function (mesh) {
  80869. finalizeSingleMesh(mesh, serializationObject);
  80870. });
  80871. return serializationObject;
  80872. };
  80873. return SceneSerializer;
  80874. }());
  80875. BABYLON.SceneSerializer = SceneSerializer;
  80876. })(BABYLON || (BABYLON = {}));
  80877. //# sourceMappingURL=babylon.sceneSerializer.js.map
  80878. var BABYLON;
  80879. (function (BABYLON) {
  80880. var ReflectionProbe = /** @class */ (function () {
  80881. function ReflectionProbe(name, size, scene, generateMipMaps) {
  80882. if (generateMipMaps === void 0) { generateMipMaps = true; }
  80883. var _this = this;
  80884. this.name = name;
  80885. this._viewMatrix = BABYLON.Matrix.Identity();
  80886. this._target = BABYLON.Vector3.Zero();
  80887. this._add = BABYLON.Vector3.Zero();
  80888. this.invertYAxis = false;
  80889. this.position = BABYLON.Vector3.Zero();
  80890. this._scene = scene;
  80891. this._scene.reflectionProbes.push(this);
  80892. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  80893. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  80894. switch (faceIndex) {
  80895. case 0:
  80896. _this._add.copyFromFloats(1, 0, 0);
  80897. break;
  80898. case 1:
  80899. _this._add.copyFromFloats(-1, 0, 0);
  80900. break;
  80901. case 2:
  80902. _this._add.copyFromFloats(0, _this.invertYAxis ? 1 : -1, 0);
  80903. break;
  80904. case 3:
  80905. _this._add.copyFromFloats(0, _this.invertYAxis ? -1 : 1, 0);
  80906. break;
  80907. case 4:
  80908. _this._add.copyFromFloats(0, 0, 1);
  80909. break;
  80910. case 5:
  80911. _this._add.copyFromFloats(0, 0, -1);
  80912. break;
  80913. }
  80914. if (_this._attachedMesh) {
  80915. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  80916. }
  80917. _this.position.addToRef(_this._add, _this._target);
  80918. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  80919. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  80920. scene._forcedViewPosition = _this.position;
  80921. });
  80922. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  80923. scene._forcedViewPosition = null;
  80924. scene.updateTransformMatrix(true);
  80925. });
  80926. if (scene.activeCamera) {
  80927. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  80928. }
  80929. }
  80930. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  80931. get: function () {
  80932. return this._renderTargetTexture.samples;
  80933. },
  80934. set: function (value) {
  80935. this._renderTargetTexture.samples = value;
  80936. },
  80937. enumerable: true,
  80938. configurable: true
  80939. });
  80940. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  80941. get: function () {
  80942. return this._renderTargetTexture.refreshRate;
  80943. },
  80944. set: function (value) {
  80945. this._renderTargetTexture.refreshRate = value;
  80946. },
  80947. enumerable: true,
  80948. configurable: true
  80949. });
  80950. ReflectionProbe.prototype.getScene = function () {
  80951. return this._scene;
  80952. };
  80953. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  80954. get: function () {
  80955. return this._renderTargetTexture;
  80956. },
  80957. enumerable: true,
  80958. configurable: true
  80959. });
  80960. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  80961. get: function () {
  80962. return this._renderTargetTexture.renderList;
  80963. },
  80964. enumerable: true,
  80965. configurable: true
  80966. });
  80967. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  80968. this._attachedMesh = mesh;
  80969. };
  80970. /**
  80971. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  80972. *
  80973. * @param renderingGroupId The rendering group id corresponding to its index
  80974. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  80975. */
  80976. ReflectionProbe.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  80977. this._renderTargetTexture.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  80978. };
  80979. ReflectionProbe.prototype.dispose = function () {
  80980. var index = this._scene.reflectionProbes.indexOf(this);
  80981. if (index !== -1) {
  80982. // Remove from the scene if found
  80983. this._scene.reflectionProbes.splice(index, 1);
  80984. }
  80985. if (this._renderTargetTexture) {
  80986. this._renderTargetTexture.dispose();
  80987. this._renderTargetTexture = null;
  80988. }
  80989. };
  80990. return ReflectionProbe;
  80991. }());
  80992. BABYLON.ReflectionProbe = ReflectionProbe;
  80993. })(BABYLON || (BABYLON = {}));
  80994. //# sourceMappingURL=babylon.reflectionProbe.js.map
  80995. var BABYLON;
  80996. (function (BABYLON) {
  80997. var Layer = /** @class */ (function () {
  80998. function Layer(name, imgUrl, scene, isBackground, color) {
  80999. this.name = name;
  81000. this.scale = new BABYLON.Vector2(1, 1);
  81001. this.offset = new BABYLON.Vector2(0, 0);
  81002. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  81003. this.layerMask = 0x0FFFFFFF;
  81004. this._vertexBuffers = {};
  81005. // Events
  81006. /**
  81007. * An event triggered when the layer is disposed.
  81008. * @type {BABYLON.Observable}
  81009. */
  81010. this.onDisposeObservable = new BABYLON.Observable();
  81011. /**
  81012. * An event triggered before rendering the scene
  81013. * @type {BABYLON.Observable}
  81014. */
  81015. this.onBeforeRenderObservable = new BABYLON.Observable();
  81016. /**
  81017. * An event triggered after rendering the scene
  81018. * @type {BABYLON.Observable}
  81019. */
  81020. this.onAfterRenderObservable = new BABYLON.Observable();
  81021. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  81022. this.isBackground = isBackground === undefined ? true : isBackground;
  81023. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  81024. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  81025. this._scene.layers.push(this);
  81026. var engine = this._scene.getEngine();
  81027. // VBO
  81028. var vertices = [];
  81029. vertices.push(1, 1);
  81030. vertices.push(-1, 1);
  81031. vertices.push(-1, -1);
  81032. vertices.push(1, -1);
  81033. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  81034. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  81035. this._createIndexBuffer();
  81036. // Effects
  81037. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  81038. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  81039. }
  81040. Object.defineProperty(Layer.prototype, "onDispose", {
  81041. set: function (callback) {
  81042. if (this._onDisposeObserver) {
  81043. this.onDisposeObservable.remove(this._onDisposeObserver);
  81044. }
  81045. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  81046. },
  81047. enumerable: true,
  81048. configurable: true
  81049. });
  81050. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  81051. set: function (callback) {
  81052. if (this._onBeforeRenderObserver) {
  81053. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  81054. }
  81055. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  81056. },
  81057. enumerable: true,
  81058. configurable: true
  81059. });
  81060. Object.defineProperty(Layer.prototype, "onAfterRender", {
  81061. set: function (callback) {
  81062. if (this._onAfterRenderObserver) {
  81063. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  81064. }
  81065. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  81066. },
  81067. enumerable: true,
  81068. configurable: true
  81069. });
  81070. Layer.prototype._createIndexBuffer = function () {
  81071. var engine = this._scene.getEngine();
  81072. // Indices
  81073. var indices = [];
  81074. indices.push(0);
  81075. indices.push(1);
  81076. indices.push(2);
  81077. indices.push(0);
  81078. indices.push(2);
  81079. indices.push(3);
  81080. this._indexBuffer = engine.createIndexBuffer(indices);
  81081. };
  81082. Layer.prototype._rebuild = function () {
  81083. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  81084. if (vb) {
  81085. vb._rebuild();
  81086. }
  81087. this._createIndexBuffer();
  81088. };
  81089. Layer.prototype.render = function () {
  81090. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  81091. // Check
  81092. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  81093. return;
  81094. var engine = this._scene.getEngine();
  81095. this.onBeforeRenderObservable.notifyObservers(this);
  81096. // Render
  81097. engine.enableEffect(currentEffect);
  81098. engine.setState(false);
  81099. // Texture
  81100. currentEffect.setTexture("textureSampler", this.texture);
  81101. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  81102. // Color
  81103. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  81104. // Scale / offset
  81105. currentEffect.setVector2("offset", this.offset);
  81106. currentEffect.setVector2("scale", this.scale);
  81107. // VBOs
  81108. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  81109. // Draw order
  81110. if (!this.alphaTest) {
  81111. engine.setAlphaMode(this.alphaBlendingMode);
  81112. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  81113. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  81114. }
  81115. else {
  81116. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  81117. }
  81118. this.onAfterRenderObservable.notifyObservers(this);
  81119. };
  81120. Layer.prototype.dispose = function () {
  81121. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  81122. if (vertexBuffer) {
  81123. vertexBuffer.dispose();
  81124. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  81125. }
  81126. if (this._indexBuffer) {
  81127. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  81128. this._indexBuffer = null;
  81129. }
  81130. if (this.texture) {
  81131. this.texture.dispose();
  81132. this.texture = null;
  81133. }
  81134. // Remove from scene
  81135. var index = this._scene.layers.indexOf(this);
  81136. this._scene.layers.splice(index, 1);
  81137. // Callback
  81138. this.onDisposeObservable.notifyObservers(this);
  81139. this.onDisposeObservable.clear();
  81140. this.onAfterRenderObservable.clear();
  81141. this.onBeforeRenderObservable.clear();
  81142. };
  81143. return Layer;
  81144. }());
  81145. BABYLON.Layer = Layer;
  81146. })(BABYLON || (BABYLON = {}));
  81147. //# sourceMappingURL=babylon.layer.js.map
  81148. var BABYLON;
  81149. (function (BABYLON) {
  81150. var TextureTools = /** @class */ (function () {
  81151. function TextureTools() {
  81152. }
  81153. /**
  81154. * Uses the GPU to create a copy texture rescaled at a given size
  81155. * @param texture Texture to copy from
  81156. * @param width Desired width
  81157. * @param height Desired height
  81158. * @return Generated texture
  81159. */
  81160. TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
  81161. if (useBilinearMode === void 0) { useBilinearMode = true; }
  81162. var scene = texture.getScene();
  81163. var engine = scene.getEngine();
  81164. var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
  81165. rtt.wrapU = texture.wrapU;
  81166. rtt.wrapV = texture.wrapV;
  81167. rtt.uOffset = texture.uOffset;
  81168. rtt.vOffset = texture.vOffset;
  81169. rtt.uScale = texture.uScale;
  81170. rtt.vScale = texture.vScale;
  81171. rtt.uAng = texture.uAng;
  81172. rtt.vAng = texture.vAng;
  81173. rtt.wAng = texture.wAng;
  81174. rtt.coordinatesIndex = texture.coordinatesIndex;
  81175. rtt.level = texture.level;
  81176. rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  81177. rtt._texture.isReady = false;
  81178. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  81179. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  81180. var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  81181. passPostProcess.getEffect().executeWhenCompiled(function () {
  81182. passPostProcess.onApply = function (effect) {
  81183. effect.setTexture("textureSampler", texture);
  81184. };
  81185. var internalTexture = rtt.getInternalTexture();
  81186. if (internalTexture) {
  81187. scene.postProcessManager.directRender([passPostProcess], internalTexture);
  81188. engine.unBindFramebuffer(internalTexture);
  81189. rtt.disposeFramebufferObjects();
  81190. passPostProcess.dispose();
  81191. internalTexture.isReady = true;
  81192. }
  81193. });
  81194. return rtt;
  81195. };
  81196. TextureTools.GetEnvironmentBRDFTexture = function (scene) {
  81197. if (!scene._environmentBRDFTexture) {
  81198. var texture = BABYLON.Texture.CreateFromBase64String(this._environmentBRDFBase64Texture, "EnvironmentBRDFTexture", scene, true, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  81199. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  81200. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  81201. scene._environmentBRDFTexture = texture;
  81202. }
  81203. return scene._environmentBRDFTexture;
  81204. };
  81205. 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=";
  81206. return TextureTools;
  81207. }());
  81208. BABYLON.TextureTools = TextureTools;
  81209. })(BABYLON || (BABYLON = {}));
  81210. //# sourceMappingURL=babylon.textureTools.js.map
  81211. var BABYLON;
  81212. (function (BABYLON) {
  81213. var FramingBehavior = /** @class */ (function () {
  81214. function FramingBehavior() {
  81215. this._mode = FramingBehavior.FitFrustumSidesMode;
  81216. this._radiusScale = 1.0;
  81217. this._positionScale = 0.5;
  81218. this._defaultElevation = 0.3;
  81219. this._elevationReturnTime = 1500;
  81220. this._elevationReturnWaitTime = 1000;
  81221. this._zoomStopsAnimation = false;
  81222. this._framingTime = 1500;
  81223. this._isPointerDown = false;
  81224. this._lastInteractionTime = -Infinity;
  81225. // Framing control
  81226. this._animatables = new Array();
  81227. this._betaIsAnimating = false;
  81228. }
  81229. Object.defineProperty(FramingBehavior.prototype, "name", {
  81230. get: function () {
  81231. return "Framing";
  81232. },
  81233. enumerable: true,
  81234. configurable: true
  81235. });
  81236. Object.defineProperty(FramingBehavior.prototype, "mode", {
  81237. /**
  81238. * Gets current mode used by the behavior.
  81239. */
  81240. get: function () {
  81241. return this._mode;
  81242. },
  81243. /**
  81244. * Sets the current mode used by the behavior
  81245. */
  81246. set: function (mode) {
  81247. this._mode = mode;
  81248. },
  81249. enumerable: true,
  81250. configurable: true
  81251. });
  81252. Object.defineProperty(FramingBehavior.prototype, "radiusScale", {
  81253. /**
  81254. * Gets the scale applied to the radius
  81255. */
  81256. get: function () {
  81257. return this._radiusScale;
  81258. },
  81259. /**
  81260. * Sets the scale applied to the radius (1 by default)
  81261. */
  81262. set: function (radius) {
  81263. this._radiusScale = radius;
  81264. },
  81265. enumerable: true,
  81266. configurable: true
  81267. });
  81268. Object.defineProperty(FramingBehavior.prototype, "positionScale", {
  81269. /**
  81270. * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  81271. */
  81272. get: function () {
  81273. return this._positionScale;
  81274. },
  81275. /**
  81276. * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  81277. */
  81278. set: function (scale) {
  81279. this._positionScale = scale;
  81280. },
  81281. enumerable: true,
  81282. configurable: true
  81283. });
  81284. Object.defineProperty(FramingBehavior.prototype, "defaultElevation", {
  81285. /**
  81286. * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle
  81287. * behaviour is triggered, in radians.
  81288. */
  81289. get: function () {
  81290. return this._defaultElevation;
  81291. },
  81292. /**
  81293. * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle
  81294. * behaviour is triggered, in radians.
  81295. */
  81296. set: function (elevation) {
  81297. this._defaultElevation = elevation;
  81298. },
  81299. enumerable: true,
  81300. configurable: true
  81301. });
  81302. Object.defineProperty(FramingBehavior.prototype, "elevationReturnTime", {
  81303. /**
  81304. * Gets the time (in milliseconds) taken to return to the default beta position.
  81305. * Negative value indicates camera should not return to default.
  81306. */
  81307. get: function () {
  81308. return this._elevationReturnTime;
  81309. },
  81310. /**
  81311. * Sets the time (in milliseconds) taken to return to the default beta position.
  81312. * Negative value indicates camera should not return to default.
  81313. */
  81314. set: function (speed) {
  81315. this._elevationReturnTime = speed;
  81316. },
  81317. enumerable: true,
  81318. configurable: true
  81319. });
  81320. Object.defineProperty(FramingBehavior.prototype, "elevationReturnWaitTime", {
  81321. /**
  81322. * Gets the delay (in milliseconds) taken before the camera returns to the default beta position.
  81323. */
  81324. get: function () {
  81325. return this._elevationReturnWaitTime;
  81326. },
  81327. /**
  81328. * Sets the delay (in milliseconds) taken before the camera returns to the default beta position.
  81329. */
  81330. set: function (time) {
  81331. this._elevationReturnWaitTime = time;
  81332. },
  81333. enumerable: true,
  81334. configurable: true
  81335. });
  81336. Object.defineProperty(FramingBehavior.prototype, "zoomStopsAnimation", {
  81337. /**
  81338. * Gets the flag that indicates if user zooming should stop animation.
  81339. */
  81340. get: function () {
  81341. return this._zoomStopsAnimation;
  81342. },
  81343. /**
  81344. * Sets the flag that indicates if user zooming should stop animation.
  81345. */
  81346. set: function (flag) {
  81347. this._zoomStopsAnimation = flag;
  81348. },
  81349. enumerable: true,
  81350. configurable: true
  81351. });
  81352. Object.defineProperty(FramingBehavior.prototype, "framingTime", {
  81353. /**
  81354. * Gets the transition time when framing the mesh, in milliseconds
  81355. */
  81356. get: function () {
  81357. return this._framingTime;
  81358. },
  81359. /**
  81360. * Sets the transition time when framing the mesh, in milliseconds
  81361. */
  81362. set: function (time) {
  81363. this._framingTime = time;
  81364. },
  81365. enumerable: true,
  81366. configurable: true
  81367. });
  81368. FramingBehavior.prototype.init = function () {
  81369. // Do notihng
  81370. };
  81371. FramingBehavior.prototype.attach = function (camera) {
  81372. var _this = this;
  81373. this._attachedCamera = camera;
  81374. var scene = this._attachedCamera.getScene();
  81375. FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode);
  81376. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  81377. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  81378. _this._isPointerDown = true;
  81379. return;
  81380. }
  81381. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  81382. _this._isPointerDown = false;
  81383. }
  81384. });
  81385. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  81386. if (mesh) {
  81387. _this.zoomOnMesh(mesh);
  81388. }
  81389. });
  81390. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  81391. // Stop the animation if there is user interaction and the animation should stop for this interaction
  81392. _this._applyUserInteraction();
  81393. // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it
  81394. // back to the default position after a given timeout
  81395. _this._maintainCameraAboveGround();
  81396. });
  81397. };
  81398. FramingBehavior.prototype.detach = function () {
  81399. if (!this._attachedCamera) {
  81400. return;
  81401. }
  81402. var scene = this._attachedCamera.getScene();
  81403. if (this._onPrePointerObservableObserver) {
  81404. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  81405. }
  81406. if (this._onAfterCheckInputsObserver) {
  81407. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  81408. }
  81409. if (this._onMeshTargetChangedObserver) {
  81410. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  81411. }
  81412. this._attachedCamera = null;
  81413. };
  81414. /**
  81415. * Targets the given mesh and updates zoom level accordingly.
  81416. * @param mesh The mesh to target.
  81417. * @param radius Optional. If a cached radius position already exists, overrides default.
  81418. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  81419. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  81420. * @param onAnimationEnd Callback triggered at the end of the framing animation
  81421. */
  81422. FramingBehavior.prototype.zoomOnMesh = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  81423. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  81424. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  81425. mesh.computeWorldMatrix(true);
  81426. var boundingBox = mesh.getBoundingInfo().boundingBox;
  81427. this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ, onAnimationEnd);
  81428. };
  81429. /**
  81430. * Targets the given mesh with its children and updates zoom level accordingly.
  81431. * @param mesh The mesh to target.
  81432. * @param radius Optional. If a cached radius position already exists, overrides default.
  81433. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  81434. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  81435. * @param onAnimationEnd Callback triggered at the end of the framing animation
  81436. */
  81437. FramingBehavior.prototype.zoomOnMeshHierarchy = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  81438. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  81439. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  81440. mesh.computeWorldMatrix(true);
  81441. var boundingBox = mesh.getHierarchyBoundingVectors(true);
  81442. this.zoomOnBoundingInfo(boundingBox.min, boundingBox.max, focusOnOriginXZ, onAnimationEnd);
  81443. };
  81444. /**
  81445. * Targets the given meshes with their children and updates zoom level accordingly.
  81446. * @param meshes The mesh to target.
  81447. * @param radius Optional. If a cached radius position already exists, overrides default.
  81448. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  81449. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  81450. * @param onAnimationEnd Callback triggered at the end of the framing animation
  81451. */
  81452. FramingBehavior.prototype.zoomOnMeshesHierarchy = function (meshes, focusOnOriginXZ, onAnimationEnd) {
  81453. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  81454. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  81455. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  81456. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  81457. for (var i = 0; i < meshes.length; i++) {
  81458. var boundingInfo = meshes[i].getHierarchyBoundingVectors(true);
  81459. BABYLON.Tools.CheckExtends(boundingInfo.min, min, max);
  81460. BABYLON.Tools.CheckExtends(boundingInfo.max, min, max);
  81461. }
  81462. this.zoomOnBoundingInfo(min, max, focusOnOriginXZ, onAnimationEnd);
  81463. };
  81464. /**
  81465. * Targets the given mesh and updates zoom level accordingly.
  81466. * @param mesh The mesh to target.
  81467. * @param radius Optional. If a cached radius position already exists, overrides default.
  81468. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  81469. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  81470. * @param onAnimationEnd Callback triggered at the end of the framing animation
  81471. */
  81472. FramingBehavior.prototype.zoomOnBoundingInfo = function (minimumWorld, maximumWorld, focusOnOriginXZ, onAnimationEnd) {
  81473. var _this = this;
  81474. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  81475. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  81476. var zoomTarget;
  81477. if (!this._attachedCamera) {
  81478. return;
  81479. }
  81480. // Find target by interpolating from bottom of bounding box in world-space to top via framingPositionY
  81481. var bottom = minimumWorld.y;
  81482. var top = maximumWorld.y;
  81483. var zoomTargetY = bottom + (top - bottom) * this._positionScale;
  81484. var radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5);
  81485. if (focusOnOriginXZ) {
  81486. zoomTarget = new BABYLON.Vector3(0, zoomTargetY, 0);
  81487. }
  81488. else {
  81489. var centerWorld = minimumWorld.add(radiusWorld);
  81490. zoomTarget = new BABYLON.Vector3(centerWorld.x, zoomTargetY, centerWorld.z);
  81491. }
  81492. if (!this._vectorTransition) {
  81493. this._vectorTransition = BABYLON.Animation.CreateAnimation("target", BABYLON.Animation.ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction);
  81494. }
  81495. this._betaIsAnimating = true;
  81496. var animatable = BABYLON.Animation.TransitionTo("target", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime);
  81497. if (animatable) {
  81498. this._animatables.push(animatable);
  81499. }
  81500. // sets the radius and lower radius bounds
  81501. // Small delta ensures camera is not always at lower zoom limit.
  81502. var radius = 0;
  81503. if (this._mode === FramingBehavior.FitFrustumSidesMode) {
  81504. var position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  81505. this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ;
  81506. radius = position;
  81507. }
  81508. else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  81509. radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  81510. if (this._attachedCamera.lowerRadiusLimit === null) {
  81511. this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ;
  81512. }
  81513. }
  81514. // Set sensibilities
  81515. var extend = maximumWorld.subtract(minimumWorld).length();
  81516. this._attachedCamera.panningSensibility = 5000 / extend;
  81517. this._attachedCamera.wheelPrecision = 100 / radius;
  81518. // transition to new radius
  81519. if (!this._radiusTransition) {
  81520. this._radiusTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  81521. }
  81522. animatable = BABYLON.Animation.TransitionTo("radius", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime, function () {
  81523. if (onAnimationEnd) {
  81524. onAnimationEnd();
  81525. }
  81526. if (_this._attachedCamera) {
  81527. _this._attachedCamera.storeState();
  81528. }
  81529. });
  81530. if (animatable) {
  81531. this._animatables.push(animatable);
  81532. }
  81533. };
  81534. /**
  81535. * Calculates the lowest radius for the camera based on the bounding box of the mesh.
  81536. * @param mesh The mesh on which to base the calculation. mesh boundingInfo used to estimate necessary
  81537. * frustum width.
  81538. * @return The minimum distance from the primary mesh's center point at which the camera must be kept in order
  81539. * to fully enclose the mesh in the viewing frustum.
  81540. */
  81541. FramingBehavior.prototype._calculateLowerRadiusFromModelBoundingSphere = function (minimumWorld, maximumWorld) {
  81542. var size = maximumWorld.subtract(minimumWorld);
  81543. var boxVectorGlobalDiagonal = size.length();
  81544. var frustumSlope = this._getFrustumSlope();
  81545. // Formula for setting distance
  81546. // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene)
  81547. var radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5;
  81548. // Horizon distance
  81549. var radius = radiusWithoutFraming * this._radiusScale;
  81550. var distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.x * frustumSlope.x));
  81551. var distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.y * frustumSlope.y));
  81552. var distance = Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum);
  81553. var camera = this._attachedCamera;
  81554. if (!camera) {
  81555. return 0;
  81556. }
  81557. if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  81558. // Don't exceed the requested limit
  81559. distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance;
  81560. }
  81561. // Don't exceed the upper radius limit
  81562. if (camera.upperRadiusLimit) {
  81563. distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance;
  81564. }
  81565. return distance;
  81566. };
  81567. /**
  81568. * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera
  81569. * is automatically returned to its default position (expected to be above ground plane).
  81570. */
  81571. FramingBehavior.prototype._maintainCameraAboveGround = function () {
  81572. var _this = this;
  81573. if (this._elevationReturnTime < 0) {
  81574. return;
  81575. }
  81576. var timeSinceInteraction = BABYLON.Tools.Now - this._lastInteractionTime;
  81577. var defaultBeta = Math.PI * 0.5 - this._defaultElevation;
  81578. var limitBeta = Math.PI * 0.5;
  81579. // Bring the camera back up if below the ground plane
  81580. if (this._attachedCamera && !this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) {
  81581. this._betaIsAnimating = true;
  81582. //Transition to new position
  81583. this.stopAllAnimations();
  81584. if (!this._betaTransition) {
  81585. this._betaTransition = BABYLON.Animation.CreateAnimation("beta", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  81586. }
  81587. var animatabe = BABYLON.Animation.TransitionTo("beta", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, function () {
  81588. _this._clearAnimationLocks();
  81589. _this.stopAllAnimations();
  81590. });
  81591. if (animatabe) {
  81592. this._animatables.push(animatabe);
  81593. }
  81594. }
  81595. };
  81596. /**
  81597. * Returns the frustum slope based on the canvas ratio and camera FOV
  81598. * @returns The frustum slope represented as a Vector2 with X and Y slopes
  81599. */
  81600. FramingBehavior.prototype._getFrustumSlope = function () {
  81601. // Calculate the viewport ratio
  81602. // Aspect Ratio is Height/Width.
  81603. var camera = this._attachedCamera;
  81604. if (!camera) {
  81605. return BABYLON.Vector2.Zero();
  81606. }
  81607. var engine = camera.getScene().getEngine();
  81608. var aspectRatio = engine.getAspectRatio(camera);
  81609. // Camera FOV is the vertical field of view (top-bottom) in radians.
  81610. // Slope of the frustum top/bottom planes in view space, relative to the forward vector.
  81611. var frustumSlopeY = Math.tan(camera.fov / 2);
  81612. // Slope of the frustum left/right planes in view space, relative to the forward vector.
  81613. // Provides the amount that one side (e.g. left) of the frustum gets wider for every unit
  81614. // along the forward vector.
  81615. var frustumSlopeX = frustumSlopeY * aspectRatio;
  81616. return new BABYLON.Vector2(frustumSlopeX, frustumSlopeY);
  81617. };
  81618. /**
  81619. * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties.
  81620. */
  81621. FramingBehavior.prototype._clearAnimationLocks = function () {
  81622. this._betaIsAnimating = false;
  81623. };
  81624. /**
  81625. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  81626. */
  81627. FramingBehavior.prototype._applyUserInteraction = function () {
  81628. if (this.isUserIsMoving) {
  81629. this._lastInteractionTime = BABYLON.Tools.Now;
  81630. this.stopAllAnimations();
  81631. this._clearAnimationLocks();
  81632. }
  81633. };
  81634. /**
  81635. * Stops and removes all animations that have been applied to the camera
  81636. */
  81637. FramingBehavior.prototype.stopAllAnimations = function () {
  81638. if (this._attachedCamera) {
  81639. this._attachedCamera.animations = [];
  81640. }
  81641. while (this._animatables.length) {
  81642. if (this._animatables[0]) {
  81643. this._animatables[0].onAnimationEnd = null;
  81644. this._animatables[0].stop();
  81645. }
  81646. this._animatables.shift();
  81647. }
  81648. };
  81649. Object.defineProperty(FramingBehavior.prototype, "isUserIsMoving", {
  81650. /**
  81651. * Gets a value indicating if the user is moving the camera
  81652. */
  81653. get: function () {
  81654. if (!this._attachedCamera) {
  81655. return false;
  81656. }
  81657. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  81658. this._attachedCamera.inertialBetaOffset !== 0 ||
  81659. this._attachedCamera.inertialRadiusOffset !== 0 ||
  81660. this._attachedCamera.inertialPanningX !== 0 ||
  81661. this._attachedCamera.inertialPanningY !== 0 ||
  81662. this._isPointerDown;
  81663. },
  81664. enumerable: true,
  81665. configurable: true
  81666. });
  81667. /**
  81668. * The easing function used by animations
  81669. */
  81670. FramingBehavior.EasingFunction = new BABYLON.ExponentialEase();
  81671. /**
  81672. * The easing mode used by animations
  81673. */
  81674. FramingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT;
  81675. // Statics
  81676. /**
  81677. * The camera can move all the way towards the mesh.
  81678. */
  81679. FramingBehavior.IgnoreBoundsSizeMode = 0;
  81680. /**
  81681. * The camera is not allowed to zoom closer to the mesh than the point at which the adjusted bounding sphere touches the frustum sides
  81682. */
  81683. FramingBehavior.FitFrustumSidesMode = 1;
  81684. return FramingBehavior;
  81685. }());
  81686. BABYLON.FramingBehavior = FramingBehavior;
  81687. })(BABYLON || (BABYLON = {}));
  81688. //# sourceMappingURL=babylon.framingBehavior.js.map
  81689. var BABYLON;
  81690. (function (BABYLON) {
  81691. /**
  81692. * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius
  81693. */
  81694. var BouncingBehavior = /** @class */ (function () {
  81695. function BouncingBehavior() {
  81696. /**
  81697. * The duration of the animation, in milliseconds
  81698. */
  81699. this.transitionDuration = 450;
  81700. /**
  81701. * Length of the distance animated by the transition when lower radius is reached
  81702. */
  81703. this.lowerRadiusTransitionRange = 2;
  81704. /**
  81705. * Length of the distance animated by the transition when upper radius is reached
  81706. */
  81707. this.upperRadiusTransitionRange = -2;
  81708. this._autoTransitionRange = false;
  81709. // Animations
  81710. this._radiusIsAnimating = false;
  81711. this._radiusBounceTransition = null;
  81712. this._animatables = new Array();
  81713. }
  81714. Object.defineProperty(BouncingBehavior.prototype, "name", {
  81715. get: function () {
  81716. return "Bouncing";
  81717. },
  81718. enumerable: true,
  81719. configurable: true
  81720. });
  81721. Object.defineProperty(BouncingBehavior.prototype, "autoTransitionRange", {
  81722. /**
  81723. * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  81724. */
  81725. get: function () {
  81726. return this._autoTransitionRange;
  81727. },
  81728. /**
  81729. * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  81730. * Transition ranges will be set to 5% of the bounding box diagonal in world space
  81731. */
  81732. set: function (value) {
  81733. var _this = this;
  81734. if (this._autoTransitionRange === value) {
  81735. return;
  81736. }
  81737. this._autoTransitionRange = value;
  81738. var camera = this._attachedCamera;
  81739. if (!camera) {
  81740. return;
  81741. }
  81742. if (value) {
  81743. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  81744. if (!mesh) {
  81745. return;
  81746. }
  81747. mesh.computeWorldMatrix(true);
  81748. var diagonal = mesh.getBoundingInfo().diagonalLength;
  81749. _this.lowerRadiusTransitionRange = diagonal * 0.05;
  81750. _this.upperRadiusTransitionRange = diagonal * 0.05;
  81751. });
  81752. }
  81753. else if (this._onMeshTargetChangedObserver) {
  81754. camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  81755. }
  81756. },
  81757. enumerable: true,
  81758. configurable: true
  81759. });
  81760. BouncingBehavior.prototype.init = function () {
  81761. // Do notihng
  81762. };
  81763. BouncingBehavior.prototype.attach = function (camera) {
  81764. var _this = this;
  81765. this._attachedCamera = camera;
  81766. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  81767. if (!_this._attachedCamera) {
  81768. return;
  81769. }
  81770. // Add the bounce animation to the lower radius limit
  81771. if (_this._isRadiusAtLimit(_this._attachedCamera.lowerRadiusLimit)) {
  81772. _this._applyBoundRadiusAnimation(_this.lowerRadiusTransitionRange);
  81773. }
  81774. // Add the bounce animation to the upper radius limit
  81775. if (_this._isRadiusAtLimit(_this._attachedCamera.upperRadiusLimit)) {
  81776. _this._applyBoundRadiusAnimation(_this.upperRadiusTransitionRange);
  81777. }
  81778. });
  81779. };
  81780. BouncingBehavior.prototype.detach = function () {
  81781. if (!this._attachedCamera) {
  81782. return;
  81783. }
  81784. if (this._onAfterCheckInputsObserver) {
  81785. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  81786. }
  81787. if (this._onMeshTargetChangedObserver) {
  81788. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  81789. }
  81790. this._attachedCamera = null;
  81791. };
  81792. /**
  81793. * Checks if the camera radius is at the specified limit. Takes into account animation locks.
  81794. * @param radiusLimit The limit to check against.
  81795. * @return Bool to indicate if at limit.
  81796. */
  81797. BouncingBehavior.prototype._isRadiusAtLimit = function (radiusLimit) {
  81798. if (!this._attachedCamera) {
  81799. return false;
  81800. }
  81801. if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) {
  81802. return true;
  81803. }
  81804. return false;
  81805. };
  81806. /**
  81807. * Applies an animation to the radius of the camera, extending by the radiusDelta.
  81808. * @param radiusDelta The delta by which to animate to. Can be negative.
  81809. */
  81810. BouncingBehavior.prototype._applyBoundRadiusAnimation = function (radiusDelta) {
  81811. var _this = this;
  81812. if (!this._attachedCamera) {
  81813. return;
  81814. }
  81815. if (!this._radiusBounceTransition) {
  81816. BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode);
  81817. this._radiusBounceTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction);
  81818. }
  81819. // Prevent zoom until bounce has completed
  81820. this._cachedWheelPrecision = this._attachedCamera.wheelPrecision;
  81821. this._attachedCamera.wheelPrecision = Infinity;
  81822. this._attachedCamera.inertialRadiusOffset = 0;
  81823. // Animate to the radius limit
  81824. this.stopAllAnimations();
  81825. this._radiusIsAnimating = true;
  81826. var animatable = BABYLON.Animation.TransitionTo("radius", this._attachedCamera.radius + radiusDelta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusBounceTransition, this.transitionDuration, function () { return _this._clearAnimationLocks(); });
  81827. if (animatable) {
  81828. this._animatables.push(animatable);
  81829. }
  81830. };
  81831. /**
  81832. * Removes all animation locks. Allows new animations to be added to any of the camera properties.
  81833. */
  81834. BouncingBehavior.prototype._clearAnimationLocks = function () {
  81835. this._radiusIsAnimating = false;
  81836. if (this._attachedCamera) {
  81837. this._attachedCamera.wheelPrecision = this._cachedWheelPrecision;
  81838. }
  81839. };
  81840. /**
  81841. * Stops and removes all animations that have been applied to the camera
  81842. */
  81843. BouncingBehavior.prototype.stopAllAnimations = function () {
  81844. if (this._attachedCamera) {
  81845. this._attachedCamera.animations = [];
  81846. }
  81847. while (this._animatables.length) {
  81848. this._animatables[0].onAnimationEnd = null;
  81849. this._animatables[0].stop();
  81850. this._animatables.shift();
  81851. }
  81852. };
  81853. /**
  81854. * The easing function used by animations
  81855. */
  81856. BouncingBehavior.EasingFunction = new BABYLON.BackEase(0.3);
  81857. /**
  81858. * The easing mode used by animations
  81859. */
  81860. BouncingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEOUT;
  81861. return BouncingBehavior;
  81862. }());
  81863. BABYLON.BouncingBehavior = BouncingBehavior;
  81864. })(BABYLON || (BABYLON = {}));
  81865. //# sourceMappingURL=babylon.bouncingBehavior.js.map
  81866. var BABYLON;
  81867. (function (BABYLON) {
  81868. var AutoRotationBehavior = /** @class */ (function () {
  81869. function AutoRotationBehavior() {
  81870. this._zoomStopsAnimation = false;
  81871. this._idleRotationSpeed = 0.05;
  81872. this._idleRotationWaitTime = 2000;
  81873. this._idleRotationSpinupTime = 2000;
  81874. this._isPointerDown = false;
  81875. this._lastFrameTime = null;
  81876. this._lastInteractionTime = -Infinity;
  81877. this._cameraRotationSpeed = 0;
  81878. this._lastFrameRadius = 0;
  81879. }
  81880. Object.defineProperty(AutoRotationBehavior.prototype, "name", {
  81881. get: function () {
  81882. return "AutoRotation";
  81883. },
  81884. enumerable: true,
  81885. configurable: true
  81886. });
  81887. Object.defineProperty(AutoRotationBehavior.prototype, "zoomStopsAnimation", {
  81888. /**
  81889. * Gets the flag that indicates if user zooming should stop animation.
  81890. */
  81891. get: function () {
  81892. return this._zoomStopsAnimation;
  81893. },
  81894. /**
  81895. * Sets the flag that indicates if user zooming should stop animation.
  81896. */
  81897. set: function (flag) {
  81898. this._zoomStopsAnimation = flag;
  81899. },
  81900. enumerable: true,
  81901. configurable: true
  81902. });
  81903. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpeed", {
  81904. /**
  81905. * Gets the default speed at which the camera rotates around the model.
  81906. */
  81907. get: function () {
  81908. return this._idleRotationSpeed;
  81909. },
  81910. /**
  81911. * Sets the default speed at which the camera rotates around the model.
  81912. */
  81913. set: function (speed) {
  81914. this._idleRotationSpeed = speed;
  81915. },
  81916. enumerable: true,
  81917. configurable: true
  81918. });
  81919. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationWaitTime", {
  81920. /**
  81921. * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating.
  81922. */
  81923. get: function () {
  81924. return this._idleRotationWaitTime;
  81925. },
  81926. /**
  81927. * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating.
  81928. */
  81929. set: function (time) {
  81930. this._idleRotationWaitTime = time;
  81931. },
  81932. enumerable: true,
  81933. configurable: true
  81934. });
  81935. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpinupTime", {
  81936. /**
  81937. * Gets the time (milliseconds) to take to spin up to the full idle rotation speed.
  81938. */
  81939. get: function () {
  81940. return this._idleRotationSpinupTime;
  81941. },
  81942. /**
  81943. * Sets the time (milliseconds) to take to spin up to the full idle rotation speed.
  81944. */
  81945. set: function (time) {
  81946. this._idleRotationSpinupTime = time;
  81947. },
  81948. enumerable: true,
  81949. configurable: true
  81950. });
  81951. Object.defineProperty(AutoRotationBehavior.prototype, "rotationInProgress", {
  81952. /**
  81953. * Gets a value indicating if the camera is currently rotating because of this behavior
  81954. */
  81955. get: function () {
  81956. return Math.abs(this._cameraRotationSpeed) > 0;
  81957. },
  81958. enumerable: true,
  81959. configurable: true
  81960. });
  81961. AutoRotationBehavior.prototype.init = function () {
  81962. // Do notihng
  81963. };
  81964. AutoRotationBehavior.prototype.attach = function (camera) {
  81965. var _this = this;
  81966. this._attachedCamera = camera;
  81967. var scene = this._attachedCamera.getScene();
  81968. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  81969. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  81970. _this._isPointerDown = true;
  81971. return;
  81972. }
  81973. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  81974. _this._isPointerDown = false;
  81975. }
  81976. });
  81977. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  81978. var now = BABYLON.Tools.Now;
  81979. var dt = 0;
  81980. if (_this._lastFrameTime != null) {
  81981. dt = now - _this._lastFrameTime;
  81982. }
  81983. _this._lastFrameTime = now;
  81984. // Stop the animation if there is user interaction and the animation should stop for this interaction
  81985. _this._applyUserInteraction();
  81986. var timeToRotation = now - _this._lastInteractionTime - _this._idleRotationWaitTime;
  81987. var scale = Math.max(Math.min(timeToRotation / (_this._idleRotationSpinupTime), 1), 0);
  81988. _this._cameraRotationSpeed = _this._idleRotationSpeed * scale;
  81989. // Step camera rotation by rotation speed
  81990. if (_this._attachedCamera) {
  81991. _this._attachedCamera.alpha -= _this._cameraRotationSpeed * (dt / 1000);
  81992. }
  81993. });
  81994. };
  81995. AutoRotationBehavior.prototype.detach = function () {
  81996. if (!this._attachedCamera) {
  81997. return;
  81998. }
  81999. var scene = this._attachedCamera.getScene();
  82000. if (this._onPrePointerObservableObserver) {
  82001. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  82002. }
  82003. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  82004. this._attachedCamera = null;
  82005. };
  82006. /**
  82007. * Returns true if user is scrolling.
  82008. * @return true if user is scrolling.
  82009. */
  82010. AutoRotationBehavior.prototype._userIsZooming = function () {
  82011. if (!this._attachedCamera) {
  82012. return false;
  82013. }
  82014. return this._attachedCamera.inertialRadiusOffset !== 0;
  82015. };
  82016. AutoRotationBehavior.prototype._shouldAnimationStopForInteraction = function () {
  82017. if (!this._attachedCamera) {
  82018. return false;
  82019. }
  82020. var zoomHasHitLimit = false;
  82021. if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) {
  82022. zoomHasHitLimit = true;
  82023. }
  82024. // Update the record of previous radius - works as an approx. indicator of hitting radius limits
  82025. this._lastFrameRadius = this._attachedCamera.radius;
  82026. return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming();
  82027. };
  82028. /**
  82029. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  82030. */
  82031. AutoRotationBehavior.prototype._applyUserInteraction = function () {
  82032. if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) {
  82033. this._lastInteractionTime = BABYLON.Tools.Now;
  82034. }
  82035. };
  82036. // Tools
  82037. AutoRotationBehavior.prototype._userIsMoving = function () {
  82038. if (!this._attachedCamera) {
  82039. return false;
  82040. }
  82041. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  82042. this._attachedCamera.inertialBetaOffset !== 0 ||
  82043. this._attachedCamera.inertialRadiusOffset !== 0 ||
  82044. this._attachedCamera.inertialPanningX !== 0 ||
  82045. this._attachedCamera.inertialPanningY !== 0 ||
  82046. this._isPointerDown;
  82047. };
  82048. return AutoRotationBehavior;
  82049. }());
  82050. BABYLON.AutoRotationBehavior = AutoRotationBehavior;
  82051. })(BABYLON || (BABYLON = {}));
  82052. //# sourceMappingURL=babylon.autoRotationBehavior.js.map
  82053. var BABYLON;
  82054. (function (BABYLON) {
  82055. var NullEngineOptions = /** @class */ (function () {
  82056. function NullEngineOptions() {
  82057. this.renderWidth = 512;
  82058. this.renderHeight = 256;
  82059. this.textureSize = 512;
  82060. this.deterministicLockstep = false;
  82061. this.lockstepMaxSteps = 4;
  82062. }
  82063. return NullEngineOptions;
  82064. }());
  82065. BABYLON.NullEngineOptions = NullEngineOptions;
  82066. /**
  82067. * The null engine class provides support for headless version of babylon.js.
  82068. * This can be used in server side scenario or for testing purposes
  82069. */
  82070. var NullEngine = /** @class */ (function (_super) {
  82071. __extends(NullEngine, _super);
  82072. function NullEngine(options) {
  82073. if (options === void 0) { options = new NullEngineOptions(); }
  82074. var _this = _super.call(this, null) || this;
  82075. if (options.deterministicLockstep === undefined) {
  82076. options.deterministicLockstep = false;
  82077. }
  82078. if (options.lockstepMaxSteps === undefined) {
  82079. options.lockstepMaxSteps = 4;
  82080. }
  82081. _this._options = options;
  82082. // Init caps
  82083. // We consider we are on a webgl1 capable device
  82084. _this._caps = new BABYLON.EngineCapabilities();
  82085. _this._caps.maxTexturesImageUnits = 16;
  82086. _this._caps.maxVertexTextureImageUnits = 16;
  82087. _this._caps.maxTextureSize = 512;
  82088. _this._caps.maxCubemapTextureSize = 512;
  82089. _this._caps.maxRenderTextureSize = 512;
  82090. _this._caps.maxVertexAttribs = 16;
  82091. _this._caps.maxVaryingVectors = 16;
  82092. _this._caps.maxFragmentUniformVectors = 16;
  82093. _this._caps.maxVertexUniformVectors = 16;
  82094. // Extensions
  82095. _this._caps.standardDerivatives = false;
  82096. _this._caps.astc = null;
  82097. _this._caps.s3tc = null;
  82098. _this._caps.pvrtc = null;
  82099. _this._caps.etc1 = null;
  82100. _this._caps.etc2 = null;
  82101. _this._caps.textureAnisotropicFilterExtension = null;
  82102. _this._caps.maxAnisotropy = 0;
  82103. _this._caps.uintIndices = false;
  82104. _this._caps.fragmentDepthSupported = false;
  82105. _this._caps.highPrecisionShaderSupported = true;
  82106. _this._caps.colorBufferFloat = false;
  82107. _this._caps.textureFloat = false;
  82108. _this._caps.textureFloatLinearFiltering = false;
  82109. _this._caps.textureFloatRender = false;
  82110. _this._caps.textureHalfFloat = false;
  82111. _this._caps.textureHalfFloatLinearFiltering = false;
  82112. _this._caps.textureHalfFloatRender = false;
  82113. _this._caps.textureLOD = false;
  82114. _this._caps.drawBuffersExtension = false;
  82115. _this._caps.depthTextureExtension = false;
  82116. _this._caps.vertexArrayObject = false;
  82117. _this._caps.instancedArrays = false;
  82118. BABYLON.Tools.Log("Babylon.js null engine (v" + BABYLON.Engine.Version + ") launched");
  82119. // Wrappers
  82120. if (typeof URL === "undefined") {
  82121. URL = {
  82122. createObjectURL: function () { },
  82123. revokeObjectURL: function () { }
  82124. };
  82125. }
  82126. if (typeof Blob === "undefined") {
  82127. Blob = function () { };
  82128. }
  82129. return _this;
  82130. }
  82131. NullEngine.prototype.isDeterministicLockStep = function () {
  82132. return this._options.deterministicLockstep;
  82133. };
  82134. NullEngine.prototype.getLockstepMaxSteps = function () {
  82135. return this._options.lockstepMaxSteps;
  82136. };
  82137. NullEngine.prototype.createVertexBuffer = function (vertices) {
  82138. return {
  82139. capacity: 0,
  82140. references: 1,
  82141. is32Bits: false
  82142. };
  82143. };
  82144. NullEngine.prototype.createIndexBuffer = function (indices) {
  82145. return {
  82146. capacity: 0,
  82147. references: 1,
  82148. is32Bits: false
  82149. };
  82150. };
  82151. NullEngine.prototype.clear = function (color, backBuffer, depth, stencil) {
  82152. if (stencil === void 0) { stencil = false; }
  82153. };
  82154. NullEngine.prototype.getRenderWidth = function (useScreen) {
  82155. if (useScreen === void 0) { useScreen = false; }
  82156. if (!useScreen && this._currentRenderTarget) {
  82157. return this._currentRenderTarget.width;
  82158. }
  82159. return this._options.renderWidth;
  82160. };
  82161. NullEngine.prototype.getRenderHeight = function (useScreen) {
  82162. if (useScreen === void 0) { useScreen = false; }
  82163. if (!useScreen && this._currentRenderTarget) {
  82164. return this._currentRenderTarget.height;
  82165. }
  82166. return this._options.renderHeight;
  82167. };
  82168. NullEngine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  82169. this._cachedViewport = viewport;
  82170. };
  82171. NullEngine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  82172. return {
  82173. transformFeedback: null,
  82174. __SPECTOR_rebuildProgram: null
  82175. };
  82176. };
  82177. NullEngine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  82178. return [];
  82179. };
  82180. NullEngine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  82181. return [];
  82182. };
  82183. NullEngine.prototype.bindSamplers = function (effect) {
  82184. this._currentEffect = null;
  82185. };
  82186. NullEngine.prototype.enableEffect = function (effect) {
  82187. this._currentEffect = effect;
  82188. if (effect.onBind) {
  82189. effect.onBind(effect);
  82190. }
  82191. effect.onBindObservable.notifyObservers(effect);
  82192. };
  82193. NullEngine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  82194. if (zOffset === void 0) { zOffset = 0; }
  82195. if (reverseSide === void 0) { reverseSide = false; }
  82196. };
  82197. NullEngine.prototype.setIntArray = function (uniform, array) {
  82198. };
  82199. NullEngine.prototype.setIntArray2 = function (uniform, array) {
  82200. };
  82201. NullEngine.prototype.setIntArray3 = function (uniform, array) {
  82202. };
  82203. NullEngine.prototype.setIntArray4 = function (uniform, array) {
  82204. };
  82205. NullEngine.prototype.setFloatArray = function (uniform, array) {
  82206. };
  82207. NullEngine.prototype.setFloatArray2 = function (uniform, array) {
  82208. };
  82209. NullEngine.prototype.setFloatArray3 = function (uniform, array) {
  82210. };
  82211. NullEngine.prototype.setFloatArray4 = function (uniform, array) {
  82212. };
  82213. NullEngine.prototype.setArray = function (uniform, array) {
  82214. };
  82215. NullEngine.prototype.setArray2 = function (uniform, array) {
  82216. };
  82217. NullEngine.prototype.setArray3 = function (uniform, array) {
  82218. };
  82219. NullEngine.prototype.setArray4 = function (uniform, array) {
  82220. };
  82221. NullEngine.prototype.setMatrices = function (uniform, matrices) {
  82222. };
  82223. NullEngine.prototype.setMatrix = function (uniform, matrix) {
  82224. };
  82225. NullEngine.prototype.setMatrix3x3 = function (uniform, matrix) {
  82226. };
  82227. NullEngine.prototype.setMatrix2x2 = function (uniform, matrix) {
  82228. };
  82229. NullEngine.prototype.setFloat = function (uniform, value) {
  82230. };
  82231. NullEngine.prototype.setFloat2 = function (uniform, x, y) {
  82232. };
  82233. NullEngine.prototype.setFloat3 = function (uniform, x, y, z) {
  82234. };
  82235. NullEngine.prototype.setBool = function (uniform, bool) {
  82236. };
  82237. NullEngine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  82238. };
  82239. NullEngine.prototype.setColor3 = function (uniform, color3) {
  82240. };
  82241. NullEngine.prototype.setColor4 = function (uniform, color3, alpha) {
  82242. };
  82243. NullEngine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  82244. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  82245. if (this._alphaMode === mode) {
  82246. return;
  82247. }
  82248. this._alphaState.alphaBlend = (mode !== BABYLON.Engine.ALPHA_DISABLE);
  82249. if (!noDepthWriteChange) {
  82250. this.setDepthWrite(mode === BABYLON.Engine.ALPHA_DISABLE);
  82251. }
  82252. this._alphaMode = mode;
  82253. };
  82254. NullEngine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  82255. };
  82256. NullEngine.prototype.wipeCaches = function (bruteForce) {
  82257. if (this.preventCacheWipeBetweenFrames) {
  82258. return;
  82259. }
  82260. this.resetTextureCache();
  82261. this._currentEffect = null;
  82262. if (bruteForce) {
  82263. this._currentProgram = null;
  82264. this._stencilState.reset();
  82265. this._depthCullingState.reset();
  82266. this.setDepthFunctionToLessOrEqual();
  82267. this._alphaState.reset();
  82268. }
  82269. this._cachedVertexBuffers = null;
  82270. this._cachedIndexBuffer = null;
  82271. this._cachedEffectForVertexBuffers = null;
  82272. };
  82273. NullEngine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  82274. };
  82275. NullEngine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  82276. };
  82277. NullEngine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  82278. };
  82279. NullEngine.prototype._createTexture = function () {
  82280. return {};
  82281. };
  82282. NullEngine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  82283. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  82284. if (onLoad === void 0) { onLoad = null; }
  82285. if (onError === void 0) { onError = null; }
  82286. if (buffer === void 0) { buffer = null; }
  82287. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  82288. var url = String(urlArg);
  82289. texture.url = url;
  82290. texture.generateMipMaps = !noMipmap;
  82291. texture.samplingMode = samplingMode;
  82292. texture.invertY = invertY;
  82293. texture.baseWidth = this._options.textureSize;
  82294. texture.baseHeight = this._options.textureSize;
  82295. texture.width = this._options.textureSize;
  82296. texture.height = this._options.textureSize;
  82297. if (format) {
  82298. texture.format = format;
  82299. }
  82300. texture.isReady = true;
  82301. if (onLoad) {
  82302. onLoad();
  82303. }
  82304. return texture;
  82305. };
  82306. NullEngine.prototype.createRenderTargetTexture = function (size, options) {
  82307. var fullOptions = new BABYLON.RenderTargetCreationOptions();
  82308. if (options !== undefined && typeof options === "object") {
  82309. fullOptions.generateMipMaps = options.generateMipMaps;
  82310. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  82311. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  82312. fullOptions.type = options.type === undefined ? BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  82313. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  82314. }
  82315. else {
  82316. fullOptions.generateMipMaps = options;
  82317. fullOptions.generateDepthBuffer = true;
  82318. fullOptions.generateStencilBuffer = false;
  82319. fullOptions.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  82320. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  82321. }
  82322. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  82323. var width = size.width || size;
  82324. var height = size.height || size;
  82325. texture._depthStencilBuffer = {};
  82326. texture._framebuffer = {};
  82327. texture.baseWidth = width;
  82328. texture.baseHeight = height;
  82329. texture.width = width;
  82330. texture.height = height;
  82331. texture.isReady = true;
  82332. texture.samples = 1;
  82333. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  82334. texture.samplingMode = fullOptions.samplingMode;
  82335. texture.type = fullOptions.type;
  82336. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  82337. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  82338. return texture;
  82339. };
  82340. NullEngine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  82341. texture.samplingMode = samplingMode;
  82342. };
  82343. NullEngine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
  82344. if (this._currentRenderTarget) {
  82345. this.unBindFramebuffer(this._currentRenderTarget);
  82346. }
  82347. this._currentRenderTarget = texture;
  82348. this._currentFramebuffer = texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer;
  82349. if (this._cachedViewport && !forceFullscreenViewport) {
  82350. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  82351. }
  82352. };
  82353. NullEngine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  82354. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  82355. this._currentRenderTarget = null;
  82356. if (onBeforeUnbind) {
  82357. if (texture._MSAAFramebuffer) {
  82358. this._currentFramebuffer = texture._framebuffer;
  82359. }
  82360. onBeforeUnbind();
  82361. }
  82362. this._currentFramebuffer = null;
  82363. };
  82364. NullEngine.prototype.createDynamicVertexBuffer = function (vertices) {
  82365. var vbo = {
  82366. capacity: 1,
  82367. references: 1,
  82368. is32Bits: false
  82369. };
  82370. return vbo;
  82371. };
  82372. NullEngine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  82373. if (offset === void 0) { offset = 0; }
  82374. };
  82375. NullEngine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset, count) {
  82376. };
  82377. NullEngine.prototype._bindTextureDirectly = function (target, texture) {
  82378. if (this._boundTexturesCache[this._activeChannel] !== texture) {
  82379. this._boundTexturesCache[this._activeChannel] = texture;
  82380. }
  82381. };
  82382. NullEngine.prototype._bindTexture = function (channel, texture) {
  82383. if (channel < 0) {
  82384. return;
  82385. }
  82386. this._bindTextureDirectly(0, texture);
  82387. };
  82388. NullEngine.prototype._releaseBuffer = function (buffer) {
  82389. buffer.references--;
  82390. if (buffer.references === 0) {
  82391. return true;
  82392. }
  82393. return false;
  82394. };
  82395. return NullEngine;
  82396. }(BABYLON.Engine));
  82397. BABYLON.NullEngine = NullEngine;
  82398. })(BABYLON || (BABYLON = {}));
  82399. //# sourceMappingURL=babylon.nullEngine.js.map
  82400. var BABYLON;
  82401. (function (BABYLON) {
  82402. /**
  82403. * This class can be used to get instrumentation data from a Babylon engine
  82404. */
  82405. var EngineInstrumentation = /** @class */ (function () {
  82406. function EngineInstrumentation(engine) {
  82407. this.engine = engine;
  82408. this._captureGPUFrameTime = false;
  82409. this._gpuFrameTime = new BABYLON.PerfCounter();
  82410. this._captureShaderCompilationTime = false;
  82411. this._shaderCompilationTime = new BABYLON.PerfCounter();
  82412. // Observers
  82413. this._onBeginFrameObserver = null;
  82414. this._onEndFrameObserver = null;
  82415. this._onBeforeShaderCompilationObserver = null;
  82416. this._onAfterShaderCompilationObserver = null;
  82417. }
  82418. Object.defineProperty(EngineInstrumentation.prototype, "gpuFrameTimeCounter", {
  82419. // Properties
  82420. /**
  82421. * Gets the perf counter used for GPU frame time
  82422. */
  82423. get: function () {
  82424. return this._gpuFrameTime;
  82425. },
  82426. enumerable: true,
  82427. configurable: true
  82428. });
  82429. Object.defineProperty(EngineInstrumentation.prototype, "captureGPUFrameTime", {
  82430. /**
  82431. * Gets the GPU frame time capture status
  82432. */
  82433. get: function () {
  82434. return this._captureGPUFrameTime;
  82435. },
  82436. /**
  82437. * Enable or disable the GPU frame time capture
  82438. */
  82439. set: function (value) {
  82440. var _this = this;
  82441. if (value === this._captureGPUFrameTime) {
  82442. return;
  82443. }
  82444. this._captureGPUFrameTime = value;
  82445. if (value) {
  82446. this._onBeginFrameObserver = this.engine.onBeginFrameObservable.add(function () {
  82447. if (!_this._gpuFrameTimeToken) {
  82448. _this._gpuFrameTimeToken = _this.engine.startTimeQuery();
  82449. }
  82450. });
  82451. this._onEndFrameObserver = this.engine.onEndFrameObservable.add(function () {
  82452. if (!_this._gpuFrameTimeToken) {
  82453. return;
  82454. }
  82455. var time = _this.engine.endTimeQuery(_this._gpuFrameTimeToken);
  82456. if (time > -1) {
  82457. _this._gpuFrameTimeToken = null;
  82458. _this._gpuFrameTime.fetchNewFrame();
  82459. _this._gpuFrameTime.addCount(time, true);
  82460. }
  82461. });
  82462. }
  82463. else {
  82464. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  82465. this._onBeginFrameObserver = null;
  82466. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  82467. this._onEndFrameObserver = null;
  82468. }
  82469. },
  82470. enumerable: true,
  82471. configurable: true
  82472. });
  82473. Object.defineProperty(EngineInstrumentation.prototype, "shaderCompilationTimeCounter", {
  82474. /**
  82475. * Gets the perf counter used for shader compilation time
  82476. */
  82477. get: function () {
  82478. return this._shaderCompilationTime;
  82479. },
  82480. enumerable: true,
  82481. configurable: true
  82482. });
  82483. Object.defineProperty(EngineInstrumentation.prototype, "captureShaderCompilationTime", {
  82484. /**
  82485. * Gets the shader compilation time capture status
  82486. */
  82487. get: function () {
  82488. return this._captureShaderCompilationTime;
  82489. },
  82490. /**
  82491. * Enable or disable the shader compilation time capture
  82492. */
  82493. set: function (value) {
  82494. var _this = this;
  82495. if (value === this._captureShaderCompilationTime) {
  82496. return;
  82497. }
  82498. this._captureShaderCompilationTime = value;
  82499. if (value) {
  82500. this._onBeforeShaderCompilationObserver = this.engine.onBeforeShaderCompilationObservable.add(function () {
  82501. _this._shaderCompilationTime.fetchNewFrame();
  82502. _this._shaderCompilationTime.beginMonitoring();
  82503. });
  82504. this._onAfterShaderCompilationObserver = this.engine.onAfterShaderCompilationObservable.add(function () {
  82505. _this._shaderCompilationTime.endMonitoring();
  82506. });
  82507. }
  82508. else {
  82509. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  82510. this._onBeforeShaderCompilationObserver = null;
  82511. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  82512. this._onAfterShaderCompilationObserver = null;
  82513. }
  82514. },
  82515. enumerable: true,
  82516. configurable: true
  82517. });
  82518. EngineInstrumentation.prototype.dispose = function () {
  82519. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  82520. this._onBeginFrameObserver = null;
  82521. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  82522. this._onEndFrameObserver = null;
  82523. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  82524. this._onBeforeShaderCompilationObserver = null;
  82525. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  82526. this._onAfterShaderCompilationObserver = null;
  82527. this.engine = null;
  82528. };
  82529. return EngineInstrumentation;
  82530. }());
  82531. BABYLON.EngineInstrumentation = EngineInstrumentation;
  82532. })(BABYLON || (BABYLON = {}));
  82533. //# sourceMappingURL=babylon.engineInstrumentation.js.map
  82534. var BABYLON;
  82535. (function (BABYLON) {
  82536. /**
  82537. * This class can be used to get instrumentation data from a Babylon engine
  82538. */
  82539. var SceneInstrumentation = /** @class */ (function () {
  82540. function SceneInstrumentation(scene) {
  82541. var _this = this;
  82542. this.scene = scene;
  82543. this._captureActiveMeshesEvaluationTime = false;
  82544. this._activeMeshesEvaluationTime = new BABYLON.PerfCounter();
  82545. this._captureRenderTargetsRenderTime = false;
  82546. this._renderTargetsRenderTime = new BABYLON.PerfCounter();
  82547. this._captureFrameTime = false;
  82548. this._frameTime = new BABYLON.PerfCounter();
  82549. this._captureRenderTime = false;
  82550. this._renderTime = new BABYLON.PerfCounter();
  82551. this._captureInterFrameTime = false;
  82552. this._interFrameTime = new BABYLON.PerfCounter();
  82553. this._captureParticlesRenderTime = false;
  82554. this._particlesRenderTime = new BABYLON.PerfCounter();
  82555. this._captureSpritesRenderTime = false;
  82556. this._spritesRenderTime = new BABYLON.PerfCounter();
  82557. this._capturePhysicsTime = false;
  82558. this._physicsTime = new BABYLON.PerfCounter();
  82559. this._captureAnimationsTime = false;
  82560. this._animationsTime = new BABYLON.PerfCounter();
  82561. // Observers
  82562. this._onBeforeActiveMeshesEvaluationObserver = null;
  82563. this._onAfterActiveMeshesEvaluationObserver = null;
  82564. this._onBeforeRenderTargetsRenderObserver = null;
  82565. this._onAfterRenderTargetsRenderObserver = null;
  82566. this._onAfterRenderObserver = null;
  82567. this._onBeforeDrawPhaseObserver = null;
  82568. this._onAfterDrawPhaseObserver = null;
  82569. this._onBeforeAnimationsObserver = null;
  82570. this._onBeforeParticlesRenderingObserver = null;
  82571. this._onAfterParticlesRenderingObserver = null;
  82572. this._onBeforeSpritesRenderingObserver = null;
  82573. this._onAfterSpritesRenderingObserver = null;
  82574. this._onBeforePhysicsObserver = null;
  82575. this._onAfterPhysicsObserver = null;
  82576. this._onAfterAnimationsObserver = null;
  82577. // Before render
  82578. this._onBeforeAnimationsObserver = scene.onBeforeAnimationsObservable.add(function () {
  82579. if (_this._captureActiveMeshesEvaluationTime) {
  82580. _this._activeMeshesEvaluationTime.fetchNewFrame();
  82581. }
  82582. if (_this._captureRenderTargetsRenderTime) {
  82583. _this._renderTargetsRenderTime.fetchNewFrame();
  82584. }
  82585. if (_this._captureFrameTime) {
  82586. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  82587. _this._frameTime.beginMonitoring();
  82588. }
  82589. if (_this._captureInterFrameTime) {
  82590. _this._interFrameTime.endMonitoring();
  82591. }
  82592. if (_this._captureParticlesRenderTime) {
  82593. _this._particlesRenderTime.fetchNewFrame();
  82594. }
  82595. if (_this._captureSpritesRenderTime) {
  82596. _this._spritesRenderTime.fetchNewFrame();
  82597. }
  82598. if (_this._captureAnimationsTime) {
  82599. _this._animationsTime.beginMonitoring();
  82600. }
  82601. _this.scene.getEngine()._drawCalls.fetchNewFrame();
  82602. _this.scene.getEngine()._textureCollisions.fetchNewFrame();
  82603. });
  82604. // After render
  82605. this._onAfterRenderObserver = scene.onAfterRenderObservable.add(function () {
  82606. if (_this._captureFrameTime) {
  82607. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  82608. _this._frameTime.endMonitoring();
  82609. }
  82610. if (_this._captureRenderTime) {
  82611. _this._renderTime.endMonitoring(false);
  82612. }
  82613. if (_this._captureInterFrameTime) {
  82614. _this._interFrameTime.beginMonitoring();
  82615. }
  82616. });
  82617. }
  82618. Object.defineProperty(SceneInstrumentation.prototype, "activeMeshesEvaluationTimeCounter", {
  82619. // Properties
  82620. /**
  82621. * Gets the perf counter used for active meshes evaluation time
  82622. */
  82623. get: function () {
  82624. return this._activeMeshesEvaluationTime;
  82625. },
  82626. enumerable: true,
  82627. configurable: true
  82628. });
  82629. Object.defineProperty(SceneInstrumentation.prototype, "captureActiveMeshesEvaluationTime", {
  82630. /**
  82631. * Gets the active meshes evaluation time capture status
  82632. */
  82633. get: function () {
  82634. return this._captureActiveMeshesEvaluationTime;
  82635. },
  82636. /**
  82637. * Enable or disable the active meshes evaluation time capture
  82638. */
  82639. set: function (value) {
  82640. var _this = this;
  82641. if (value === this._captureActiveMeshesEvaluationTime) {
  82642. return;
  82643. }
  82644. this._captureActiveMeshesEvaluationTime = value;
  82645. if (value) {
  82646. this._onBeforeActiveMeshesEvaluationObserver = this.scene.onBeforeActiveMeshesEvaluationObservable.add(function () {
  82647. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  82648. _this._activeMeshesEvaluationTime.beginMonitoring();
  82649. });
  82650. this._onAfterActiveMeshesEvaluationObserver = this.scene.onAfterActiveMeshesEvaluationObservable.add(function () {
  82651. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  82652. _this._activeMeshesEvaluationTime.endMonitoring();
  82653. });
  82654. }
  82655. else {
  82656. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  82657. this._onBeforeActiveMeshesEvaluationObserver = null;
  82658. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  82659. this._onAfterActiveMeshesEvaluationObserver = null;
  82660. }
  82661. },
  82662. enumerable: true,
  82663. configurable: true
  82664. });
  82665. Object.defineProperty(SceneInstrumentation.prototype, "renderTargetsRenderTimeCounter", {
  82666. /**
  82667. * Gets the perf counter used for render targets render time
  82668. */
  82669. get: function () {
  82670. return this._renderTargetsRenderTime;
  82671. },
  82672. enumerable: true,
  82673. configurable: true
  82674. });
  82675. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTargetsRenderTime", {
  82676. /**
  82677. * Gets the render targets render time capture status
  82678. */
  82679. get: function () {
  82680. return this._captureRenderTargetsRenderTime;
  82681. },
  82682. /**
  82683. * Enable or disable the render targets render time capture
  82684. */
  82685. set: function (value) {
  82686. var _this = this;
  82687. if (value === this._captureRenderTargetsRenderTime) {
  82688. return;
  82689. }
  82690. this._captureRenderTargetsRenderTime = value;
  82691. if (value) {
  82692. this._onBeforeRenderTargetsRenderObserver = this.scene.OnBeforeRenderTargetsRenderObservable.add(function () {
  82693. BABYLON.Tools.StartPerformanceCounter("Render targets rendering");
  82694. _this._renderTargetsRenderTime.beginMonitoring();
  82695. });
  82696. this._onAfterRenderTargetsRenderObserver = this.scene.OnAfterRenderTargetsRenderObservable.add(function () {
  82697. BABYLON.Tools.EndPerformanceCounter("Render targets rendering");
  82698. _this._renderTargetsRenderTime.endMonitoring(false);
  82699. });
  82700. }
  82701. else {
  82702. this.scene.OnBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  82703. this._onBeforeRenderTargetsRenderObserver = null;
  82704. this.scene.OnAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  82705. this._onAfterRenderTargetsRenderObserver = null;
  82706. }
  82707. },
  82708. enumerable: true,
  82709. configurable: true
  82710. });
  82711. Object.defineProperty(SceneInstrumentation.prototype, "particlesRenderTimeCounter", {
  82712. /**
  82713. * Gets the perf counter used for particles render time
  82714. */
  82715. get: function () {
  82716. return this._particlesRenderTime;
  82717. },
  82718. enumerable: true,
  82719. configurable: true
  82720. });
  82721. Object.defineProperty(SceneInstrumentation.prototype, "captureParticlesRenderTime", {
  82722. /**
  82723. * Gets the particles render time capture status
  82724. */
  82725. get: function () {
  82726. return this._captureParticlesRenderTime;
  82727. },
  82728. /**
  82729. * Enable or disable the particles render time capture
  82730. */
  82731. set: function (value) {
  82732. var _this = this;
  82733. if (value === this._captureParticlesRenderTime) {
  82734. return;
  82735. }
  82736. this._captureParticlesRenderTime = value;
  82737. if (value) {
  82738. this._onBeforeParticlesRenderingObserver = this.scene.onBeforeParticlesRenderingObservable.add(function () {
  82739. BABYLON.Tools.StartPerformanceCounter("Particles");
  82740. _this._particlesRenderTime.beginMonitoring();
  82741. });
  82742. this._onAfterParticlesRenderingObserver = this.scene.onAfterParticlesRenderingObservable.add(function () {
  82743. BABYLON.Tools.EndPerformanceCounter("Particles");
  82744. _this._particlesRenderTime.endMonitoring(false);
  82745. });
  82746. }
  82747. else {
  82748. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  82749. this._onBeforeParticlesRenderingObserver = null;
  82750. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  82751. this._onAfterParticlesRenderingObserver = null;
  82752. }
  82753. },
  82754. enumerable: true,
  82755. configurable: true
  82756. });
  82757. Object.defineProperty(SceneInstrumentation.prototype, "spritesRenderTimeCounter", {
  82758. /**
  82759. * Gets the perf counter used for sprites render time
  82760. */
  82761. get: function () {
  82762. return this._spritesRenderTime;
  82763. },
  82764. enumerable: true,
  82765. configurable: true
  82766. });
  82767. Object.defineProperty(SceneInstrumentation.prototype, "captureSpritesRenderTime", {
  82768. /**
  82769. * Gets the sprites render time capture status
  82770. */
  82771. get: function () {
  82772. return this._captureSpritesRenderTime;
  82773. },
  82774. /**
  82775. * Enable or disable the sprites render time capture
  82776. */
  82777. set: function (value) {
  82778. var _this = this;
  82779. if (value === this._captureSpritesRenderTime) {
  82780. return;
  82781. }
  82782. this._captureSpritesRenderTime = value;
  82783. if (value) {
  82784. this._onBeforeSpritesRenderingObserver = this.scene.onBeforeSpritesRenderingObservable.add(function () {
  82785. BABYLON.Tools.StartPerformanceCounter("Sprites");
  82786. _this._spritesRenderTime.beginMonitoring();
  82787. });
  82788. this._onAfterSpritesRenderingObserver = this.scene.onAfterSpritesRenderingObservable.add(function () {
  82789. BABYLON.Tools.EndPerformanceCounter("Sprites");
  82790. _this._spritesRenderTime.endMonitoring(false);
  82791. });
  82792. }
  82793. else {
  82794. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  82795. this._onBeforeSpritesRenderingObserver = null;
  82796. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  82797. this._onAfterSpritesRenderingObserver = null;
  82798. }
  82799. },
  82800. enumerable: true,
  82801. configurable: true
  82802. });
  82803. Object.defineProperty(SceneInstrumentation.prototype, "physicsTimeCounter", {
  82804. /**
  82805. * Gets the perf counter used for physics time
  82806. */
  82807. get: function () {
  82808. return this._physicsTime;
  82809. },
  82810. enumerable: true,
  82811. configurable: true
  82812. });
  82813. Object.defineProperty(SceneInstrumentation.prototype, "capturePhysicsTime", {
  82814. /**
  82815. * Gets the physics time capture status
  82816. */
  82817. get: function () {
  82818. return this._capturePhysicsTime;
  82819. },
  82820. /**
  82821. * Enable or disable the physics time capture
  82822. */
  82823. set: function (value) {
  82824. var _this = this;
  82825. if (value === this._capturePhysicsTime) {
  82826. return;
  82827. }
  82828. this._capturePhysicsTime = value;
  82829. if (value) {
  82830. this._onBeforePhysicsObserver = this.scene.onBeforePhysicsObservable.add(function () {
  82831. BABYLON.Tools.StartPerformanceCounter("Physics");
  82832. _this._physicsTime.beginMonitoring();
  82833. });
  82834. this._onAfterPhysicsObserver = this.scene.onAfterPhysicsObservable.add(function () {
  82835. BABYLON.Tools.EndPerformanceCounter("Physics");
  82836. _this._physicsTime.endMonitoring();
  82837. });
  82838. }
  82839. else {
  82840. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  82841. this._onBeforePhysicsObserver = null;
  82842. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  82843. this._onAfterPhysicsObserver = null;
  82844. }
  82845. },
  82846. enumerable: true,
  82847. configurable: true
  82848. });
  82849. Object.defineProperty(SceneInstrumentation.prototype, "animationsTimeCounter", {
  82850. /**
  82851. * Gets the perf counter used for animations time
  82852. */
  82853. get: function () {
  82854. return this._animationsTime;
  82855. },
  82856. enumerable: true,
  82857. configurable: true
  82858. });
  82859. Object.defineProperty(SceneInstrumentation.prototype, "captureAnimationsTime", {
  82860. /**
  82861. * Gets the animations time capture status
  82862. */
  82863. get: function () {
  82864. return this._captureAnimationsTime;
  82865. },
  82866. /**
  82867. * Enable or disable the animations time capture
  82868. */
  82869. set: function (value) {
  82870. var _this = this;
  82871. if (value === this._captureAnimationsTime) {
  82872. return;
  82873. }
  82874. this._captureAnimationsTime = value;
  82875. if (value) {
  82876. this._onAfterAnimationsObserver = this.scene.onAfterAnimationsObservable.add(function () {
  82877. _this._animationsTime.endMonitoring();
  82878. });
  82879. }
  82880. else {
  82881. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  82882. this._onAfterAnimationsObserver = null;
  82883. }
  82884. },
  82885. enumerable: true,
  82886. configurable: true
  82887. });
  82888. Object.defineProperty(SceneInstrumentation.prototype, "frameTimeCounter", {
  82889. /**
  82890. * Gets the perf counter used for frame time capture
  82891. */
  82892. get: function () {
  82893. return this._frameTime;
  82894. },
  82895. enumerable: true,
  82896. configurable: true
  82897. });
  82898. Object.defineProperty(SceneInstrumentation.prototype, "captureFrameTime", {
  82899. /**
  82900. * Gets the frame time capture status
  82901. */
  82902. get: function () {
  82903. return this._captureFrameTime;
  82904. },
  82905. /**
  82906. * Enable or disable the frame time capture
  82907. */
  82908. set: function (value) {
  82909. this._captureFrameTime = value;
  82910. },
  82911. enumerable: true,
  82912. configurable: true
  82913. });
  82914. Object.defineProperty(SceneInstrumentation.prototype, "interFrameTimeCounter", {
  82915. /**
  82916. * Gets the perf counter used for inter-frames time capture
  82917. */
  82918. get: function () {
  82919. return this._interFrameTime;
  82920. },
  82921. enumerable: true,
  82922. configurable: true
  82923. });
  82924. Object.defineProperty(SceneInstrumentation.prototype, "captureInterFrameTime", {
  82925. /**
  82926. * Gets the inter-frames time capture status
  82927. */
  82928. get: function () {
  82929. return this._captureInterFrameTime;
  82930. },
  82931. /**
  82932. * Enable or disable the inter-frames time capture
  82933. */
  82934. set: function (value) {
  82935. this._captureInterFrameTime = value;
  82936. },
  82937. enumerable: true,
  82938. configurable: true
  82939. });
  82940. Object.defineProperty(SceneInstrumentation.prototype, "renderTimeCounter", {
  82941. /**
  82942. * Gets the perf counter used for render time capture
  82943. */
  82944. get: function () {
  82945. return this._renderTime;
  82946. },
  82947. enumerable: true,
  82948. configurable: true
  82949. });
  82950. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTime", {
  82951. /**
  82952. * Gets the render time capture status
  82953. */
  82954. get: function () {
  82955. return this._captureRenderTime;
  82956. },
  82957. /**
  82958. * Enable or disable the render time capture
  82959. */
  82960. set: function (value) {
  82961. var _this = this;
  82962. if (value === this._captureRenderTime) {
  82963. return;
  82964. }
  82965. this._captureRenderTime = value;
  82966. if (value) {
  82967. this._onBeforeDrawPhaseObserver = this.scene.onBeforeDrawPhaseObservable.add(function () {
  82968. _this._renderTime.beginMonitoring();
  82969. BABYLON.Tools.StartPerformanceCounter("Main render");
  82970. });
  82971. this._onAfterDrawPhaseObserver = this.scene.onAfterDrawPhaseObservable.add(function () {
  82972. _this._renderTime.endMonitoring(false);
  82973. BABYLON.Tools.EndPerformanceCounter("Main render");
  82974. });
  82975. }
  82976. else {
  82977. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  82978. this._onBeforeDrawPhaseObserver = null;
  82979. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  82980. this._onAfterDrawPhaseObserver = null;
  82981. }
  82982. },
  82983. enumerable: true,
  82984. configurable: true
  82985. });
  82986. Object.defineProperty(SceneInstrumentation.prototype, "drawCallsCounter", {
  82987. /**
  82988. * Gets the perf counter used for draw calls
  82989. */
  82990. get: function () {
  82991. return this.scene.getEngine()._drawCalls;
  82992. },
  82993. enumerable: true,
  82994. configurable: true
  82995. });
  82996. Object.defineProperty(SceneInstrumentation.prototype, "textureCollisionsCounter", {
  82997. /**
  82998. * Gets the perf counter used for texture collisions
  82999. */
  83000. get: function () {
  83001. return this.scene.getEngine()._textureCollisions;
  83002. },
  83003. enumerable: true,
  83004. configurable: true
  83005. });
  83006. SceneInstrumentation.prototype.dispose = function () {
  83007. this.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  83008. this._onAfterRenderObserver = null;
  83009. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  83010. this._onBeforeActiveMeshesEvaluationObserver = null;
  83011. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  83012. this._onAfterActiveMeshesEvaluationObserver = null;
  83013. this.scene.OnBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  83014. this._onBeforeRenderTargetsRenderObserver = null;
  83015. this.scene.OnAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  83016. this._onAfterRenderTargetsRenderObserver = null;
  83017. this.scene.onBeforeAnimationsObservable.remove(this._onBeforeAnimationsObserver);
  83018. this._onBeforeAnimationsObserver = null;
  83019. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  83020. this._onBeforeParticlesRenderingObserver = null;
  83021. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  83022. this._onAfterParticlesRenderingObserver = null;
  83023. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  83024. this._onBeforeSpritesRenderingObserver = null;
  83025. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  83026. this._onAfterSpritesRenderingObserver = null;
  83027. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  83028. this._onBeforeDrawPhaseObserver = null;
  83029. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  83030. this._onAfterDrawPhaseObserver = null;
  83031. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  83032. this._onBeforePhysicsObserver = null;
  83033. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  83034. this._onAfterPhysicsObserver = null;
  83035. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  83036. this._onAfterAnimationsObserver = null;
  83037. this.scene = null;
  83038. };
  83039. return SceneInstrumentation;
  83040. }());
  83041. BABYLON.SceneInstrumentation = SceneInstrumentation;
  83042. })(BABYLON || (BABYLON = {}));
  83043. //# sourceMappingURL=babylon.sceneInstrumentation.js.map
  83044. var BABYLON;
  83045. (function (BABYLON) {
  83046. var _TimeToken = /** @class */ (function () {
  83047. function _TimeToken() {
  83048. this._timeElapsedQueryEnded = false;
  83049. }
  83050. return _TimeToken;
  83051. }());
  83052. BABYLON._TimeToken = _TimeToken;
  83053. })(BABYLON || (BABYLON = {}));
  83054. //# sourceMappingURL=babylon.timeToken.js.map
  83055. var BABYLON;
  83056. (function (BABYLON) {
  83057. /**
  83058. * Background material defines definition.
  83059. */
  83060. var BackgroundMaterialDefines = /** @class */ (function (_super) {
  83061. __extends(BackgroundMaterialDefines, _super);
  83062. /**
  83063. * Constructor of the defines.
  83064. */
  83065. function BackgroundMaterialDefines() {
  83066. var _this = _super.call(this) || this;
  83067. /**
  83068. * True if the diffuse texture is in use.
  83069. */
  83070. _this.DIFFUSE = false;
  83071. /**
  83072. * The direct UV channel to use.
  83073. */
  83074. _this.DIFFUSEDIRECTUV = 0;
  83075. /**
  83076. * True if the diffuse texture is in gamma space.
  83077. */
  83078. _this.GAMMADIFFUSE = false;
  83079. /**
  83080. * True if the diffuse texture has opacity in the alpha channel.
  83081. */
  83082. _this.DIFFUSEHASALPHA = false;
  83083. /**
  83084. * True if you want the material to fade to transparent at grazing angle.
  83085. */
  83086. _this.OPACITYFRESNEL = false;
  83087. /**
  83088. * True if an extra blur needs to be added in the reflection.
  83089. */
  83090. _this.REFLECTIONBLUR = false;
  83091. /**
  83092. * True if you want the material to fade to reflection at grazing angle.
  83093. */
  83094. _this.REFLECTIONFRESNEL = false;
  83095. /**
  83096. * True if you want the material to falloff as far as you move away from the scene center.
  83097. */
  83098. _this.REFLECTIONFALLOFF = false;
  83099. /**
  83100. * False if the current Webgl implementation does not support the texture lod extension.
  83101. */
  83102. _this.TEXTURELODSUPPORT = false;
  83103. /**
  83104. * True to ensure the data are premultiplied.
  83105. */
  83106. _this.PREMULTIPLYALPHA = false;
  83107. /**
  83108. * True if the texture contains cooked RGB values and not gray scaled multipliers.
  83109. */
  83110. _this.USERGBCOLOR = false;
  83111. /**
  83112. * True to add noise in order to reduce the banding effect.
  83113. */
  83114. _this.NOISE = false;
  83115. // Image Processing Configuration.
  83116. _this.IMAGEPROCESSING = false;
  83117. _this.VIGNETTE = false;
  83118. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  83119. _this.VIGNETTEBLENDMODEOPAQUE = false;
  83120. _this.TONEMAPPING = false;
  83121. _this.CONTRAST = false;
  83122. _this.COLORCURVES = false;
  83123. _this.COLORGRADING = false;
  83124. _this.COLORGRADING3D = false;
  83125. _this.SAMPLER3DGREENDEPTH = false;
  83126. _this.SAMPLER3DBGRMAP = false;
  83127. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  83128. _this.EXPOSURE = false;
  83129. // Reflection.
  83130. _this.REFLECTION = false;
  83131. _this.REFLECTIONMAP_3D = false;
  83132. _this.REFLECTIONMAP_SPHERICAL = false;
  83133. _this.REFLECTIONMAP_PLANAR = false;
  83134. _this.REFLECTIONMAP_CUBIC = false;
  83135. _this.REFLECTIONMAP_PROJECTION = false;
  83136. _this.REFLECTIONMAP_SKYBOX = false;
  83137. _this.REFLECTIONMAP_EXPLICIT = false;
  83138. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  83139. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  83140. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  83141. _this.INVERTCUBICMAP = false;
  83142. _this.REFLECTIONMAP_OPPOSITEZ = false;
  83143. _this.LODINREFLECTIONALPHA = false;
  83144. _this.GAMMAREFLECTION = false;
  83145. // Default BJS.
  83146. _this.MAINUV1 = false;
  83147. _this.MAINUV2 = false;
  83148. _this.UV1 = false;
  83149. _this.UV2 = false;
  83150. _this.CLIPPLANE = false;
  83151. _this.POINTSIZE = false;
  83152. _this.FOG = false;
  83153. _this.NORMAL = false;
  83154. _this.NUM_BONE_INFLUENCERS = 0;
  83155. _this.BonesPerMesh = 0;
  83156. _this.INSTANCES = false;
  83157. _this.SHADOWFLOAT = false;
  83158. _this.rebuild();
  83159. return _this;
  83160. }
  83161. return BackgroundMaterialDefines;
  83162. }(BABYLON.MaterialDefines));
  83163. /**
  83164. * Background material used to create an efficient environement around your scene.
  83165. */
  83166. var BackgroundMaterial = /** @class */ (function (_super) {
  83167. __extends(BackgroundMaterial, _super);
  83168. /**
  83169. * constructor
  83170. * @param name The name of the material
  83171. * @param scene The scene to add the material to
  83172. */
  83173. function BackgroundMaterial(name, scene) {
  83174. var _this = _super.call(this, name, scene) || this;
  83175. _this.primaryColor = BABYLON.Color3.White();
  83176. _this.primaryLevel = 1;
  83177. _this.secondaryColor = BABYLON.Color3.Gray();
  83178. _this.secondaryLevel = 1;
  83179. _this.tertiaryColor = BABYLON.Color3.Black();
  83180. _this.tertiaryLevel = 1;
  83181. _this.reflectionTexture = null;
  83182. _this.reflectionBlur = 0;
  83183. _this.diffuseTexture = null;
  83184. /**
  83185. * Specify the list of lights casting shadow on the material.
  83186. * All scene shadow lights will be included if null.
  83187. */
  83188. _this._shadowLights = null;
  83189. _this.shadowLights = null;
  83190. _this.shadowBlurScale = 1;
  83191. _this.shadowLevel = 0;
  83192. _this.sceneCenter = BABYLON.Vector3.Zero();
  83193. _this.opacityFresnel = true;
  83194. _this.reflectionFresnel = false;
  83195. _this.reflectionFalloffDistance = 0.0;
  83196. _this.reflectionAmount = 1.0;
  83197. _this.reflectionReflectance0 = 0.05;
  83198. _this.reflectionReflectance90 = 0.5;
  83199. _this.useRGBColor = true;
  83200. _this.enableNoise = false;
  83201. /**
  83202. * Number of Simultaneous lights allowed on the material.
  83203. */
  83204. _this._maxSimultaneousLights = 4;
  83205. _this.maxSimultaneousLights = 4;
  83206. /**
  83207. * Keep track of the image processing observer to allow dispose and replace.
  83208. */
  83209. _this._imageProcessingObserver = null;
  83210. // Temp values kept as cache in the material.
  83211. _this._renderTargets = new BABYLON.SmartArray(16);
  83212. _this._reflectionControls = BABYLON.Vector4.Zero();
  83213. // Setup the default processing configuration to the scene.
  83214. _this._attachImageProcessingConfiguration(null);
  83215. _this.getRenderTargetTextures = function () {
  83216. _this._renderTargets.reset();
  83217. if (_this._diffuseTexture && _this._diffuseTexture.isRenderTarget) {
  83218. _this._renderTargets.push(_this._diffuseTexture);
  83219. }
  83220. if (_this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  83221. _this._renderTargets.push(_this._reflectionTexture);
  83222. }
  83223. return _this._renderTargets;
  83224. };
  83225. return _this;
  83226. }
  83227. Object.defineProperty(BackgroundMaterial.prototype, "reflectionStandardFresnelWeight", {
  83228. /**
  83229. * Sets the reflection reflectance fresnel values according to the default standard
  83230. * empirically know to work well :-)
  83231. */
  83232. set: function (value) {
  83233. var reflectionWeight = value;
  83234. if (reflectionWeight < 0.5) {
  83235. reflectionWeight = reflectionWeight * 2.0;
  83236. this.reflectionReflectance0 = BackgroundMaterial.standardReflectance0 * reflectionWeight;
  83237. this.reflectionReflectance90 = BackgroundMaterial.standardReflectance90 * reflectionWeight;
  83238. }
  83239. else {
  83240. reflectionWeight = reflectionWeight * 2.0 - 1.0;
  83241. this.reflectionReflectance0 = BackgroundMaterial.standardReflectance0 + (1.0 - BackgroundMaterial.standardReflectance0) * reflectionWeight;
  83242. this.reflectionReflectance90 = BackgroundMaterial.standardReflectance90 + (1.0 - BackgroundMaterial.standardReflectance90) * reflectionWeight;
  83243. }
  83244. },
  83245. enumerable: true,
  83246. configurable: true
  83247. });
  83248. /**
  83249. * Attaches a new image processing configuration to the PBR Material.
  83250. * @param configuration (if null the scene configuration will be use)
  83251. */
  83252. BackgroundMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  83253. var _this = this;
  83254. if (configuration === this._imageProcessingConfiguration) {
  83255. return;
  83256. }
  83257. // Detaches observer.
  83258. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  83259. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  83260. }
  83261. // Pick the scene configuration if needed.
  83262. if (!configuration) {
  83263. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  83264. }
  83265. else {
  83266. this._imageProcessingConfiguration = configuration;
  83267. }
  83268. // Attaches observer.
  83269. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  83270. _this._markAllSubMeshesAsImageProcessingDirty();
  83271. });
  83272. };
  83273. Object.defineProperty(BackgroundMaterial.prototype, "imageProcessingConfiguration", {
  83274. /**
  83275. * Gets the image processing configuration used either in this material.
  83276. */
  83277. get: function () {
  83278. return this._imageProcessingConfiguration;
  83279. },
  83280. /**
  83281. * Sets the Default image processing configuration used either in the this material.
  83282. *
  83283. * If sets to null, the scene one is in use.
  83284. */
  83285. set: function (value) {
  83286. this._attachImageProcessingConfiguration(value);
  83287. // Ensure the effect will be rebuilt.
  83288. this._markAllSubMeshesAsTexturesDirty();
  83289. },
  83290. enumerable: true,
  83291. configurable: true
  83292. });
  83293. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurvesEnabled", {
  83294. /**
  83295. * Gets wether the color curves effect is enabled.
  83296. */
  83297. get: function () {
  83298. return this.imageProcessingConfiguration.colorCurvesEnabled;
  83299. },
  83300. /**
  83301. * Sets wether the color curves effect is enabled.
  83302. */
  83303. set: function (value) {
  83304. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  83305. },
  83306. enumerable: true,
  83307. configurable: true
  83308. });
  83309. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingEnabled", {
  83310. /**
  83311. * Gets wether the color grading effect is enabled.
  83312. */
  83313. get: function () {
  83314. return this.imageProcessingConfiguration.colorGradingEnabled;
  83315. },
  83316. /**
  83317. * Gets wether the color grading effect is enabled.
  83318. */
  83319. set: function (value) {
  83320. this.imageProcessingConfiguration.colorGradingEnabled = value;
  83321. },
  83322. enumerable: true,
  83323. configurable: true
  83324. });
  83325. Object.defineProperty(BackgroundMaterial.prototype, "cameraToneMappingEnabled", {
  83326. /**
  83327. * Gets wether tonemapping is enabled or not.
  83328. */
  83329. get: function () {
  83330. return this._imageProcessingConfiguration.toneMappingEnabled;
  83331. },
  83332. /**
  83333. * Sets wether tonemapping is enabled or not
  83334. */
  83335. set: function (value) {
  83336. this._imageProcessingConfiguration.toneMappingEnabled = value;
  83337. },
  83338. enumerable: true,
  83339. configurable: true
  83340. });
  83341. ;
  83342. ;
  83343. Object.defineProperty(BackgroundMaterial.prototype, "cameraExposure", {
  83344. /**
  83345. * The camera exposure used on this material.
  83346. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  83347. * This corresponds to a photographic exposure.
  83348. */
  83349. get: function () {
  83350. return this._imageProcessingConfiguration.exposure;
  83351. },
  83352. /**
  83353. * The camera exposure used on this material.
  83354. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  83355. * This corresponds to a photographic exposure.
  83356. */
  83357. set: function (value) {
  83358. this._imageProcessingConfiguration.exposure = value;
  83359. },
  83360. enumerable: true,
  83361. configurable: true
  83362. });
  83363. ;
  83364. ;
  83365. Object.defineProperty(BackgroundMaterial.prototype, "cameraContrast", {
  83366. /**
  83367. * Gets The camera contrast used on this material.
  83368. */
  83369. get: function () {
  83370. return this._imageProcessingConfiguration.contrast;
  83371. },
  83372. /**
  83373. * Sets The camera contrast used on this material.
  83374. */
  83375. set: function (value) {
  83376. this._imageProcessingConfiguration.contrast = value;
  83377. },
  83378. enumerable: true,
  83379. configurable: true
  83380. });
  83381. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingTexture", {
  83382. /**
  83383. * Gets the Color Grading 2D Lookup Texture.
  83384. */
  83385. get: function () {
  83386. return this._imageProcessingConfiguration.colorGradingTexture;
  83387. },
  83388. /**
  83389. * Sets the Color Grading 2D Lookup Texture.
  83390. */
  83391. set: function (value) {
  83392. this.imageProcessingConfiguration.colorGradingTexture = value;
  83393. },
  83394. enumerable: true,
  83395. configurable: true
  83396. });
  83397. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurves", {
  83398. /**
  83399. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  83400. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  83401. * 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;
  83402. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  83403. */
  83404. get: function () {
  83405. return this.imageProcessingConfiguration.colorCurves;
  83406. },
  83407. /**
  83408. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  83409. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  83410. * 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;
  83411. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  83412. */
  83413. set: function (value) {
  83414. this.imageProcessingConfiguration.colorCurves = value;
  83415. },
  83416. enumerable: true,
  83417. configurable: true
  83418. });
  83419. /**
  83420. * The entire material has been created in order to prevent overdraw.
  83421. * @returns false
  83422. */
  83423. BackgroundMaterial.prototype.needAlphaTesting = function () {
  83424. return true;
  83425. };
  83426. /**
  83427. * The entire material has been created in order to prevent overdraw.
  83428. * @returns true if blending is enable
  83429. */
  83430. BackgroundMaterial.prototype.needAlphaBlending = function () {
  83431. return ((this.alpha < 0) || (this._diffuseTexture != null && this._diffuseTexture.hasAlpha));
  83432. };
  83433. /**
  83434. * Checks wether the material is ready to be rendered for a given mesh.
  83435. * @param mesh The mesh to render
  83436. * @param subMesh The submesh to check against
  83437. * @param useInstances Specify wether or not the material is used with instances
  83438. */
  83439. BackgroundMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  83440. var _this = this;
  83441. if (useInstances === void 0) { useInstances = false; }
  83442. if (subMesh.effect && this.isFrozen) {
  83443. if (this._wasPreviouslyReady) {
  83444. return true;
  83445. }
  83446. }
  83447. if (!subMesh._materialDefines) {
  83448. subMesh._materialDefines = new BackgroundMaterialDefines();
  83449. }
  83450. var scene = this.getScene();
  83451. var defines = subMesh._materialDefines;
  83452. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  83453. if (defines._renderId === scene.getRenderId()) {
  83454. return true;
  83455. }
  83456. }
  83457. var engine = scene.getEngine();
  83458. // Lights
  83459. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, false, this._maxSimultaneousLights);
  83460. defines._needNormals = true;
  83461. // Textures
  83462. if (defines._areTexturesDirty) {
  83463. defines._needUVs = false;
  83464. if (scene.texturesEnabled) {
  83465. if (scene.getEngine().getCaps().textureLOD) {
  83466. defines.TEXTURELODSUPPORT = true;
  83467. }
  83468. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  83469. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  83470. return false;
  83471. }
  83472. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  83473. defines.DIFFUSEHASALPHA = this._diffuseTexture.hasAlpha;
  83474. defines.GAMMADIFFUSE = this._diffuseTexture.gammaSpace;
  83475. defines.OPACITYFRESNEL = this._opacityFresnel;
  83476. }
  83477. else {
  83478. defines.DIFFUSE = false;
  83479. defines.DIFFUSEHASALPHA = false;
  83480. defines.GAMMADIFFUSE = false;
  83481. defines.OPACITYFRESNEL = false;
  83482. }
  83483. var reflectionTexture = this._reflectionTexture;
  83484. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  83485. if (!reflectionTexture.isReadyOrNotBlocking()) {
  83486. return false;
  83487. }
  83488. defines.REFLECTION = true;
  83489. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  83490. defines.REFLECTIONBLUR = this._reflectionBlur > 0;
  83491. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  83492. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  83493. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  83494. defines.INVERTCUBICMAP = true;
  83495. }
  83496. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  83497. switch (reflectionTexture.coordinatesMode) {
  83498. case BABYLON.Texture.CUBIC_MODE:
  83499. case BABYLON.Texture.INVCUBIC_MODE:
  83500. defines.REFLECTIONMAP_CUBIC = true;
  83501. break;
  83502. case BABYLON.Texture.EXPLICIT_MODE:
  83503. defines.REFLECTIONMAP_EXPLICIT = true;
  83504. break;
  83505. case BABYLON.Texture.PLANAR_MODE:
  83506. defines.REFLECTIONMAP_PLANAR = true;
  83507. break;
  83508. case BABYLON.Texture.PROJECTION_MODE:
  83509. defines.REFLECTIONMAP_PROJECTION = true;
  83510. break;
  83511. case BABYLON.Texture.SKYBOX_MODE:
  83512. defines.REFLECTIONMAP_SKYBOX = true;
  83513. break;
  83514. case BABYLON.Texture.SPHERICAL_MODE:
  83515. defines.REFLECTIONMAP_SPHERICAL = true;
  83516. break;
  83517. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  83518. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  83519. break;
  83520. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  83521. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  83522. break;
  83523. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  83524. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  83525. break;
  83526. }
  83527. if (this.reflectionFresnel) {
  83528. defines.REFLECTIONFRESNEL = true;
  83529. defines.REFLECTIONFALLOFF = this.reflectionFalloffDistance > 0;
  83530. this._reflectionControls.x = this.reflectionAmount;
  83531. this._reflectionControls.y = this.reflectionReflectance0;
  83532. this._reflectionControls.z = this.reflectionReflectance90;
  83533. this._reflectionControls.w = 1 / this.reflectionFalloffDistance;
  83534. }
  83535. else {
  83536. defines.REFLECTIONFRESNEL = false;
  83537. defines.REFLECTIONFALLOFF = false;
  83538. }
  83539. }
  83540. else {
  83541. defines.REFLECTION = false;
  83542. defines.REFLECTIONFALLOFF = false;
  83543. defines.REFLECTIONBLUR = false;
  83544. defines.REFLECTIONMAP_3D = false;
  83545. defines.REFLECTIONMAP_SPHERICAL = false;
  83546. defines.REFLECTIONMAP_PLANAR = false;
  83547. defines.REFLECTIONMAP_CUBIC = false;
  83548. defines.REFLECTIONMAP_PROJECTION = false;
  83549. defines.REFLECTIONMAP_SKYBOX = false;
  83550. defines.REFLECTIONMAP_EXPLICIT = false;
  83551. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  83552. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  83553. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  83554. defines.INVERTCUBICMAP = false;
  83555. defines.REFLECTIONMAP_OPPOSITEZ = false;
  83556. defines.LODINREFLECTIONALPHA = false;
  83557. defines.GAMMAREFLECTION = false;
  83558. }
  83559. }
  83560. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  83561. defines.USERGBCOLOR = this._useRGBColor;
  83562. defines.NOISE = this._enableNoise;
  83563. }
  83564. if (defines._areImageProcessingDirty) {
  83565. if (!this._imageProcessingConfiguration.isReady()) {
  83566. return false;
  83567. }
  83568. this._imageProcessingConfiguration.prepareDefines(defines);
  83569. }
  83570. // Misc.
  83571. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  83572. // Values that need to be evaluated on every frame
  83573. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  83574. // Attribs
  83575. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, false, true, false)) {
  83576. if (mesh) {
  83577. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  83578. mesh.createNormals(true);
  83579. BABYLON.Tools.Warn("BackgroundMaterial: Normals have been created for the mesh: " + mesh.name);
  83580. }
  83581. }
  83582. }
  83583. // Get correct effect
  83584. if (defines.isDirty) {
  83585. defines.markAsProcessed();
  83586. scene.resetCachedMaterial();
  83587. // Fallbacks
  83588. var fallbacks = new BABYLON.EffectFallbacks();
  83589. if (defines.FOG) {
  83590. fallbacks.addFallback(0, "FOG");
  83591. }
  83592. if (defines.POINTSIZE) {
  83593. fallbacks.addFallback(1, "POINTSIZE");
  83594. }
  83595. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  83596. if (defines.NUM_BONE_INFLUENCERS > 0) {
  83597. fallbacks.addCPUSkinningFallback(0, mesh);
  83598. }
  83599. //Attributes
  83600. var attribs = [BABYLON.VertexBuffer.PositionKind];
  83601. if (defines.NORMAL) {
  83602. attribs.push(BABYLON.VertexBuffer.NormalKind);
  83603. }
  83604. if (defines.UV1) {
  83605. attribs.push(BABYLON.VertexBuffer.UVKind);
  83606. }
  83607. if (defines.UV2) {
  83608. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  83609. }
  83610. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  83611. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  83612. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType",
  83613. "vFogInfos", "vFogColor", "pointSize",
  83614. "vClipPlane", "mBones",
  83615. "vPrimaryColor", "vSecondaryColor", "vTertiaryColor",
  83616. "vReflectionInfos", "reflectionMatrix", "vReflectionMicrosurfaceInfos",
  83617. "shadowLevel", "alpha",
  83618. "vBackgroundCenter", "vReflectionControl",
  83619. "vDiffuseInfos", "diffuseMatrix",
  83620. ];
  83621. var samplers = ["diffuseSampler", "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh"];
  83622. var uniformBuffers = ["Material", "Scene"];
  83623. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  83624. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  83625. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  83626. uniformsNames: uniforms,
  83627. uniformBuffersNames: uniformBuffers,
  83628. samplers: samplers,
  83629. defines: defines,
  83630. maxSimultaneousLights: this._maxSimultaneousLights
  83631. });
  83632. var onCompiled = function (effect) {
  83633. if (_this.onCompiled) {
  83634. _this.onCompiled(effect);
  83635. }
  83636. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  83637. };
  83638. var join = defines.toString();
  83639. subMesh.setEffect(scene.getEngine().createEffect("background", {
  83640. attributes: attribs,
  83641. uniformsNames: uniforms,
  83642. uniformBuffersNames: uniformBuffers,
  83643. samplers: samplers,
  83644. defines: join,
  83645. fallbacks: fallbacks,
  83646. onCompiled: onCompiled,
  83647. onError: this.onError,
  83648. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights }
  83649. }, engine), defines);
  83650. this.buildUniformLayout();
  83651. }
  83652. if (!subMesh.effect || !subMesh.effect.isReady()) {
  83653. return false;
  83654. }
  83655. defines._renderId = scene.getRenderId();
  83656. this._wasPreviouslyReady = true;
  83657. return true;
  83658. };
  83659. /**
  83660. * Build the uniform buffer used in the material.
  83661. */
  83662. BackgroundMaterial.prototype.buildUniformLayout = function () {
  83663. // Order is important !
  83664. this._uniformBuffer.addUniform("vPrimaryColor", 4);
  83665. this._uniformBuffer.addUniform("vSecondaryColor", 4);
  83666. this._uniformBuffer.addUniform("vTertiaryColor", 4);
  83667. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  83668. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  83669. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  83670. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  83671. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  83672. this._uniformBuffer.addUniform("pointSize", 1);
  83673. this._uniformBuffer.addUniform("shadowLevel", 1);
  83674. this._uniformBuffer.addUniform("alpha", 1);
  83675. this._uniformBuffer.addUniform("vBackgroundCenter", 3);
  83676. this._uniformBuffer.addUniform("vReflectionControl", 4);
  83677. this._uniformBuffer.create();
  83678. };
  83679. /**
  83680. * Unbind the material.
  83681. */
  83682. BackgroundMaterial.prototype.unbind = function () {
  83683. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  83684. this._uniformBuffer.setTexture("diffuseSampler", null);
  83685. }
  83686. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  83687. this._uniformBuffer.setTexture("reflectionSampler", null);
  83688. }
  83689. _super.prototype.unbind.call(this);
  83690. };
  83691. /**
  83692. * Bind only the world matrix to the material.
  83693. * @param world The world matrix to bind.
  83694. */
  83695. BackgroundMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  83696. this._activeEffect.setMatrix("world", world);
  83697. };
  83698. /**
  83699. * Bind the material for a dedicated submeh (every used meshes will be considered opaque).
  83700. * @param world The world matrix to bind.
  83701. * @param subMesh The submesh to bind for.
  83702. */
  83703. BackgroundMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  83704. var scene = this.getScene();
  83705. var defines = subMesh._materialDefines;
  83706. if (!defines) {
  83707. return;
  83708. }
  83709. var effect = subMesh.effect;
  83710. if (!effect) {
  83711. return;
  83712. }
  83713. this._activeEffect = effect;
  83714. // Matrices
  83715. this.bindOnlyWorldMatrix(world);
  83716. // Bones
  83717. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  83718. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  83719. if (mustRebind) {
  83720. this._uniformBuffer.bindToEffect(effect, "Material");
  83721. this.bindViewProjection(effect);
  83722. var reflectionTexture = this._reflectionTexture;
  83723. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  83724. // Texture uniforms
  83725. if (scene.texturesEnabled) {
  83726. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  83727. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  83728. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  83729. }
  83730. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  83731. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  83732. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, this._reflectionBlur);
  83733. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  83734. }
  83735. }
  83736. if (this.shadowLevel > 0) {
  83737. this._uniformBuffer.updateFloat("shadowLevel", this.shadowLevel);
  83738. }
  83739. this._uniformBuffer.updateFloat("alpha", this.alpha);
  83740. // Point size
  83741. if (this.pointsCloud) {
  83742. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  83743. }
  83744. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryColor, this._primaryLevel);
  83745. this._uniformBuffer.updateColor4("vSecondaryColor", this._secondaryColor, this._secondaryLevel);
  83746. this._uniformBuffer.updateColor4("vTertiaryColor", this._tertiaryColor, this._tertiaryLevel);
  83747. }
  83748. // Textures
  83749. if (scene.texturesEnabled) {
  83750. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  83751. this._uniformBuffer.setTexture("diffuseSampler", this._diffuseTexture);
  83752. }
  83753. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  83754. if (defines.REFLECTIONBLUR && defines.TEXTURELODSUPPORT) {
  83755. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  83756. }
  83757. else if (!defines.REFLECTIONBLUR) {
  83758. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  83759. }
  83760. else {
  83761. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  83762. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  83763. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  83764. }
  83765. if (defines.REFLECTIONFRESNEL) {
  83766. this._uniformBuffer.updateFloat3("vBackgroundCenter", this.sceneCenter.x, this.sceneCenter.y, this.sceneCenter.z);
  83767. this._uniformBuffer.updateFloat4("vReflectionControl", this._reflectionControls.x, this._reflectionControls.y, this._reflectionControls.z, this._reflectionControls.w);
  83768. }
  83769. }
  83770. }
  83771. // Clip plane
  83772. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  83773. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  83774. }
  83775. if (mustRebind || !this.isFrozen) {
  83776. if (scene.lightsEnabled) {
  83777. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, false);
  83778. }
  83779. // View
  83780. this.bindView(effect);
  83781. // Fog
  83782. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  83783. // image processing
  83784. this._imageProcessingConfiguration.bind(this._activeEffect);
  83785. }
  83786. this._uniformBuffer.update();
  83787. this._afterBind(mesh);
  83788. };
  83789. /**
  83790. * Dispose the material.
  83791. * @forceDisposeEffect Force disposal of the associated effect.
  83792. * @forceDisposeTextures Force disposal of the associated textures.
  83793. */
  83794. BackgroundMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  83795. if (forceDisposeEffect === void 0) { forceDisposeEffect = false; }
  83796. if (forceDisposeTextures === void 0) { forceDisposeTextures = false; }
  83797. if (forceDisposeTextures) {
  83798. if (this.diffuseTexture) {
  83799. this.diffuseTexture.dispose();
  83800. }
  83801. if (this.reflectionTexture) {
  83802. this.reflectionTexture.dispose();
  83803. }
  83804. }
  83805. this._renderTargets.dispose();
  83806. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  83807. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  83808. }
  83809. _super.prototype.dispose.call(this, forceDisposeEffect);
  83810. };
  83811. /**
  83812. * Clones the material.
  83813. * @name The cloned name.
  83814. * @returns The cloned material.
  83815. */
  83816. BackgroundMaterial.prototype.clone = function (name) {
  83817. var _this = this;
  83818. return BABYLON.SerializationHelper.Clone(function () { return new BackgroundMaterial(name, _this.getScene()); }, this);
  83819. };
  83820. /**
  83821. * Serializes the current material to its JSON representation.
  83822. * @returns The JSON representation.
  83823. */
  83824. BackgroundMaterial.prototype.serialize = function () {
  83825. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  83826. serializationObject.customType = "BABYLON.BackgroundMaterial";
  83827. return serializationObject;
  83828. };
  83829. /**
  83830. * Gets the class name of the material
  83831. * @returns "BackgroundMaterial"
  83832. */
  83833. BackgroundMaterial.prototype.getClassName = function () {
  83834. return "BackgroundMaterial";
  83835. };
  83836. /**
  83837. * Parse a JSON input to create back a background material.
  83838. * @param source
  83839. * @param scene
  83840. * @param rootUrl
  83841. * @returns the instantiated BackgroundMaterial.
  83842. */
  83843. BackgroundMaterial.Parse = function (source, scene, rootUrl) {
  83844. return BABYLON.SerializationHelper.Parse(function () { return new BackgroundMaterial(source.name, scene); }, source, scene, rootUrl);
  83845. };
  83846. /**
  83847. * Standard reflectance value at parallel view angle.
  83848. */
  83849. BackgroundMaterial.standardReflectance0 = 0.05;
  83850. /**
  83851. * Standard reflectance value at grazing angle.
  83852. */
  83853. BackgroundMaterial.standardReflectance90 = 0.5;
  83854. __decorate([
  83855. BABYLON.serializeAsColor3()
  83856. ], BackgroundMaterial.prototype, "_primaryColor", void 0);
  83857. __decorate([
  83858. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  83859. ], BackgroundMaterial.prototype, "primaryColor", void 0);
  83860. __decorate([
  83861. BABYLON.serialize()
  83862. ], BackgroundMaterial.prototype, "_primaryLevel", void 0);
  83863. __decorate([
  83864. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  83865. ], BackgroundMaterial.prototype, "primaryLevel", void 0);
  83866. __decorate([
  83867. BABYLON.serializeAsColor3()
  83868. ], BackgroundMaterial.prototype, "_secondaryColor", void 0);
  83869. __decorate([
  83870. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  83871. ], BackgroundMaterial.prototype, "secondaryColor", void 0);
  83872. __decorate([
  83873. BABYLON.serialize()
  83874. ], BackgroundMaterial.prototype, "_secondaryLevel", void 0);
  83875. __decorate([
  83876. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  83877. ], BackgroundMaterial.prototype, "secondaryLevel", void 0);
  83878. __decorate([
  83879. BABYLON.serializeAsColor3()
  83880. ], BackgroundMaterial.prototype, "_tertiaryColor", void 0);
  83881. __decorate([
  83882. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  83883. ], BackgroundMaterial.prototype, "tertiaryColor", void 0);
  83884. __decorate([
  83885. BABYLON.serialize()
  83886. ], BackgroundMaterial.prototype, "_tertiaryLevel", void 0);
  83887. __decorate([
  83888. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  83889. ], BackgroundMaterial.prototype, "tertiaryLevel", void 0);
  83890. __decorate([
  83891. BABYLON.serializeAsTexture()
  83892. ], BackgroundMaterial.prototype, "_reflectionTexture", void 0);
  83893. __decorate([
  83894. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  83895. ], BackgroundMaterial.prototype, "reflectionTexture", void 0);
  83896. __decorate([
  83897. BABYLON.serialize()
  83898. ], BackgroundMaterial.prototype, "_reflectionBlur", void 0);
  83899. __decorate([
  83900. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  83901. ], BackgroundMaterial.prototype, "reflectionBlur", void 0);
  83902. __decorate([
  83903. BABYLON.serializeAsTexture()
  83904. ], BackgroundMaterial.prototype, "_diffuseTexture", void 0);
  83905. __decorate([
  83906. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  83907. ], BackgroundMaterial.prototype, "diffuseTexture", void 0);
  83908. __decorate([
  83909. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  83910. ], BackgroundMaterial.prototype, "shadowLights", void 0);
  83911. __decorate([
  83912. BABYLON.serialize()
  83913. ], BackgroundMaterial.prototype, "_shadowBlurScale", void 0);
  83914. __decorate([
  83915. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  83916. ], BackgroundMaterial.prototype, "shadowBlurScale", void 0);
  83917. __decorate([
  83918. BABYLON.serialize()
  83919. ], BackgroundMaterial.prototype, "_shadowLevel", void 0);
  83920. __decorate([
  83921. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  83922. ], BackgroundMaterial.prototype, "shadowLevel", void 0);
  83923. __decorate([
  83924. BABYLON.serializeAsVector3()
  83925. ], BackgroundMaterial.prototype, "_sceneCenter", void 0);
  83926. __decorate([
  83927. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  83928. ], BackgroundMaterial.prototype, "sceneCenter", void 0);
  83929. __decorate([
  83930. BABYLON.serialize()
  83931. ], BackgroundMaterial.prototype, "_opacityFresnel", void 0);
  83932. __decorate([
  83933. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  83934. ], BackgroundMaterial.prototype, "opacityFresnel", void 0);
  83935. __decorate([
  83936. BABYLON.serialize()
  83937. ], BackgroundMaterial.prototype, "_reflectionFresnel", void 0);
  83938. __decorate([
  83939. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  83940. ], BackgroundMaterial.prototype, "reflectionFresnel", void 0);
  83941. __decorate([
  83942. BABYLON.serialize()
  83943. ], BackgroundMaterial.prototype, "_reflectionFalloffDistance", void 0);
  83944. __decorate([
  83945. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  83946. ], BackgroundMaterial.prototype, "reflectionFalloffDistance", void 0);
  83947. __decorate([
  83948. BABYLON.serialize()
  83949. ], BackgroundMaterial.prototype, "_reflectionAmount", void 0);
  83950. __decorate([
  83951. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  83952. ], BackgroundMaterial.prototype, "reflectionAmount", void 0);
  83953. __decorate([
  83954. BABYLON.serialize()
  83955. ], BackgroundMaterial.prototype, "_reflectionReflectance0", void 0);
  83956. __decorate([
  83957. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  83958. ], BackgroundMaterial.prototype, "reflectionReflectance0", void 0);
  83959. __decorate([
  83960. BABYLON.serialize()
  83961. ], BackgroundMaterial.prototype, "_reflectionReflectance90", void 0);
  83962. __decorate([
  83963. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  83964. ], BackgroundMaterial.prototype, "reflectionReflectance90", void 0);
  83965. __decorate([
  83966. BABYLON.serialize()
  83967. ], BackgroundMaterial.prototype, "_useRGBColor", void 0);
  83968. __decorate([
  83969. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  83970. ], BackgroundMaterial.prototype, "useRGBColor", void 0);
  83971. __decorate([
  83972. BABYLON.serialize()
  83973. ], BackgroundMaterial.prototype, "_enableNoise", void 0);
  83974. __decorate([
  83975. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  83976. ], BackgroundMaterial.prototype, "enableNoise", void 0);
  83977. __decorate([
  83978. BABYLON.serialize()
  83979. ], BackgroundMaterial.prototype, "_maxSimultaneousLights", void 0);
  83980. __decorate([
  83981. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  83982. ], BackgroundMaterial.prototype, "maxSimultaneousLights", void 0);
  83983. __decorate([
  83984. BABYLON.serializeAsImageProcessingConfiguration()
  83985. ], BackgroundMaterial.prototype, "_imageProcessingConfiguration", void 0);
  83986. return BackgroundMaterial;
  83987. }(BABYLON.PushMaterial));
  83988. BABYLON.BackgroundMaterial = BackgroundMaterial;
  83989. })(BABYLON || (BABYLON = {}));
  83990. //# sourceMappingURL=babylon.backgroundMaterial.js.map
  83991. var __assign = (this && this.__assign) || Object.assign || function(t) {
  83992. for (var s, i = 1, n = arguments.length; i < n; i++) {
  83993. s = arguments[i];
  83994. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  83995. t[p] = s[p];
  83996. }
  83997. return t;
  83998. };
  83999. var BABYLON;
  84000. (function (BABYLON) {
  84001. /**
  84002. * The Environment helper class can be used to add a fully featuread none expensive background to your scene.
  84003. * It includes by default a skybox and a ground relying on the BackgroundMaterial.
  84004. * It also helps with the default setup of your imageProcessing configuration.
  84005. */
  84006. var EnvironmentHelper = /** @class */ (function () {
  84007. /**
  84008. * constructor
  84009. * @param options
  84010. * @param scene The scene to add the material to
  84011. */
  84012. function EnvironmentHelper(options, scene) {
  84013. this._options = __assign({}, EnvironmentHelper._getDefaultOptions(), options);
  84014. this._scene = scene;
  84015. this._setupBackground();
  84016. this._setupImageProcessing();
  84017. }
  84018. /**
  84019. * Creates the default options for the helper.
  84020. */
  84021. EnvironmentHelper._getDefaultOptions = function () {
  84022. return {
  84023. createGround: true,
  84024. groundSize: 15,
  84025. groundTexture: this._groundTextureCDNUrl,
  84026. groundColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  84027. groundOpacity: 0.9,
  84028. enableGroundShadow: true,
  84029. groundShadowLevel: 0.5,
  84030. enableGroundMirror: false,
  84031. groundMirrorSizeRatio: 0.3,
  84032. groundMirrorBlurKernel: 64,
  84033. groundMirrorAmount: 1,
  84034. groundMirrorFresnelWeight: 1,
  84035. groundMirrorFallOffDistance: 0,
  84036. groundMirrorTextureType: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT,
  84037. groundYBias: 0.00001,
  84038. createSkybox: true,
  84039. skyboxSize: 20,
  84040. skyboxTexture: this._skyboxTextureCDNUrl,
  84041. skyboxColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  84042. backgroundYRotation: 0,
  84043. sizeAuto: true,
  84044. rootPosition: BABYLON.Vector3.Zero(),
  84045. setupImageProcessing: true,
  84046. environmentTexture: this._environmentTextureCDNUrl,
  84047. cameraExposure: 0.8,
  84048. cameraContrast: 1.2,
  84049. toneMappingEnabled: true,
  84050. };
  84051. };
  84052. Object.defineProperty(EnvironmentHelper.prototype, "rootMesh", {
  84053. /**
  84054. * Gets the root mesh created by the helper.
  84055. */
  84056. get: function () {
  84057. return this._rootMesh;
  84058. },
  84059. enumerable: true,
  84060. configurable: true
  84061. });
  84062. Object.defineProperty(EnvironmentHelper.prototype, "skybox", {
  84063. /**
  84064. * Gets the skybox created by the helper.
  84065. */
  84066. get: function () {
  84067. return this._skybox;
  84068. },
  84069. enumerable: true,
  84070. configurable: true
  84071. });
  84072. Object.defineProperty(EnvironmentHelper.prototype, "skyboxTexture", {
  84073. /**
  84074. * Gets the skybox texture created by the helper.
  84075. */
  84076. get: function () {
  84077. return this._skyboxTexture;
  84078. },
  84079. enumerable: true,
  84080. configurable: true
  84081. });
  84082. Object.defineProperty(EnvironmentHelper.prototype, "skyboxMaterial", {
  84083. /**
  84084. * Gets the skybox material created by the helper.
  84085. */
  84086. get: function () {
  84087. return this._skyboxMaterial;
  84088. },
  84089. enumerable: true,
  84090. configurable: true
  84091. });
  84092. Object.defineProperty(EnvironmentHelper.prototype, "ground", {
  84093. /**
  84094. * Gets the ground mesh created by the helper.
  84095. */
  84096. get: function () {
  84097. return this._ground;
  84098. },
  84099. enumerable: true,
  84100. configurable: true
  84101. });
  84102. Object.defineProperty(EnvironmentHelper.prototype, "groundTexture", {
  84103. /**
  84104. * Gets the ground texture created by the helper.
  84105. */
  84106. get: function () {
  84107. return this._groundTexture;
  84108. },
  84109. enumerable: true,
  84110. configurable: true
  84111. });
  84112. Object.defineProperty(EnvironmentHelper.prototype, "groundMirror", {
  84113. /**
  84114. * Gets the ground mirror created by the helper.
  84115. */
  84116. get: function () {
  84117. return this._groundMirror;
  84118. },
  84119. enumerable: true,
  84120. configurable: true
  84121. });
  84122. Object.defineProperty(EnvironmentHelper.prototype, "groundMirrorRenderList", {
  84123. /**
  84124. * Gets the ground mirror render list to helps pushing the meshes
  84125. * you wish in the ground reflection.
  84126. */
  84127. get: function () {
  84128. if (this._groundMirror) {
  84129. return this._groundMirror.renderList;
  84130. }
  84131. return null;
  84132. },
  84133. enumerable: true,
  84134. configurable: true
  84135. });
  84136. Object.defineProperty(EnvironmentHelper.prototype, "groundMaterial", {
  84137. /**
  84138. * Gets the ground material created by the helper.
  84139. */
  84140. get: function () {
  84141. return this._groundMaterial;
  84142. },
  84143. enumerable: true,
  84144. configurable: true
  84145. });
  84146. /**
  84147. * Updates the background according to the new options
  84148. * @param options
  84149. */
  84150. EnvironmentHelper.prototype.updateOptions = function (options) {
  84151. var newOptions = __assign({}, this._options, options);
  84152. if (this._ground && !newOptions.createGround) {
  84153. this._ground.dispose();
  84154. this._ground = null;
  84155. }
  84156. if (this._groundMaterial && !newOptions.createGround) {
  84157. this._groundMaterial.dispose();
  84158. this._groundMaterial = null;
  84159. }
  84160. if (this._groundTexture) {
  84161. if (this._options.groundTexture != newOptions.groundTexture) {
  84162. this._groundTexture.dispose();
  84163. this._groundTexture = null;
  84164. }
  84165. }
  84166. if (this._skybox && !newOptions.createSkybox) {
  84167. this._skybox.dispose();
  84168. this._skybox = null;
  84169. }
  84170. if (this._skyboxMaterial && !newOptions.createSkybox) {
  84171. this._skyboxMaterial.dispose();
  84172. this._skyboxMaterial = null;
  84173. }
  84174. if (this._skyboxTexture) {
  84175. if (this._options.skyboxTexture != newOptions.skyboxTexture) {
  84176. this._skyboxTexture.dispose();
  84177. this._skyboxTexture = null;
  84178. }
  84179. }
  84180. if (this._groundMirror && !newOptions.enableGroundMirror) {
  84181. this._groundMirror.dispose();
  84182. this._groundMirror = null;
  84183. }
  84184. if (this._scene.environmentTexture) {
  84185. if (this._options.environmentTexture != newOptions.environmentTexture) {
  84186. this._scene.environmentTexture.dispose();
  84187. }
  84188. }
  84189. this._options = newOptions;
  84190. this._setupBackground();
  84191. this._setupImageProcessing();
  84192. };
  84193. /**
  84194. * Sets the primary color of all the available elements.
  84195. * @param color
  84196. */
  84197. EnvironmentHelper.prototype.setMainColor = function (color) {
  84198. if (this.groundMaterial) {
  84199. this.groundMaterial.primaryColor = color;
  84200. }
  84201. if (this.skyboxMaterial) {
  84202. this.skyboxMaterial.primaryColor = color;
  84203. }
  84204. if (this.groundMirror) {
  84205. this.groundMirror.clearColor = new BABYLON.Color4(color.r, color.g, color.b, 1.0);
  84206. }
  84207. };
  84208. /**
  84209. * Setup the image processing according to the specified options.
  84210. */
  84211. EnvironmentHelper.prototype._setupImageProcessing = function () {
  84212. if (this._options.setupImageProcessing) {
  84213. this._scene.imageProcessingConfiguration.contrast = this._options.cameraContrast;
  84214. this._scene.imageProcessingConfiguration.exposure = this._options.cameraExposure;
  84215. this._scene.imageProcessingConfiguration.toneMappingEnabled = this._options.toneMappingEnabled;
  84216. this._setupEnvironmentTexture();
  84217. }
  84218. };
  84219. /**
  84220. * Setup the environment texture according to the specified options.
  84221. */
  84222. EnvironmentHelper.prototype._setupEnvironmentTexture = function () {
  84223. if (this._scene.environmentTexture) {
  84224. return;
  84225. }
  84226. if (this._options.environmentTexture instanceof BABYLON.BaseTexture) {
  84227. this._scene.environmentTexture = this._options.environmentTexture;
  84228. return;
  84229. }
  84230. var environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(this._options.environmentTexture, this._scene);
  84231. this._scene.environmentTexture = environmentTexture;
  84232. };
  84233. /**
  84234. * Setup the background according to the specified options.
  84235. */
  84236. EnvironmentHelper.prototype._setupBackground = function () {
  84237. if (!this._rootMesh) {
  84238. this._rootMesh = new BABYLON.Mesh("BackgroundHelper", this._scene);
  84239. }
  84240. this._rootMesh.rotation.y = this._options.backgroundYRotation;
  84241. var sceneSize = this._getSceneSize();
  84242. if (this._options.createGround) {
  84243. this._setupGround(sceneSize);
  84244. this._setupGroundMaterial();
  84245. this._setupGroundDiffuseTexture();
  84246. if (this._options.enableGroundMirror) {
  84247. this._setupGroundMirrorTexture(sceneSize);
  84248. }
  84249. this._setupMirrorInGroundMaterial();
  84250. }
  84251. if (this._options.createSkybox) {
  84252. this._setupSkybox(sceneSize);
  84253. this._setupSkyboxMaterial();
  84254. this._setupSkyboxReflectionTexture();
  84255. }
  84256. this._rootMesh.position.x = sceneSize.rootPosition.x;
  84257. this._rootMesh.position.z = sceneSize.rootPosition.z;
  84258. this._rootMesh.position.y = sceneSize.rootPosition.y;
  84259. };
  84260. /**
  84261. * Get the scene sizes according to the setup.
  84262. */
  84263. EnvironmentHelper.prototype._getSceneSize = function () {
  84264. var groundSize = this._options.groundSize;
  84265. var skyboxSize = this._options.skyboxSize;
  84266. var rootPosition = this._options.rootPosition;
  84267. if (!this._scene.meshes || this._scene.meshes.length === 1) {
  84268. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  84269. }
  84270. var sceneExtends = this._scene.getWorldExtends();
  84271. var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  84272. if (this._options.sizeAuto) {
  84273. if (this._scene.activeCamera instanceof BABYLON.ArcRotateCamera &&
  84274. this._scene.activeCamera.upperRadiusLimit) {
  84275. groundSize = this._scene.activeCamera.upperRadiusLimit * 2;
  84276. skyboxSize = groundSize;
  84277. }
  84278. var sceneDiagonalLenght = sceneDiagonal.length();
  84279. if (sceneDiagonalLenght > groundSize) {
  84280. groundSize = sceneDiagonalLenght * 2;
  84281. skyboxSize = groundSize;
  84282. }
  84283. // 10 % bigger.
  84284. groundSize *= 1.1;
  84285. skyboxSize *= 1.5;
  84286. rootPosition = sceneExtends.min.add(sceneDiagonal.scale(0.5));
  84287. rootPosition.y = sceneExtends.min.y - this._options.groundYBias;
  84288. }
  84289. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  84290. };
  84291. /**
  84292. * Setup the ground according to the specified options.
  84293. */
  84294. EnvironmentHelper.prototype._setupGround = function (sceneSize) {
  84295. var _this = this;
  84296. if (!this._ground) {
  84297. this._ground = BABYLON.Mesh.CreatePlane("BackgroundPlane", sceneSize.groundSize, this._scene);
  84298. this._ground.rotation.x = Math.PI / 2; // Face up by default.
  84299. this._ground.parent = this._rootMesh;
  84300. this._ground.onDisposeObservable.add(function () { _this._ground = null; });
  84301. }
  84302. this._ground.receiveShadows = this._options.enableGroundShadow;
  84303. };
  84304. /**
  84305. * Setup the ground material according to the specified options.
  84306. */
  84307. EnvironmentHelper.prototype._setupGroundMaterial = function () {
  84308. if (!this._groundMaterial) {
  84309. this._groundMaterial = new BABYLON.BackgroundMaterial("BackgroundPlaneMaterial", this._scene);
  84310. }
  84311. this._groundMaterial.alpha = this._options.groundOpacity;
  84312. this._groundMaterial.alphaMode = BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;
  84313. this._groundMaterial.shadowLevel = this._options.groundShadowLevel;
  84314. this._groundMaterial.primaryLevel = 1;
  84315. this._groundMaterial.primaryColor = this._options.groundColor;
  84316. this._groundMaterial.secondaryLevel = 0;
  84317. this._groundMaterial.tertiaryLevel = 0;
  84318. this._groundMaterial.useRGBColor = false;
  84319. this._groundMaterial.enableNoise = true;
  84320. if (this._ground) {
  84321. this._ground.material = this._groundMaterial;
  84322. }
  84323. };
  84324. /**
  84325. * Setup the ground diffuse texture according to the specified options.
  84326. */
  84327. EnvironmentHelper.prototype._setupGroundDiffuseTexture = function () {
  84328. if (!this._groundMaterial) {
  84329. return;
  84330. }
  84331. if (this._groundTexture) {
  84332. return;
  84333. }
  84334. if (this._options.groundTexture instanceof BABYLON.BaseTexture) {
  84335. this._groundMaterial.diffuseTexture = this._options.groundTexture;
  84336. return;
  84337. }
  84338. var diffuseTexture = new BABYLON.Texture(this._options.groundTexture, this._scene);
  84339. diffuseTexture.gammaSpace = false;
  84340. diffuseTexture.hasAlpha = true;
  84341. this._groundMaterial.diffuseTexture = diffuseTexture;
  84342. };
  84343. /**
  84344. * Setup the ground mirror texture according to the specified options.
  84345. */
  84346. EnvironmentHelper.prototype._setupGroundMirrorTexture = function (sceneSize) {
  84347. var wrapping = BABYLON.Texture.CLAMP_ADDRESSMODE;
  84348. if (!this._groundMirror) {
  84349. this._groundMirror = new BABYLON.MirrorTexture("BackgroundPlaneMirrorTexture", { ratio: this._options.groundMirrorSizeRatio }, this._scene, false, this._options.groundMirrorTextureType, BABYLON.Texture.BILINEAR_SAMPLINGMODE, true);
  84350. this._groundMirror.mirrorPlane = new BABYLON.Plane(0, -1, 0, sceneSize.rootPosition.y);
  84351. this._groundMirror.anisotropicFilteringLevel = 1;
  84352. this._groundMirror.wrapU = wrapping;
  84353. this._groundMirror.wrapV = wrapping;
  84354. this._groundMirror.gammaSpace = false;
  84355. if (this._groundMirror.renderList) {
  84356. for (var i = 0; i < this._scene.meshes.length; i++) {
  84357. var mesh = this._scene.meshes[i];
  84358. if (mesh !== this._ground &&
  84359. mesh !== this._skybox &&
  84360. mesh !== this._rootMesh) {
  84361. this._groundMirror.renderList.push(mesh);
  84362. }
  84363. }
  84364. }
  84365. }
  84366. this._groundMirror.clearColor = new BABYLON.Color4(this._options.groundColor.r, this._options.groundColor.g, this._options.groundColor.b, 1);
  84367. this._groundMirror.adaptiveBlurKernel = this._options.groundMirrorBlurKernel;
  84368. };
  84369. /**
  84370. * Setup the ground to receive the mirror texture.
  84371. */
  84372. EnvironmentHelper.prototype._setupMirrorInGroundMaterial = function () {
  84373. if (this._groundMaterial) {
  84374. this._groundMaterial.reflectionTexture = this._groundMirror;
  84375. this._groundMaterial.reflectionFresnel = true;
  84376. this._groundMaterial.reflectionAmount = this._options.groundMirrorAmount;
  84377. this._groundMaterial.reflectionStandardFresnelWeight = this._options.groundMirrorFresnelWeight;
  84378. this._groundMaterial.reflectionFalloffDistance = this._options.groundMirrorFallOffDistance;
  84379. }
  84380. };
  84381. /**
  84382. * Setup the skybox according to the specified options.
  84383. */
  84384. EnvironmentHelper.prototype._setupSkybox = function (sceneSize) {
  84385. var _this = this;
  84386. if (!this._skybox) {
  84387. this._skybox = BABYLON.Mesh.CreateBox("BackgroundSkybox", sceneSize.skyboxSize, this._scene, undefined, BABYLON.Mesh.BACKSIDE);
  84388. this._skybox.onDisposeObservable.add(function () { _this._skybox = null; });
  84389. }
  84390. this._skybox.parent = this._rootMesh;
  84391. };
  84392. /**
  84393. * Setup the skybox material according to the specified options.
  84394. */
  84395. EnvironmentHelper.prototype._setupSkyboxMaterial = function () {
  84396. if (!this._skybox) {
  84397. return;
  84398. }
  84399. if (!this._skyboxMaterial) {
  84400. this._skyboxMaterial = new BABYLON.BackgroundMaterial("BackgroundSkyboxMaterial", this._scene);
  84401. }
  84402. this._skyboxMaterial.useRGBColor = false;
  84403. this._skyboxMaterial.primaryLevel = 1;
  84404. this._skyboxMaterial.primaryColor = this._options.skyboxColor;
  84405. this._skyboxMaterial.secondaryLevel = 0;
  84406. this._skyboxMaterial.tertiaryLevel = 0;
  84407. this._skyboxMaterial.enableNoise = true;
  84408. this._skybox.material = this._skyboxMaterial;
  84409. };
  84410. /**
  84411. * Setup the skybox reflection texture according to the specified options.
  84412. */
  84413. EnvironmentHelper.prototype._setupSkyboxReflectionTexture = function () {
  84414. if (!this._skyboxMaterial) {
  84415. return;
  84416. }
  84417. if (this._skyboxTexture) {
  84418. return;
  84419. }
  84420. if (this._options.skyboxTexture instanceof BABYLON.BaseTexture) {
  84421. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  84422. return;
  84423. }
  84424. this._skyboxTexture = new BABYLON.CubeTexture(this._options.skyboxTexture, this._scene);
  84425. this._skyboxTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  84426. this._skyboxTexture.gammaSpace = false;
  84427. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  84428. };
  84429. /**
  84430. * Dispose all the elements created by the Helper.
  84431. */
  84432. EnvironmentHelper.prototype.dispose = function () {
  84433. if (this._groundMaterial) {
  84434. this._groundMaterial.dispose(true, true);
  84435. }
  84436. if (this._skyboxMaterial) {
  84437. this._skyboxMaterial.dispose(true, true);
  84438. }
  84439. this._rootMesh.dispose(false);
  84440. };
  84441. /**
  84442. * Default ground texture URL.
  84443. */
  84444. EnvironmentHelper._groundTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundGround.png";
  84445. /**
  84446. * Default skybox texture URL.
  84447. */
  84448. EnvironmentHelper._skyboxTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundSkybox.dds";
  84449. /**
  84450. * Default environment texture URL.
  84451. */
  84452. EnvironmentHelper._environmentTextureCDNUrl = "https://assets.babylonjs.com/environments/environmentSpecular.dds";
  84453. return EnvironmentHelper;
  84454. }());
  84455. BABYLON.EnvironmentHelper = EnvironmentHelper;
  84456. })(BABYLON || (BABYLON = {}));
  84457. //# sourceMappingURL=babylon.environmentHelper.js.map
  84458. BABYLON.Effect.ShadersStore={"defaultVertexShader":"#include<__decl__defaultVertex>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<helperFunctions>\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nvarying vec2 vDiffuseUV;\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nvarying vec2 vAmbientUV;\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nvarying vec2 vOpacityUV;\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nvarying vec2 vEmissiveUV;\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nvarying vec2 vLightmapUV;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM) && SPECULARDIRECTUV == 0\nvarying vec2 vSpecularUV;\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<bumpVertexDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\nvec3 positionUpdated=position;\n#ifdef NORMAL \nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=positionUpdated;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normalUpdated);\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif\n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM) && SPECULARDIRECTUV == 0\nif (vSpecularInfos.x == 0.)\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#include<bumpVertex>\n#include<clipPlaneVertex>\n#include<fogVertex>\n#include<shadowsVertex>[0..maxSimultaneousLights]\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n#include<pointCloudVertex>\n#include<logDepthVertex>\n}","defaultPixelShader":"#include<__decl__defaultFragment>\n#if defined(BUMP) || !defined(NORMAL)\n#extension GL_OES_standard_derivatives : enable\n#endif\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\n\n#define RECIPROCAL_PI2 0.15915494\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n\n#include<helperFunctions>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n\n#ifdef DIFFUSE\n#if DIFFUSEDIRECTUV == 1\n#define vDiffuseUV vMainUV1\n#elif DIFFUSEDIRECTUV == 2\n#define vDiffuseUV vMainUV2\n#else\nvarying vec2 vDiffuseUV;\n#endif\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef AMBIENT\n#if AMBIENTDIRECTUV == 1\n#define vAmbientUV vMainUV1\n#elif AMBIENTDIRECTUV == 2\n#define vAmbientUV vMainUV2\n#else\nvarying vec2 vAmbientUV;\n#endif\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY \n#if OPACITYDIRECTUV == 1\n#define vOpacityUV vMainUV1\n#elif OPACITYDIRECTUV == 2\n#define vOpacityUV vMainUV2\n#else\nvarying vec2 vOpacityUV;\n#endif\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\n#if EMISSIVEDIRECTUV == 1\n#define vEmissiveUV vMainUV1\n#elif EMISSIVEDIRECTUV == 2\n#define vEmissiveUV vMainUV2\n#else\nvarying vec2 vEmissiveUV;\n#endif\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\n#if LIGHTMAPDIRECTUV == 1\n#define vLightmapUV vMainUV1\n#elif LIGHTMAPDIRECTUV == 2\n#define vLightmapUV vMainUV2\n#else\nvarying vec2 vLightmapUV;\n#endif\nuniform sampler2D lightmapSampler;\n#endif\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\nuniform samplerCube refractionCubeSampler;\n#else\nuniform sampler2D refraction2DSampler;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\n#if SPECULARDIRECTUV == 1\n#define vSpecularUV vMainUV1\n#elif SPECULARDIRECTUV == 2\n#define vSpecularUV vMainUV2\n#else\nvarying vec2 vSpecularUV;\n#endif\nuniform sampler2D specularSampler;\n#endif\n\n#include<fresnelFunction>\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\nuniform samplerCube reflectionCubeSampler;\n#else\nuniform sampler2D reflection2DSampler;\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#include<imageProcessingDeclaration>\n#include<imageProcessingFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n#include<fogFragmentDeclaration>\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\nvec4 baseColor=vec4(1.,1.,1.,1.);\nvec3 diffuseColor=vDiffuseColor.rgb;\n\nfloat alpha=vDiffuseColor.a;\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=normalize(-cross(dFdx(vPositionW),dFdy(vPositionW)));\n#endif\n#include<bumpFragment>\n#ifdef TWOSIDEDLIGHTING\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n#ifdef DIFFUSE\nbaseColor=texture2D(diffuseSampler,vDiffuseUV+uvOffset);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\n#ifdef ALPHAFROMDIFFUSE\nalpha*=baseColor.a;\n#endif\nbaseColor.rgb*=vDiffuseInfos.y;\n#endif\n#include<depthPrePass>\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n\nvec3 baseAmbientColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nbaseAmbientColor=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#endif\n\n#ifdef SPECULARTERM\nfloat glossiness=vSpecularColor.a;\nvec3 specularColor=vSpecularColor.rgb;\n#ifdef SPECULAR\nvec4 specularMapColor=texture2D(specularSampler,vSpecularUV+uvOffset);\nspecularColor=specularMapColor.rgb;\n#ifdef GLOSSINESS\nglossiness=glossiness*specularMapColor.a;\n#endif\n#endif\n#else\nfloat glossiness=0.;\n#endif\n\nvec3 diffuseBase=vec3(0.,0.,0.);\nlightingInfo info;\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\nfloat shadow=1.;\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb*vLightmapInfos.y;\n#endif\n#include<lightFragment>[0..maxSimultaneousLights]\n\nvec3 refractionColor=vec3(0.,0.,0.);\n#ifdef REFRACTION\nvec3 refractionVector=normalize(refract(-viewDirectionW,normalW,vRefractionInfos.y));\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nif (dot(refractionVector,viewDirectionW)<1.0)\n{\nrefractionColor=textureCube(refractionCubeSampler,refractionVector).rgb*vRefractionInfos.x;\n}\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\nrefractionColor=texture2D(refraction2DSampler,refractionCoords).rgb*vRefractionInfos.x;\n#endif\n#endif\n\nvec3 reflectionColor=vec3(0.,0.,0.);\n#ifdef REFLECTION\nvec3 vReflectionUVW=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_3D\n#ifdef ROUGHNESS\nfloat bias=vReflectionInfos.y;\n#ifdef SPECULARTERM\n#ifdef SPECULAR\n#ifdef GLOSSINESS\nbias*=(1.0-specularMapColor.a);\n#endif\n#endif\n#endif\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW,bias).rgb*vReflectionInfos.x;\n#else\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW).rgb*vReflectionInfos.x;\n#endif\n#else\nvec2 coords=vReflectionUVW.xy;\n#ifdef REFLECTIONMAP_PROJECTION\ncoords/=vReflectionUVW.z;\n#endif\ncoords.y=1.0-coords.y;\nreflectionColor=texture2D(reflection2DSampler,coords).rgb*vReflectionInfos.x;\n#endif\n#ifdef REFLECTIONFRESNEL\nfloat reflectionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,reflectionRightColor.a,reflectionLeftColor.a);\n#ifdef REFLECTIONFRESNELFROMSPECULAR\n#ifdef SPECULARTERM\nreflectionColor*=specularColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#endif\n#endif\n#ifdef REFRACTIONFRESNEL\nfloat refractionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,refractionRightColor.a,refractionLeftColor.a);\nrefractionColor*=refractionLeftColor.rgb*(1.0-refractionFresnelTerm)+refractionFresnelTerm*refractionRightColor.rgb;\n#endif\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nopacityMap.rgb=opacityMap.rgb*vec3(0.3,0.59,0.11);\nalpha*=(opacityMap.x+opacityMap.y+opacityMap.z)* vOpacityInfos.y;\n#else\nalpha*=opacityMap.a*vOpacityInfos.y;\n#endif\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#ifdef OPACITYFRESNEL\nfloat opacityFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,opacityParts.z,opacityParts.w);\nalpha+=opacityParts.x*(1.0-opacityFresnelTerm)+opacityFresnelTerm*opacityParts.y;\n#endif\n\nvec3 emissiveColor=vEmissiveColor;\n#ifdef EMISSIVE\nemissiveColor+=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb*vEmissiveInfos.y;\n#endif\n#ifdef EMISSIVEFRESNEL\nfloat emissiveFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,emissiveRightColor.a,emissiveLeftColor.a);\nemissiveColor*=emissiveLeftColor.rgb*(1.0-emissiveFresnelTerm)+emissiveFresnelTerm*emissiveRightColor.rgb;\n#endif\n\n#ifdef DIFFUSEFRESNEL\nfloat diffuseFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,diffuseRightColor.a,diffuseLeftColor.a);\ndiffuseBase*=diffuseLeftColor.rgb*(1.0-diffuseFresnelTerm)+diffuseFresnelTerm*diffuseRightColor.rgb;\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\n#ifdef LINKEMISSIVEWITHDIFFUSE\nvec3 finalDiffuse=clamp((diffuseBase+emissiveColor)*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+emissiveColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#endif\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase*specularColor;\n#ifdef SPECULAROVERALPHA\nalpha=clamp(alpha+dot(finalSpecular,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\n#ifdef REFLECTIONOVERALPHA\nalpha=clamp(alpha+dot(reflectionColor,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec4 color=vec4(clamp(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+emissiveColor+refractionColor,0.0,1.0),alpha);\n#else\nvec4 color=vec4(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+refractionColor,alpha);\n#endif\n\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\ncolor.rgb*=lightmapColor;\n#else\ncolor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n#include<logDepthFragment>\n#include<fogFragment>\n\n\n#ifdef IMAGEPROCESSINGPOSTPROCESS\ncolor.rgb=toLinearSpace(color.rgb);\n#else\n#ifdef IMAGEPROCESSING\ncolor.rgb=toLinearSpace(color.rgb);\ncolor=applyImageProcessing(color);\n#endif\n#endif\n#ifdef PREMULTIPLYALPHA\n\ncolor.rgb*=color.a;\n#endif\ngl_FragColor=color;\n}","pbrVertexShader":"precision highp float;\n#include<__decl__pbrVertex>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2; \n#endif \n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<helperFunctions>\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#if defined(ALBEDO) && ALBEDODIRECTUV == 0\nvarying vec2 vAlbedoUV;\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nvarying vec2 vAmbientUV;\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nvarying vec2 vOpacityUV;\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nvarying vec2 vEmissiveUV;\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nvarying vec2 vLightmapUV;\n#endif\n#if defined(REFLECTIVITY) && REFLECTIVITYDIRECTUV == 0\nvarying vec2 vReflectivityUV;\n#endif\n#if defined(MICROSURFACEMAP) && MICROSURFACEMAPDIRECTUV == 0\nvarying vec2 vMicroSurfaceSamplerUV;\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvarying vec3 vEnvironmentIrradiance;\n#include<harmonicsFunctions>\n#endif\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<bumpVertexDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\nvec3 positionUpdated=position;\n#ifdef NORMAL\nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=positionUpdated;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normalUpdated);\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvec3 reflectionVector=vec3(reflectionMatrix*vec4(vNormalW,0)).xyz;\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\nvEnvironmentIrradiance=environmentIrradianceJones(reflectionVector);\n#endif\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif \n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif \n#if defined(ALBEDO) && ALBEDODIRECTUV == 0 \nif (vAlbedoInfos.x == 0.)\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0 \nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0 \nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0 \nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0 \nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(REFLECTIVITY) && REFLECTIVITYDIRECTUV == 0 \nif (vReflectivityInfos.x == 0.)\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(MICROSURFACEMAP) && MICROSURFACEMAPDIRECTUV == 0 \nif (vMicroSurfaceSamplerInfos.x == 0.)\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0 \nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<bumpVertex>\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n\n#include<logDepthVertex>\n}","pbrPixelShader":"#if defined(BUMP) || !defined(NORMAL) || defined(FORCENORMALFORWARD)\n#extension GL_OES_standard_derivatives : enable\n#endif\n#ifdef LODBASEDMICROSFURACE\n#extension GL_EXT_shader_texture_lod : enable\n#endif\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nprecision highp float;\n#include<__decl__pbrFragment>\nuniform vec4 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec4 vCameraInfos;\n\nvarying vec3 vPositionW;\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif \n#ifdef MAINUV2 \nvarying vec2 vMainUV2;\n#endif \n#ifdef NORMAL\nvarying vec3 vNormalW;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvarying vec3 vEnvironmentIrradiance;\n#endif\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n\n#ifdef ALBEDO\n#if ALBEDODIRECTUV == 1\n#define vAlbedoUV vMainUV1\n#elif ALBEDODIRECTUV == 2\n#define vAlbedoUV vMainUV2\n#else\nvarying vec2 vAlbedoUV;\n#endif\nuniform sampler2D albedoSampler;\n#endif\n#ifdef AMBIENT\n#if AMBIENTDIRECTUV == 1\n#define vAmbientUV vMainUV1\n#elif AMBIENTDIRECTUV == 2\n#define vAmbientUV vMainUV2\n#else\nvarying vec2 vAmbientUV;\n#endif\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY\n#if OPACITYDIRECTUV == 1\n#define vOpacityUV vMainUV1\n#elif OPACITYDIRECTUV == 2\n#define vOpacityUV vMainUV2\n#else\nvarying vec2 vOpacityUV;\n#endif\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\n#if EMISSIVEDIRECTUV == 1\n#define vEmissiveUV vMainUV1\n#elif EMISSIVEDIRECTUV == 2\n#define vEmissiveUV vMainUV2\n#else\nvarying vec2 vEmissiveUV;\n#endif\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\n#if LIGHTMAPDIRECTUV == 1\n#define vLightmapUV vMainUV1\n#elif LIGHTMAPDIRECTUV == 2\n#define vLightmapUV vMainUV2\n#else\nvarying vec2 vLightmapUV;\n#endif\nuniform sampler2D lightmapSampler;\n#endif\n#ifdef REFLECTIVITY\n#if REFLECTIVITYDIRECTUV == 1\n#define vReflectivityUV vMainUV1\n#elif REFLECTIVITYDIRECTUV == 2\n#define vReflectivityUV vMainUV2\n#else\nvarying vec2 vReflectivityUV;\n#endif\nuniform sampler2D reflectivitySampler;\n#endif\n#ifdef MICROSURFACEMAP\n#if MICROSURFACEMAPDIRECTUV == 1\n#define vMicroSurfaceSamplerUV vMainUV1\n#elif MICROSURFACEMAPDIRECTUV == 2\n#define vMicroSurfaceSamplerUV vMainUV2\n#else\nvarying vec2 vMicroSurfaceSamplerUV;\n#endif\nuniform sampler2D microSurfaceSampler;\n#endif\n\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\n#define sampleRefraction(s,c) textureCube(s,c)\nuniform samplerCube refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube refractionSamplerLow;\nuniform samplerCube refractionSamplerHigh;\n#endif\n#else\n#define sampleRefraction(s,c) texture2D(s,c)\nuniform sampler2D refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube refractionSamplerLow;\nuniform samplerCube refractionSamplerHigh;\n#endif\n#endif\n#endif\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n#define sampleReflection(s,c) textureCube(s,c)\nuniform samplerCube reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#else\n#define sampleReflection(s,c) texture2D(s,c)\nuniform sampler2D reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#ifdef ENVIRONMENTBRDF\nuniform sampler2D environmentBrdfSampler;\n#endif\n\n#ifndef FROMLINEARSPACE\n#define FROMLINEARSPACE;\n#endif\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\n\n#include<shadowsFragmentFunctions>\n#include<pbrFunctions>\n#include<harmonicsFunctions>\n#include<pbrLightFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\n#include<clipPlaneFragment>\n\n\nvec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW);\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;\n#endif\n#include<bumpFragment>\n#if defined(FORCENORMALFORWARD) && defined(NORMAL)\nvec3 faceNormal=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;\n#if defined(TWOSIDEDLIGHTING)\nfaceNormal=gl_FrontFacing ? faceNormal : -faceNormal;\n#endif\nnormalW*=sign(dot(normalW,faceNormal));\n#endif\n#if defined(TWOSIDEDLIGHTING) && defined(NORMAL)\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n\n\nvec3 surfaceAlbedo=vAlbedoColor.rgb;\n\nfloat alpha=vAlbedoColor.a;\n#ifdef ALBEDO\nvec4 albedoTexture=texture2D(albedoSampler,vAlbedoUV+uvOffset);\n#if defined(ALPHAFROMALBEDO) || defined(ALPHATEST)\nalpha*=albedoTexture.a;\n#endif\nsurfaceAlbedo*=toLinearSpace(albedoTexture.rgb);\nsurfaceAlbedo*=vAlbedoInfos.y;\n#endif\n\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nalpha=getLuminance(opacityMap.rgb);\n#else\nalpha*=opacityMap.a;\n#endif\nalpha*=vOpacityInfos.y;\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#if !defined(LINKREFRACTIONTOTRANSPARENCY) && !defined(ALPHAFRESNEL)\n#ifdef ALPHATEST\nif (alpha<=ALPHATESTVALUE)\ndiscard;\n#ifndef ALPHABLEND\n\nalpha=1.0;\n#endif\n#endif\n#endif\n#include<depthPrePass>\n#ifdef VERTEXCOLOR\nsurfaceAlbedo*=vColor.rgb;\n#endif\n\nvec3 ambientOcclusionColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nvec3 ambientOcclusionColorMap=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#ifdef AMBIENTINGRAYSCALE\nambientOcclusionColorMap=vec3(ambientOcclusionColorMap.r,ambientOcclusionColorMap.r,ambientOcclusionColorMap.r);\n#endif\nambientOcclusionColor=mix(ambientOcclusionColor,ambientOcclusionColorMap,vAmbientInfos.z);\n#endif\n\nfloat microSurface=vReflectivityColor.a;\nvec3 surfaceReflectivityColor=vReflectivityColor.rgb;\n#ifdef METALLICWORKFLOW\nvec2 metallicRoughness=surfaceReflectivityColor.rg;\n#ifdef REFLECTIVITY\nvec4 surfaceMetallicColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\n#ifdef AOSTOREINMETALMAPRED\nvec3 aoStoreInMetalMap=vec3(surfaceMetallicColorMap.r,surfaceMetallicColorMap.r,surfaceMetallicColorMap.r);\nambientOcclusionColor=mix(ambientOcclusionColor,aoStoreInMetalMap,vReflectivityInfos.z);\n#endif\n#ifdef METALLNESSSTOREINMETALMAPBLUE\nmetallicRoughness.r*=surfaceMetallicColorMap.b;\n#else\nmetallicRoughness.r*=surfaceMetallicColorMap.r;\n#endif\n#ifdef ROUGHNESSSTOREINMETALMAPALPHA\nmetallicRoughness.g*=surfaceMetallicColorMap.a;\n#else\n#ifdef ROUGHNESSSTOREINMETALMAPGREEN\nmetallicRoughness.g*=surfaceMetallicColorMap.g;\n#endif\n#endif\n#endif\n#ifdef MICROSURFACEMAP\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\nmetallicRoughness.g*=microSurfaceTexel.r;\n#endif\n\nmicroSurface=1.0-metallicRoughness.g;\n\nvec3 baseColor=surfaceAlbedo;\n\n\nconst vec3 DefaultSpecularReflectanceDielectric=vec3(0.04,0.04,0.04);\n\nsurfaceAlbedo=mix(baseColor.rgb*(1.0-DefaultSpecularReflectanceDielectric.r),vec3(0.,0.,0.),metallicRoughness.r);\n\nsurfaceReflectivityColor=mix(DefaultSpecularReflectanceDielectric,baseColor,metallicRoughness.r);\n#else\n#ifdef REFLECTIVITY\nvec4 surfaceReflectivityColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\nsurfaceReflectivityColor*=toLinearSpace(surfaceReflectivityColorMap.rgb);\nsurfaceReflectivityColor*=vReflectivityInfos.y;\n#ifdef MICROSURFACEFROMREFLECTIVITYMAP\nmicroSurface*=surfaceReflectivityColorMap.a;\nmicroSurface*=vReflectivityInfos.z;\n#else\n#ifdef MICROSURFACEAUTOMATIC\nmicroSurface*=computeDefaultMicroSurface(microSurface,surfaceReflectivityColor);\n#endif\n#ifdef MICROSURFACEMAP\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\nmicroSurface*=microSurfaceTexel.r;\n#endif\n#endif\n#endif\n#endif\n\nmicroSurface=clamp(microSurface,0.,1.);\n\nfloat roughness=1.-microSurface;\n\n#ifdef ALPHAFRESNEL\n#if defined(ALPHATEST) || defined(ALPHABLEND)\n\n\n\nfloat opacityPerceptual=alpha;\n#ifdef LINEARALPHAFRESNEL\nfloat opacity0=opacityPerceptual;\n#else\nfloat opacity0=opacityPerceptual*opacityPerceptual;\n#endif\nfloat opacity90=fresnelGrazingReflectance(opacity0);\nvec3 normalForward=faceforward(normalW,-viewDirectionW,normalW);\n\nalpha=fresnelSchlickEnvironmentGGX(clamp(dot(viewDirectionW,normalForward),0.0,1.0),vec3(opacity0),vec3(opacity90),sqrt(microSurface)).x;\n#ifdef ALPHATEST\nif (alpha<=ALPHATESTVALUE)\ndiscard;\n#ifndef ALPHABLEND\n\nalpha=1.0;\n#endif\n#endif\n#endif\n#endif\n\n\nfloat NdotVUnclamped=dot(normalW,viewDirectionW);\nfloat NdotV=clamp(NdotVUnclamped,0.,1.)+0.00001;\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\n\n#ifdef REFRACTION\nvec3 environmentRefraction=vec3(0.,0.,0.);\nvec3 refractionVector=refract(-viewDirectionW,normalW,vRefractionInfos.y);\n#ifdef REFRACTIONMAP_OPPOSITEZ\nrefractionVector.z*=-1.0;\n#endif\n\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nvec3 refractionCoords=refractionVector;\nrefractionCoords=vec3(refractionMatrix*vec4(refractionCoords,0));\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\n#endif\n#ifdef LODINREFRACTIONALPHA\nfloat refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,alphaG,NdotVUnclamped);\n#else\nfloat refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,alphaG,1.0);\n#endif\n#ifdef LODBASEDMICROSFURACE\n\nrefractionLOD=refractionLOD*vRefractionMicrosurfaceInfos.y+vRefractionMicrosurfaceInfos.z;\n#ifdef LODINREFRACTIONALPHA\n\n\n\n\n\n\n\n\n\nfloat automaticRefractionLOD=UNPACK_LOD(sampleRefraction(refractionSampler,refractionCoords).a);\nfloat requestedRefractionLOD=max(automaticRefractionLOD,refractionLOD);\n#else\nfloat requestedRefractionLOD=refractionLOD;\n#endif\nenvironmentRefraction=sampleRefractionLod(refractionSampler,refractionCoords,requestedRefractionLOD).rgb;\n#else\nfloat lodRefractionNormalized=clamp(refractionLOD/log2(vRefractionMicrosurfaceInfos.x),0.,1.);\nfloat lodRefractionNormalizedDoubled=lodRefractionNormalized*2.0;\nvec3 environmentRefractionMid=sampleRefraction(refractionSampler,refractionCoords).rgb;\nif(lodRefractionNormalizedDoubled<1.0){\nenvironmentRefraction=mix(\nsampleRefraction(refractionSamplerHigh,refractionCoords).rgb,\nenvironmentRefractionMid,\nlodRefractionNormalizedDoubled\n);\n}else{\nenvironmentRefraction=mix(\nenvironmentRefractionMid,\nsampleRefraction(refractionSamplerLow,refractionCoords).rgb,\nlodRefractionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef GAMMAREFRACTION\nenvironmentRefraction=toLinearSpace(environmentRefraction.rgb);\n#endif\n\nenvironmentRefraction*=vRefractionInfos.x;\n#endif\n\n#ifdef REFLECTION\nvec3 environmentRadiance=vec3(0.,0.,0.);\nvec3 environmentIrradiance=vec3(0.,0.,0.);\nvec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\n\n#ifdef REFLECTIONMAP_3D\nvec3 reflectionCoords=reflectionVector;\n#else\nvec2 reflectionCoords=reflectionVector.xy;\n#ifdef REFLECTIONMAP_PROJECTION\nreflectionCoords/=reflectionVector.z;\n#endif\nreflectionCoords.y=1.0-reflectionCoords.y;\n#endif\n#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX)\nfloat reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG,NdotVUnclamped);\n#else\nfloat reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG,1.);\n#endif\n#ifdef LODBASEDMICROSFURACE\n\nreflectionLOD=reflectionLOD*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;\n#ifdef LODINREFLECTIONALPHA\n\n\n\n\n\n\n\n\n\nfloat automaticReflectionLOD=UNPACK_LOD(sampleReflection(reflectionSampler,reflectionCoords).a);\nfloat requestedReflectionLOD=max(automaticReflectionLOD,reflectionLOD);\n#else\nfloat requestedReflectionLOD=reflectionLOD;\n#endif\nenvironmentRadiance=sampleReflectionLod(reflectionSampler,reflectionCoords,requestedReflectionLOD).rgb;\n#else\nfloat lodReflectionNormalized=clamp(reflectionLOD/log2(vReflectionMicrosurfaceInfos.x),0.,1.);\nfloat lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;\nvec3 environmentSpecularMid=sampleReflection(reflectionSampler,reflectionCoords).rgb;\nif(lodReflectionNormalizedDoubled<1.0){\nenvironmentRadiance=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords).rgb,\nenvironmentSpecularMid,\nlodReflectionNormalizedDoubled\n);\n}else{\nenvironmentRadiance=mix(\nenvironmentSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords).rgb,\nlodReflectionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef GAMMAREFLECTION\nenvironmentRadiance=toLinearSpace(environmentRadiance.rgb);\n#endif\n\n#ifdef USESPHERICALFROMREFLECTIONMAP\n#if defined(NORMAL) && defined(USESPHERICALINVERTEX)\nenvironmentIrradiance=vEnvironmentIrradiance;\n#else\nvec3 irradianceVector=vec3(reflectionMatrix*vec4(normalW,0)).xyz;\n#ifdef REFLECTIONMAP_OPPOSITEZ\nirradianceVector.z*=-1.0;\n#endif\nenvironmentIrradiance=environmentIrradianceJones(irradianceVector);\n#endif\n#endif\n\nenvironmentRadiance*=vReflectionInfos.x;\nenvironmentRadiance*=vReflectionColor.rgb;\nenvironmentIrradiance*=vReflectionColor.rgb;\n#endif\n\n\n\nfloat reflectance=max(max(surfaceReflectivityColor.r,surfaceReflectivityColor.g),surfaceReflectivityColor.b);\nfloat reflectance90=fresnelGrazingReflectance(reflectance);\nvec3 specularEnvironmentR0=surfaceReflectivityColor.rgb;\nvec3 specularEnvironmentR90=vec3(1.0,1.0,1.0)*reflectance90;\n\nvec3 diffuseBase=vec3(0.,0.,0.);\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb*vLightmapInfos.y;\n#endif\nlightingInfo info;\nfloat shadow=1.; \nfloat NdotL=-1.;\n#include<lightFragment>[0..maxSimultaneousLights]\n\n#if defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX)\n\nvec2 brdfSamplerUV=vec2(NdotV,roughness);\n\nvec4 environmentBrdf=texture2D(environmentBrdfSampler,brdfSamplerUV);\nvec3 specularEnvironmentReflectance=specularEnvironmentR0*environmentBrdf.x+environmentBrdf.y;\n#ifdef RADIANCEOCCLUSION\n#ifdef AMBIENTINGRAYSCALE\nfloat ambientMonochrome=ambientOcclusionColor.r;\n#else\nfloat ambientMonochrome=getLuminance(ambientOcclusionColor);\n#endif\nfloat seo=environmentRadianceOcclusion(ambientMonochrome,NdotVUnclamped);\nspecularEnvironmentReflectance*=seo;\n#endif\n#ifdef HORIZONOCCLUSION\n#ifdef BUMP\n#ifdef REFLECTIONMAP_3D\nfloat eho=environmentHorizonOcclusion(reflectionCoords,normalW);\nspecularEnvironmentReflectance*=eho;\n#endif\n#endif\n#endif\n#else\n\nvec3 specularEnvironmentReflectance=fresnelSchlickEnvironmentGGX(NdotV,specularEnvironmentR0,specularEnvironmentR90,sqrt(microSurface));\n#endif\n\n#ifdef REFRACTION\nvec3 refractance=vec3(0.0,0.0,0.0);\nvec3 transmission=vec3(1.0,1.0,1.0);\n#ifdef LINKREFRACTIONTOTRANSPARENCY\n\ntransmission*=(1.0-alpha);\n\n\nvec3 mixedAlbedo=surfaceAlbedo;\nfloat maxChannel=max(max(mixedAlbedo.r,mixedAlbedo.g),mixedAlbedo.b);\nvec3 tint=clamp(maxChannel*mixedAlbedo,0.0,1.0);\n\nsurfaceAlbedo*=alpha;\n\nenvironmentIrradiance*=alpha;\n\nenvironmentRefraction*=tint;\n\nalpha=1.0;\n#endif\n\nvec3 bounceSpecularEnvironmentReflectance=(2.0*specularEnvironmentReflectance)/(1.0+specularEnvironmentReflectance);\nspecularEnvironmentReflectance=mix(bounceSpecularEnvironmentReflectance,specularEnvironmentReflectance,alpha);\n\ntransmission*=1.0-specularEnvironmentReflectance;\n\nrefractance=transmission;\n#endif\n\n\n\n\nsurfaceAlbedo.rgb=(1.-reflectance)*surfaceAlbedo.rgb;\n\nvec3 finalDiffuse=diffuseBase;\nfinalDiffuse.rgb+=vAmbientColor;\nfinalDiffuse*=surfaceAlbedo.rgb;\nfinalDiffuse=max(finalDiffuse,0.0);\n\n#ifdef REFLECTION\nvec3 finalIrradiance=environmentIrradiance;\nfinalIrradiance*=surfaceAlbedo.rgb;\n#endif\n\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase;\nfinalSpecular=max(finalSpecular,0.0);\n\nvec3 finalSpecularScaled=finalSpecular*vLightingIntensity.x*vLightingIntensity.w;\n#endif\n\n#ifdef REFLECTION\nvec3 finalRadiance=environmentRadiance;\nfinalRadiance*=specularEnvironmentReflectance;\n\nvec3 finalRadianceScaled=finalRadiance*vLightingIntensity.z;\n#endif\n\n#ifdef REFRACTION\nvec3 finalRefraction=environmentRefraction;\nfinalRefraction*=refractance;\n#endif\n\nvec3 finalEmissive=vEmissiveColor;\n#ifdef EMISSIVE\nvec3 emissiveColorTex=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb;\nfinalEmissive*=toLinearSpace(emissiveColorTex.rgb);\nfinalEmissive*=vEmissiveInfos.y;\n#endif\n\n#ifdef ALPHABLEND\nfloat luminanceOverAlpha=0.0;\n#if defined(REFLECTION) && defined(RADIANCEOVERALPHA)\nluminanceOverAlpha+=getLuminance(finalRadianceScaled);\n#endif\n#if defined(SPECULARTERM) && defined(SPECULAROVERALPHA)\nluminanceOverAlpha+=getLuminance(finalSpecularScaled);\n#endif\n#if defined(RADIANCEOVERALPHA) || defined(SPECULAROVERALPHA)\nalpha=clamp(alpha+luminanceOverAlpha*luminanceOverAlpha,0.,1.);\n#endif\n#endif\n\n\n\nvec4 finalColor=vec4(finalDiffuse*ambientOcclusionColor*vLightingIntensity.x +\n#ifdef REFLECTION\nfinalIrradiance*ambientOcclusionColor*vLightingIntensity.z +\n#endif\n#ifdef SPECULARTERM\n\n\nfinalSpecularScaled +\n#endif\n#ifdef REFLECTION\n\n\nfinalRadianceScaled +\n#endif\n#ifdef REFRACTION\nfinalRefraction*vLightingIntensity.z +\n#endif\nfinalEmissive*vLightingIntensity.y,\nalpha);\n\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\nfinalColor.rgb*=lightmapColor;\n#else\nfinalColor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n\nfinalColor=max(finalColor,0.0);\n#include<logDepthFragment>\n#include<fogFragment>(color,finalColor)\n#ifdef IMAGEPROCESSINGPOSTPROCESS\n\n\nfinalColor.rgb=clamp(finalColor.rgb,0.,30.0);\n#else\n\nfinalColor=applyImageProcessing(finalColor);\n#endif\n#ifdef PREMULTIPLYALPHA\n\nfinalColor.rgb*=finalColor.a;\n#endif\ngl_FragColor=finalColor;\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n}","spritesVertexShader":"\nattribute vec4 position;\nattribute vec4 options;\nattribute vec4 cellInfo;\nattribute vec4 color;\n\nuniform vec2 textureInfos;\nuniform mat4 view;\nuniform mat4 projection;\n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#include<fogVertexDeclaration>\nvoid main(void) { \nvec3 viewPos=(view*vec4(position.xyz,1.0)).xyz; \nvec2 cornerPos;\nfloat angle=position.w;\nvec2 size=vec2(options.x,options.y);\nvec2 offset=options.zw;\nvec2 uvScale=textureInfos.xy;\ncornerPos=vec2(offset.x-0.5,offset.y-0.5)*size;\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nviewPos+=rotatedCorner;\ngl_Position=projection*vec4(viewPos,1.0); \n\nvColor=color;\n\nvec2 uvOffset=vec2(abs(offset.x-cellInfo.x),1.0-abs(offset.y-cellInfo.y));\nvUV=(uvOffset+cellInfo.zw)*uvScale;\n\n#ifdef FOG\nvFogDistance=viewPos;\n#endif\n}","spritesPixelShader":"uniform bool alphaTest;\nvarying vec4 vColor;\n\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\nvec4 color=texture2D(diffuseSampler,vUV);\nif (alphaTest) \n{\nif (color.a<0.95)\ndiscard;\n}\ncolor*=vColor;\n#include<fogFragment>\ngl_FragColor=color;\n}","particlesVertexShader":"\nattribute vec3 position;\nattribute vec4 color;\nattribute vec4 options;\nattribute float cellIndex;\n\nuniform mat4 view;\nuniform mat4 projection;\nuniform vec3 particlesInfos; \n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nuniform mat4 invView;\nvarying float fClipDistance;\n#endif\nvoid main(void) { \nvec3 viewPos=(view*vec4(position,1.0)).xyz; \nvec3 cornerPos;\nfloat size=options.y;\nfloat angle=options.x;\nvec2 offset=options.zw;\ncornerPos=vec3(offset.x-0.5,offset.y-0.5,0.)*size;\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nviewPos+=rotatedCorner;\ngl_Position=projection*vec4(viewPos,1.0); \nvColor=color;\n#ifdef ANIMATESHEET\nfloat rowOffset=floor(cellIndex/particlesInfos.z);\nfloat columnOffset=cellIndex-rowOffset*particlesInfos.z;\nvec2 uvScale=particlesInfos.xy;\nvec2 uvOffset=vec2(offset.x ,1.0-offset.y);\nvUV=(uvOffset+vec2(columnOffset,rowOffset))*uvScale;\n#else\nvUV=offset;\n#endif\n\n#ifdef CLIPPLANE\nvec4 worldPos=invView*vec4(viewPos,1.0);\nfClipDistance=dot(worldPos,vClipPlane);\n#endif\n}","particlesPixelShader":"\nvarying vec2 vUV;\nvarying vec4 vColor;\nuniform vec4 textureMask;\nuniform sampler2D diffuseSampler;\n#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif\nvoid main(void) {\n#ifdef CLIPPLANE\nif (fClipDistance>0.0)\ndiscard;\n#endif\nvec4 baseColor=texture2D(diffuseSampler,vUV);\ngl_FragColor=(baseColor*textureMask+(vec4(1.,1.,1.,1.)-textureMask))*vColor;\n}","gpuRenderParticlesVertexShader":"#version 300 es\n\nin vec3 position;\nin float age;\nin float life;\nin vec3 velocity;\nvoid main() {\ngl_PointSize=1.0;\ngl_Position=vec4(position,1.0);\n}","gpuRenderParticlesPixelShader":"void main() {\ngl_FragColor=vec4(1.0);\n}\n","gpuUpdateParticlesVertexShader":"#version 300 es\nuniform float timeDelta;\n\nin vec3 position;\nin float age;\nin float life;\nin vec3 velocity;\n\nout vec3 outPosition;\nout float outAge;\nout float outLife;\nout vec3 outVelocity;\nvoid main() {\nif (age>=life) {\n\noutPosition=vec3(0,0,0);\n\noutAge=0.0;\noutLife=life;\n\noutVelocity=vec3(0,1,0);\n} else {\noutPosition=position+velocity*timeDelta;\noutAge=age+timeDelta;\noutLife=life;\noutVelocity=velocity;\n}\n}","gpuUpdateParticlesPixelShader":"#version 300 es\nvoid main() {\ndiscard;\n}\n","colorVertexShader":"\nattribute vec3 position;\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\nuniform mat4 viewProjection;\nuniform mat4 world;\n\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\nvoid main(void) {\nmat4 finalWorld=world;\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n}","colorPixelShader":"#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#else\nuniform vec4 color;\n#endif\nvoid main(void) {\n#ifdef VERTEXCOLOR\ngl_FragColor=vColor;\n#else\ngl_FragColor=color;\n#endif\n}","postprocessVertexShader":"\nattribute vec2 position;\nuniform vec2 scale;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd)*scale;\ngl_Position=vec4(position,0.0,1.0);\n}","passPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nvoid main(void) \n{\ngl_FragColor=texture2D(textureSampler,vUV);\n}","shadowMapVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nuniform vec2 biasAndScale;\nuniform vec2 depthValues;\nvarying float vDepthMetric;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\nvec4 worldPos=finalWorld*vec4(position,1.0);\ngl_Position=viewProjection*worldPos;\nvDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y))+biasAndScale.x;\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","shadowMapPixelShader":"#ifndef FLOAT\nvec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvarying float vDepthMetric;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nuniform vec2 biasAndScale;\nuniform vec2 depthValues;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\nfloat depth=vDepthMetric;\n#ifdef ESM\ndepth=clamp(exp(-min(87.,biasAndScale.y*depth)),0.,1.);\n#endif\n#ifdef FLOAT\ngl_FragColor=vec4(depth,1.0,1.0,1.0);\n#else\ngl_FragColor=pack(depth);\n#endif\n}","depthBoxBlurPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nvoid main(void)\n{\nvec4 colorDepth=vec4(0.0);\nfor (int x=-OFFSET; x<=OFFSET; x++)\nfor (int y=-OFFSET; y<=OFFSET; y++)\ncolorDepth+=texture2D(textureSampler,vUV+vec2(x,y)/screenSize);\ngl_FragColor=(colorDepth/float((OFFSET*2+1)*(OFFSET*2+1)));\n}","proceduralVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vPosition;\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvPosition=position;\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","depthVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nuniform vec2 depthValues;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvarying float vDepthMetric;\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y));\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","depthPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nvarying float vDepthMetric;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(vDepthMetric,vDepthMetric*vDepthMetric,0.0,1.0);\n}","ssaoPixelShader":"\nuniform sampler2D textureSampler;\nvarying vec2 vUV;\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float radius;\nuniform float area;\nuniform float fallOff;\nuniform float base;\nvec3 normalFromDepth(float depth,vec2 coords)\n{\nvec2 offset1=vec2(0.0,radius);\nvec2 offset2=vec2(radius,0.0);\nfloat depth1=texture2D(textureSampler,coords+offset1).r;\nfloat depth2=texture2D(textureSampler,coords+offset2).r;\nvec3 p1=vec3(offset1,depth1-depth);\nvec3 p2=vec3(offset2,depth2-depth);\nvec3 normal=cross(p1,p2);\nnormal.z=-normal.z;\nreturn normalize(normal);\n}\nvoid main()\n{\nvec3 random=normalize(texture2D(randomSampler,vUV*randTextureTiles).rgb);\nfloat depth=texture2D(textureSampler,vUV).r;\nvec3 position=vec3(vUV,depth);\nvec3 normal=normalFromDepth(depth,vUV);\nfloat radiusDepth=radius/depth;\nfloat occlusion=0.0;\nvec3 ray;\nvec3 hemiRay;\nfloat occlusionDepth;\nfloat difference;\nfor (int i=0; i<SAMPLES; i++)\n{\nray=radiusDepth*reflect(sampleSphere[i],random);\nhemiRay=position+sign(dot(ray,normal))*ray;\nocclusionDepth=texture2D(textureSampler,clamp(hemiRay.xy,vec2(0.001,0.001),vec2(0.999,0.999))).r;\ndifference=depth-occlusionDepth;\nocclusion+=step(fallOff,difference)*(1.0-smoothstep(fallOff,area,difference));\n}\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor.r=result;\ngl_FragColor.g=result;\ngl_FragColor.b=result;\ngl_FragColor.a=1.0;\n}\n#endif\n","ssao2PixelShader":"\nprecision highp float;\nuniform sampler2D textureSampler;\nuniform float near;\nuniform float far;\nuniform float radius;\nvarying vec2 vUV;\nfloat perspectiveDepthToViewZ( const in float invClipZ,const in float near,const in float far ) {\nreturn ( near*far )/( ( far-near )*invClipZ-far );\n}\nfloat viewZToPerspectiveDepth( const in float viewZ,const in float near,const in float far ) {\nreturn ( near*far/viewZ+far)/( far-near );\n}\nfloat viewZToOrthographicDepth( const in float viewZ,const in float near,const in float far ) {\nreturn ( viewZ+near )/( near-far );\n}\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform sampler2D normalSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float base;\nuniform float xViewport;\nuniform float yViewport;\nuniform float maxZ;\nuniform float minZAspect;\nuniform vec2 texelSize;\nuniform mat4 projection;\nvoid main()\n{\nvec3 random=texture2D(randomSampler,vUV*randTextureTiles).rgb;\nfloat depth=texture2D(textureSampler,vUV).r;\nfloat depthSign=depth/abs(depth);\ndepth=depth*depthSign;\nvec3 normal=texture2D(normalSampler,vUV).rgb; \nfloat occlusion=0.0;\nfloat correctedRadius=min(radius,minZAspect*depth/near);\nvec3 vViewRay=vec3((vUV.x*2.0-1.0)*xViewport,(vUV.y*2.0-1.0)*yViewport,depthSign);\nvec3 origin=vViewRay*depth;\nvec3 rvec=random*2.0-1.0;\nrvec.z=0.0;\nvec3 tangent=normalize(rvec-normal*dot(rvec,normal));\nvec3 bitangent=cross(normal,tangent);\nmat3 tbn=mat3(tangent,bitangent,normal);\nfloat difference;\nif (depth>maxZ) {\ngl_FragColor=vec4(1.0,1.0,1.0,1.0);\nreturn;\n}\nfor (int i=0; i<SAMPLES; ++i) {\n\nvec3 samplePosition=tbn*sampleSphere[i];\nsamplePosition=samplePosition*correctedRadius+origin;\n\nvec4 offset=vec4(samplePosition,1.0);\noffset=projection*offset;\noffset.xyz/=offset.w;\noffset.xy=offset.xy*0.5+0.5;\nif (offset.x<0.0 || offset.y<0.0 || offset.x>1.0 || offset.y>1.0) {\ncontinue;\n}\n\nfloat sampleDepth=abs(texture2D(textureSampler,offset.xy).r);\n\nfloat rangeCheck=abs(depth-sampleDepth)<correctedRadius ? 1.0 : 0.0;\ndifference=depthSign*samplePosition.z-sampleDepth;\n\nocclusion+=(difference>=1e-5 ? 1.0 : 0.0)*rangeCheck;\n}\n\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor=vec4(vec3(result),1.0);\n}\n#endif\n#ifdef BILATERAL_BLUR\nuniform sampler2D depthSampler;\nuniform float outSize;\nuniform float samplerOffsets[SAMPLES];\nvec4 blur9(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.3846153846)*direction;\nvec2 off2=vec2(3.2307692308)*direction;\ncolor+=texture2D(image,uv)*0.2270270270;\ncolor+=texture2D(image,uv+(off1/resolution))*0.3162162162;\ncolor+=texture2D(image,uv-(off1/resolution))*0.3162162162;\ncolor+=texture2D(image,uv+(off2/resolution))*0.0702702703;\ncolor+=texture2D(image,uv-(off2/resolution))*0.0702702703;\nreturn color;\n}\nvec4 blur13(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.411764705882353)*direction;\nvec2 off2=vec2(3.2941176470588234)*direction;\nvec2 off3=vec2(5.176470588235294)*direction;\ncolor+=texture2D(image,uv)*0.1964825501511404;\ncolor+=texture2D(image,uv+(off1/resolution))*0.2969069646728344;\ncolor+=texture2D(image,uv-(off1/resolution))*0.2969069646728344;\ncolor+=texture2D(image,uv+(off2/resolution))*0.09447039785044732;\ncolor+=texture2D(image,uv-(off2/resolution))*0.09447039785044732;\ncolor+=texture2D(image,uv+(off3/resolution))*0.010381362401148057;\ncolor+=texture2D(image,uv-(off3/resolution))*0.010381362401148057;\nreturn color;\n}\nvec4 blur13Bilateral(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.411764705882353)*direction;\nvec2 off2=vec2(3.2941176470588234)*direction;\nvec2 off3=vec2(5.176470588235294)*direction;\nfloat compareDepth=abs(texture2D(depthSampler,uv).r);\nfloat sampleDepth;\nfloat weight;\nfloat weightSum=30.0;\ncolor+=texture2D(image,uv)*30.0;\nsampleDepth=abs(texture2D(depthSampler,uv+(off1/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off1/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off1/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off1/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv+(off2/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off2/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off2/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off2/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv+(off3/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off3/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off3/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off3/resolution))*weight;\nreturn color/weightSum;\n}\nvoid main()\n{\n#if EXPENSIVE\nfloat compareDepth=abs(texture2D(depthSampler,vUV).r);\nfloat texelsize=1.0/outSize;\nfloat result=0.0;\nfloat weightSum=0.0;\nfor (int i=0; i<SAMPLES; ++i)\n{\n#ifdef BILATERAL_BLUR_H\nvec2 direction=vec2(1.0,0.0);\nvec2 sampleOffset=vec2(texelsize*samplerOffsets[i],0.0);\n#else\nvec2 direction=vec2(0.0,1.0);\nvec2 sampleOffset=vec2(0.0,texelsize*samplerOffsets[i]);\n#endif\nvec2 samplePos=vUV+sampleOffset;\nfloat sampleDepth=abs(texture2D(depthSampler,samplePos).r);\nfloat weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30000.0);\nresult+=texture2D(textureSampler,samplePos).r*weight;\nweightSum+=weight;\n}\nresult/=weightSum;\ngl_FragColor.rgb=vec3(result);\ngl_FragColor.a=1.0;\n#else\nvec4 color;\n#ifdef BILATERAL_BLUR_H\nvec2 direction=vec2(1.0,0.0);\ncolor=blur13Bilateral(textureSampler,vUV,outSize,direction);\n#else\nvec2 direction=vec2(0.0,1.0);\ncolor=blur13Bilateral(textureSampler,vUV,outSize,direction);\n#endif\ngl_FragColor.rgb=vec3(color.r);\ngl_FragColor.a=1.0;\n#endif\n}\n#endif\n","ssaoCombinePixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D originalColor;\nvarying vec2 vUV;\nvoid main(void) {\nvec4 ssaoColor=texture2D(textureSampler,vUV);\nvec4 sceneColor=texture2D(originalColor,vUV);\ngl_FragColor=sceneColor*ssaoColor;\n}\n","chromaticAberrationPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float chromatic_aberration;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\nvoid main(void)\n{\nvec2 centered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);\nfloat radius2=centered_screen_pos.x*centered_screen_pos.x\n+centered_screen_pos.y*centered_screen_pos.y;\nfloat radius=sqrt(radius2);\nvec4 original=texture2D(textureSampler,vUV);\nif (chromatic_aberration>0.0) {\n\nvec3 ref_indices=vec3(-0.3,0.0,0.3);\nfloat ref_shiftX=chromatic_aberration*radius*17.0/screen_width;\nfloat ref_shiftY=chromatic_aberration*radius*17.0/screen_height;\n\nvec2 ref_coords_r=vec2(vUV.x+ref_indices.r*ref_shiftX,vUV.y+ref_indices.r*ref_shiftY*0.5);\nvec2 ref_coords_g=vec2(vUV.x+ref_indices.g*ref_shiftX,vUV.y+ref_indices.g*ref_shiftY*0.5);\nvec2 ref_coords_b=vec2(vUV.x+ref_indices.b*ref_shiftX,vUV.y+ref_indices.b*ref_shiftY*0.5);\noriginal.r=texture2D(textureSampler,ref_coords_r).r;\noriginal.g=texture2D(textureSampler,ref_coords_g).g;\noriginal.b=texture2D(textureSampler,ref_coords_b).b;\n}\ngl_FragColor=original;\n}","lensHighlightsPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float gain;\nuniform float threshold;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\n\nvec4 highlightColor(vec4 color) {\nvec4 highlight=color;\nfloat luminance=dot(highlight.rgb,vec3(0.2125,0.7154,0.0721));\nfloat lum_threshold;\nif (threshold>1.0) { lum_threshold=0.94+0.01*threshold; }\nelse { lum_threshold=0.5+0.44*threshold; }\nluminance=clamp((luminance-lum_threshold)*(1.0/(1.0-lum_threshold)),0.0,1.0);\nhighlight*=luminance*gain;\nhighlight.a=1.0;\nreturn highlight;\n}\nvoid main(void)\n{\nvec4 original=texture2D(textureSampler,vUV);\n\nif (gain == -1.0) {\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\nreturn;\n}\nfloat w=2.0/screen_width;\nfloat h=2.0/screen_height;\nfloat weight=1.0;\n\nvec4 blurred=vec4(0.0,0.0,0.0,0.0);\n#ifdef PENTAGON\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.84*w,0.43*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.48*w,-1.29*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.61*w,1.51*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.55*w,-0.74*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.71*w,-0.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.94*w,1.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.40*w,-1.87*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.62*w,1.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.09*w,0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.46*w,-1.71*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.08*w,2.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.85*w,-1.89*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.89*w,0.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.29*w,1.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.40*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.54*w,2.26*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.60*w,-0.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.31*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.83*w,2.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.12*w,-2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.60*w,1.11*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.99*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.50*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.85*w,3.33*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.94*w,-1.92*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.27*w,-0.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.95*w,2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.23*w,-3.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.17*w,2.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.97*w,-0.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.25*w,-2.00*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.31*w,3.08*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.94*w,-2.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.37*w,0.64*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.13*w,1.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.03*w,-3.65*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.60*w,3.17*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.14*w,-1.19*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.00*w,-1.19*h)));\n#else\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.85*w,0.36*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.52*w,-1.14*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.46*w,1.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.46*w,-0.83*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.79*w,-0.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.11*w,1.62*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.29*w,-2.07*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.69*w,1.39*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.28*w,0.12*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.65*w,-1.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.08*w,2.44*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.63*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.55*w,0.31*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.13*w,1.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.56*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.38*w,2.34*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.64*w,-0.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.53*w,-1.21*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.06*w,2.63*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.00*w,-2.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.59*w,1.32*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.78*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.57*w,-2.50*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.54*w,2.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.39*w,-1.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,-0.28*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.04*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.02*w,-3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.09*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.07*w,-0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.44*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.52*w,3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.68*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,0.79*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.76*w,1.46*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.05*w,-2.94*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.21*w,2.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.84*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.98*w,-0.96*h)));\n#endif\nblurred/=39.0;\ngl_FragColor=blurred;\n\n}","depthOfFieldPixelShader":"\n\n\n\n\nuniform sampler2D textureSampler;\nuniform sampler2D highlightsSampler;\nuniform sampler2D depthSampler;\nuniform sampler2D grainSampler;\n\nuniform float grain_amount;\nuniform bool blur_noise;\nuniform float screen_width;\nuniform float screen_height;\nuniform float distortion;\nuniform bool dof_enabled;\n\nuniform float screen_distance; \nuniform float aperture;\nuniform float darken;\nuniform float edge_blur;\nuniform bool highlights;\n\nuniform float near;\nuniform float far;\n\nvarying vec2 vUV;\n\n#define PI 3.14159265\n#define TWOPI 6.28318530\n#define inverse_focal_length 0.1 \n\nvec2 centered_screen_pos;\nvec2 distorted_coords;\nfloat radius2;\nfloat radius;\n\nvec2 rand(vec2 co)\n{\nfloat noise1=(fract(sin(dot(co,vec2(12.9898,78.233)))*43758.5453));\nfloat noise2=(fract(sin(dot(co,vec2(12.9898,78.233)*2.0))*43758.5453));\nreturn clamp(vec2(noise1,noise2),0.0,1.0);\n}\n\nvec2 getDistortedCoords(vec2 coords) {\nif (distortion == 0.0) { return coords; }\nvec2 direction=1.0*normalize(centered_screen_pos);\nvec2 dist_coords=vec2(0.5,0.5);\ndist_coords.x=0.5+direction.x*radius2*1.0;\ndist_coords.y=0.5+direction.y*radius2*1.0;\nfloat dist_amount=clamp(distortion*0.23,0.0,1.0);\ndist_coords=mix(coords,dist_coords,dist_amount);\nreturn dist_coords;\n}\n\nfloat sampleScreen(inout vec4 color,const in vec2 offset,const in float weight) {\n\nvec2 coords=distorted_coords;\nfloat angle=rand(coords*100.0).x*TWOPI;\ncoords+=vec2(offset.x*cos(angle)-offset.y*sin(angle),offset.x*sin(angle)+offset.y*cos(angle));\ncolor+=texture2D(textureSampler,coords)*weight;\nreturn weight;\n}\n\nfloat getBlurLevel(float size) {\nreturn min(3.0,ceil(size/1.0));\n}\n\nvec4 getBlurColor(float size) {\nvec4 col=texture2D(textureSampler,distorted_coords);\nif (size == 0.0) { return col; }\n\n\nfloat blur_level=getBlurLevel(size);\nfloat w=(size/screen_width);\nfloat h=(size/screen_height);\nfloat total_weight=1.0;\nvec2 sample_coords;\ntotal_weight+=sampleScreen(col,vec2(-0.50*w,0.24*h),0.93);\ntotal_weight+=sampleScreen(col,vec2(0.30*w,-0.75*h),0.90);\ntotal_weight+=sampleScreen(col,vec2(0.36*w,0.96*h),0.87);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,-0.55*h),0.85);\ntotal_weight+=sampleScreen(col,vec2(1.33*w,-0.37*h),0.83);\ntotal_weight+=sampleScreen(col,vec2(-0.82*w,1.31*h),0.80);\ntotal_weight+=sampleScreen(col,vec2(-0.31*w,-1.67*h),0.78);\ntotal_weight+=sampleScreen(col,vec2(1.47*w,1.11*h),0.76);\ntotal_weight+=sampleScreen(col,vec2(-1.97*w,0.19*h),0.74);\ntotal_weight+=sampleScreen(col,vec2(1.42*w,-1.57*h),0.72);\nif (blur_level>1.0) {\ntotal_weight+=sampleScreen(col,vec2(0.01*w,2.25*h),0.70);\ntotal_weight+=sampleScreen(col,vec2(-1.62*w,-1.74*h),0.67);\ntotal_weight+=sampleScreen(col,vec2(2.49*w,0.20*h),0.65);\ntotal_weight+=sampleScreen(col,vec2(-2.07*w,1.61*h),0.63);\ntotal_weight+=sampleScreen(col,vec2(0.46*w,-2.70*h),0.61);\ntotal_weight+=sampleScreen(col,vec2(1.55*w,2.40*h),0.59);\ntotal_weight+=sampleScreen(col,vec2(-2.88*w,-0.75*h),0.56);\ntotal_weight+=sampleScreen(col,vec2(2.73*w,-1.44*h),0.54);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,3.02*h),0.52);\ntotal_weight+=sampleScreen(col,vec2(-1.28*w,-3.05*h),0.49);\n}\nif (blur_level>2.0) {\ntotal_weight+=sampleScreen(col,vec2(3.11*w,1.43*h),0.46);\ntotal_weight+=sampleScreen(col,vec2(-3.36*w,1.08*h),0.44);\ntotal_weight+=sampleScreen(col,vec2(1.80*w,-3.16*h),0.41);\ntotal_weight+=sampleScreen(col,vec2(0.83*w,3.65*h),0.38);\ntotal_weight+=sampleScreen(col,vec2(-3.16*w,-2.19*h),0.34);\ntotal_weight+=sampleScreen(col,vec2(3.92*w,-0.53*h),0.31);\ntotal_weight+=sampleScreen(col,vec2(-2.59*w,3.12*h),0.26);\ntotal_weight+=sampleScreen(col,vec2(-0.20*w,-4.15*h),0.22);\ntotal_weight+=sampleScreen(col,vec2(3.02*w,3.00*h),0.15);\n}\ncol/=total_weight; \n\nif (darken>0.0) {\ncol.rgb*=clamp(0.3,1.0,1.05-size*0.5*darken);\n}\n\n\n\n\nreturn col;\n}\nvoid main(void)\n{\n\ncentered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);\nradius2=centered_screen_pos.x*centered_screen_pos.x+centered_screen_pos.y*centered_screen_pos.y;\nradius=sqrt(radius2);\ndistorted_coords=getDistortedCoords(vUV); \nvec2 texels_coords=vec2(vUV.x*screen_width,vUV.y*screen_height); \nfloat depth=texture2D(depthSampler,distorted_coords).r; \nfloat distance=near+(far-near)*depth; \nvec4 color=texture2D(textureSampler,vUV); \n\n\nfloat coc=abs(aperture*(screen_distance*(inverse_focal_length-1.0/distance)-1.0));\n\nif (dof_enabled == false || coc<0.07) { coc=0.0; }\n\nfloat edge_blur_amount=0.0;\nif (edge_blur>0.0) {\nedge_blur_amount=clamp((radius*2.0-1.0+0.15*edge_blur)*1.5,0.0,1.0)*1.3;\n}\n\nfloat blur_amount=max(edge_blur_amount,coc);\n\nif (blur_amount == 0.0) {\ngl_FragColor=texture2D(textureSampler,distorted_coords);\n}\nelse {\n\ngl_FragColor=getBlurColor(blur_amount*1.7);\n\nif (highlights) {\ngl_FragColor.rgb+=clamp(coc,0.0,1.0)*texture2D(highlightsSampler,distorted_coords).rgb;\n}\nif (blur_noise) {\n\nvec2 noise=rand(distorted_coords)*0.01*blur_amount;\nvec2 blurred_coord=vec2(distorted_coords.x+noise.x,distorted_coords.y+noise.y);\ngl_FragColor=0.04*texture2D(textureSampler,blurred_coord)+0.96*gl_FragColor;\n}\n}\n\nif (grain_amount>0.0) {\nvec4 grain_color=texture2D(grainSampler,texels_coords*0.003);\ngl_FragColor.rgb+=(-0.5+grain_color.rgb)*0.30*grain_amount;\n}\n}\n","standardPixelShader":"uniform sampler2D textureSampler;\nvarying vec2 vUV;\n#if defined(PASS_POST_PROCESS)\nvoid main(void)\n{\nvec4 color=texture2D(textureSampler,vUV);\ngl_FragColor=color;\n}\n#endif\n#if defined(DOWN_SAMPLE_X4)\nuniform vec2 dsOffsets[16];\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+dsOffsets[0]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[1]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[2]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[3]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[4]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[5]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[6]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[7]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[8]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[9]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[10]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[11]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[12]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[13]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[14]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[15]);\naverage/=16.0;\ngl_FragColor=average;\n}\n#endif\n#if defined(BRIGHT_PASS)\nuniform vec2 dsOffsets[4];\nuniform float brightThreshold;\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+vec2(dsOffsets[0].x,dsOffsets[0].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[1].x,dsOffsets[1].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[2].x,dsOffsets[2].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[3].x,dsOffsets[3].y));\naverage*=0.25;\nfloat luminance=length(average.rgb);\nif (luminance<brightThreshold) {\naverage=vec4(0.0,0.0,0.0,1.0);\n}\ngl_FragColor=average;\n}\n#endif\n#if defined(TEXTURE_ADDER)\nuniform sampler2D otherSampler;\nuniform sampler2D lensSampler;\nuniform float exposure;\nvoid main(void)\n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\ncolour*=exposure;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\ncolour+=colour*texture2D(lensSampler,vUV).rgb;\nvec4 finalColor=vec4(colour.rgb,1.0)+texture2D(otherSampler,vUV);\ngl_FragColor=finalColor;\n}\n#endif\n#if defined(VLS)\n#define PI 3.1415926535897932384626433832795\nuniform mat4 shadowViewProjection;\nuniform mat4 lightWorld;\nuniform vec3 cameraPosition;\nuniform vec3 sunDirection;\nuniform vec3 sunColor;\nuniform vec2 depthValues;\nuniform float scatteringCoefficient;\nuniform float scatteringPower;\nuniform sampler2D shadowMapSampler;\nuniform sampler2D positionSampler;\nfloat computeScattering(float lightDotView)\n{\nfloat result=1.0-scatteringCoefficient*scatteringCoefficient;\nresult/=(4.0*PI*pow(1.0+scatteringCoefficient*scatteringCoefficient-(2.0*scatteringCoefficient)*lightDotView,1.5));\nreturn result;\n}\nvoid main(void)\n{\n\nvec3 worldPos=texture2D(positionSampler,vUV).rgb;\nvec3 startPosition=cameraPosition;\nvec3 rayVector=worldPos-startPosition;\nfloat rayLength=length(rayVector);\nvec3 rayDirection=rayVector/rayLength;\nfloat stepLength=rayLength/NB_STEPS;\nvec3 stepL=rayDirection*stepLength;\nvec3 currentPosition=startPosition;\nvec3 accumFog=vec3(0.0);\nfor (int i=0; i<int(NB_STEPS); i++)\n{\nvec4 worldInShadowCameraSpace=shadowViewProjection*vec4(currentPosition,1.0);\nfloat depthMetric=(worldInShadowCameraSpace.z+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depthMetric,0.0,1.0);\nworldInShadowCameraSpace.xyz/=worldInShadowCameraSpace.w;\nworldInShadowCameraSpace.xyz=0.5*worldInShadowCameraSpace.xyz+vec3(0.5);\nfloat shadowMapValue=texture2D(shadowMapSampler,worldInShadowCameraSpace.xy).r;\nif (shadowMapValue>shadowPixelDepth)\naccumFog+=sunColor*computeScattering(dot(rayDirection,sunDirection));\ncurrentPosition+=stepL;\n}\naccumFog/=NB_STEPS;\nvec3 color=accumFog*scatteringPower;\ngl_FragColor=vec4(color*exp(color) ,1.0);\n}\n#endif\n#if defined(VLSMERGE)\nuniform sampler2D originalSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(originalSampler,vUV)+texture2D(textureSampler,vUV);\n}\n#endif\n#if defined(LUMINANCE)\nuniform vec2 lumOffsets[4];\nvoid main()\n{\nfloat average=0.0;\nvec4 color=vec4(0.0);\nfloat maximum=-1e20;\nvec3 weight=vec3(0.299,0.587,0.114);\nfor (int i=0; i<4; i++)\n{\ncolor=texture2D(textureSampler,vUV+ lumOffsets[i]);\n\nfloat GreyValue=dot(color.rgb,vec3(0.33,0.33,0.33));\n\n#ifdef WEIGHTED_AVERAGE\nfloat GreyValue=dot(color.rgb,weight);\n#endif\n#ifdef BRIGHTNESS\nfloat GreyValue=max(color.r,max(color.g,color.b));\n#endif\n#ifdef HSL_COMPONENT\nfloat GreyValue=0.5*(max(color.r,max(color.g,color.b))+min(color.r,min(color.g,color.b)));\n#endif\n#ifdef MAGNITUDE\nfloat GreyValue=length(color.rgb);\n#endif\nmaximum=max(maximum,GreyValue);\naverage+=(0.25*log(1e-5+GreyValue));\n}\naverage=exp(average);\ngl_FragColor=vec4(average,maximum,0.0,1.0);\n}\n#endif\n#if defined(LUMINANCE_DOWN_SAMPLE)\nuniform vec2 dsOffsets[9];\nuniform float halfDestPixelSize;\n#ifdef FINAL_DOWN_SAMPLER\nvec4 pack(float value) {\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(value*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvoid main()\n{\nvec4 color=vec4(0.0);\nfloat average=0.0;\nfor (int i=0; i<9; i++)\n{\ncolor=texture2D(textureSampler,vUV+vec2(halfDestPixelSize,halfDestPixelSize)+dsOffsets[i]);\naverage+=color.r;\n}\naverage/=9.0;\n#ifdef FINAL_DOWN_SAMPLER\ngl_FragColor=pack(average);\n#else\ngl_FragColor=vec4(average,average,0.0,1.0);\n#endif\n}\n#endif\n#if defined(HDR)\nuniform sampler2D textureAdderSampler;\nuniform float averageLuminance;\nvoid main()\n{\nvec4 color=texture2D(textureAdderSampler,vUV);\nvec4 adjustedColor=color/averageLuminance;\ncolor=adjustedColor;\ncolor.a=1.0;\ngl_FragColor=color;\n}\n#endif\n#if defined(LENS_FLARE)\n#define GHOSTS 3\nuniform sampler2D lensColorSampler;\nuniform float strength;\nuniform float ghostDispersal;\nuniform float haloWidth;\nuniform vec2 resolution;\nuniform float distortionStrength;\nfloat hash(vec2 p)\n{\nfloat h=dot(p,vec2(127.1,311.7));\nreturn -1.0+2.0*fract(sin(h)*43758.5453123);\n}\nfloat noise(in vec2 p)\n{\nvec2 i=floor(p);\nvec2 f=fract(p);\nvec2 u=f*f*(3.0-2.0*f);\nreturn mix(mix(hash(i+vec2(0.0,0.0)),\nhash(i+vec2(1.0,0.0)),u.x),\nmix(hash(i+vec2(0.0,1.0)),\nhash(i+vec2(1.0,1.0)),u.x),u.y);\n}\nfloat fbm(vec2 p)\n{\nfloat f=0.0;\nf+=0.5000*noise(p); p*=2.02;\nf+=0.2500*noise(p); p*=2.03;\nf+=0.1250*noise(p); p*=2.01;\nf+=0.0625*noise(p); p*=2.04;\nf/=0.9375;\nreturn f;\n}\nvec3 pattern(vec2 uv)\n{\nvec2 p=-1.0+2.0*uv;\nfloat p2=dot(p,p);\nfloat f=fbm(vec2(15.0*p2))/2.0;\nfloat r=0.2+0.6*sin(12.5*length(uv-vec2(0.5)));\nfloat g=0.2+0.6*sin(20.5*length(uv-vec2(0.5)));\nfloat b=0.2+0.6*sin(17.2*length(uv-vec2(0.5)));\nreturn (1.0-f)*vec3(r,g,b);\n}\nfloat luminance(vec3 color)\n{\nreturn dot(color.rgb,vec3(0.2126,0.7152,0.0722));\n}\nvec4 textureDistorted(sampler2D tex,vec2 texcoord,vec2 direction,vec3 distortion)\n{\nreturn vec4(\ntexture2D(tex,texcoord+direction*distortion.r).r,\ntexture2D(tex,texcoord+direction*distortion.g).g,\ntexture2D(tex,texcoord+direction*distortion.b).b,\n1.0\n);\n}\nvoid main(void)\n{\nvec2 uv=-vUV+vec2(1.0);\nvec2 ghostDir=(vec2(0.5)-uv)*ghostDispersal;\nvec2 texelSize=1.0/resolution;\nvec3 distortion=vec3(-texelSize.x*distortionStrength,0.0,texelSize.x*distortionStrength);\nvec4 result=vec4(0.0);\nfloat ghostIndice=1.0;\nfor (int i=0; i<GHOSTS; ++i)\n{\nvec2 offset=fract(uv+ghostDir*ghostIndice);\nfloat weight=length(vec2(0.5)-offset)/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,offset,normalize(ghostDir),distortion)*weight*strength;\nghostIndice+=1.0;\n}\nvec2 haloVec=normalize(ghostDir)*haloWidth;\nfloat weight=length(vec2(0.5)-fract(uv+haloVec))/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,fract(uv+haloVec),normalize(ghostDir),distortion)*weight*strength;\nresult*=texture2D(lensColorSampler,vec2(length(vec2(0.5)-uv)/length(vec2(0.5))));\ngl_FragColor=result;\n}\n#endif\n#if defined(LENS_FLARE_COMPOSE)\nuniform sampler2D otherSampler;\nuniform sampler2D lensDirtSampler;\nuniform sampler2D lensStarSampler;\nuniform mat4 lensStarMatrix;\nvoid main(void)\n{\nvec2 lensFlareCoords=(lensStarMatrix*vec4(vUV,1.0,1.0)).xy;\nvec4 lensMod=texture2D(lensDirtSampler,vUV);\nlensMod+=texture2D(lensStarSampler,vUV);\nvec4 result=texture2D(textureSampler,vUV)*lensMod;\ngl_FragColor=texture2D(otherSampler,vUV)+result;\n}\n#endif\n#if defined(DEPTH_OF_FIELD)\nuniform sampler2D otherSampler;\nuniform sampler2D depthSampler;\nuniform float distance;\nvoid main(void)\n{\nvec4 sharp=texture2D(otherSampler,vUV);\nvec4 blur=texture2D(textureSampler,vUV);\nfloat dist=clamp(texture2D(depthSampler,vUV).r*distance,0.0,1.0);\nfloat factor=0.0;\nif (dist<0.05)\nfactor=1.0;\nelse if (dist<0.1)\nfactor=20.0*(0.1-dist);\nelse if (dist<0.5)\nfactor=0.0;\nelse\nfactor=2.0*(dist-0.5);\nfactor=clamp(factor,0.0,0.90);\ngl_FragColor=mix(sharp,blur,factor);\n}\n#endif\n#if defined(MOTION_BLUR)\nuniform mat4 inverseViewProjection;\nuniform mat4 prevViewProjection;\nuniform vec2 screenSize;\nuniform float motionScale;\nuniform float motionStrength;\nuniform sampler2D depthSampler;\nvoid main(void)\n{\nvec2 texelSize=1.0/screenSize;\nfloat depth=texture2D(depthSampler,vUV).r;\nvec4 cpos=vec4(vUV*2.0-1.0,depth,1.0);\ncpos=cpos*inverseViewProjection;\nvec4 ppos=cpos*prevViewProjection;\nppos.xyz/=ppos.w;\nppos.xy=ppos.xy*0.5+0.5;\nvec2 velocity=(ppos.xy-vUV)*motionScale*motionStrength;\nfloat speed=length(velocity/texelSize);\nint nSamples=int(clamp(speed,1.0,MAX_MOTION_SAMPLES));\nvec4 result=texture2D(textureSampler,vUV);\nfor (int i=1; i<int(MAX_MOTION_SAMPLES); ++i) {\nif (i>=nSamples)\nbreak;\nvec2 offset1=vUV+velocity*(float(i)/float(nSamples-1)-0.5);\nresult+=texture2D(textureSampler,offset1);\n}\ngl_FragColor=result/float(nSamples);\n}\n#endif\n","fxaaVertexShader":"\nattribute vec2 position;\nuniform vec2 texelSize;\n\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd);\nsampleCoordS=vUV+vec2( 0.0,1.0)*texelSize;\nsampleCoordE=vUV+vec2( 1.0,0.0)*texelSize;\nsampleCoordN=vUV+vec2( 0.0,-1.0)*texelSize;\nsampleCoordW=vUV+vec2(-1.0,0.0)*texelSize;\nsampleCoordNW=vUV+vec2(-1.0,-1.0)*texelSize;\nsampleCoordSE=vUV+vec2( 1.0,1.0)*texelSize;\nsampleCoordNE=vUV+vec2( 1.0,-1.0)*texelSize;\nsampleCoordSW=vUV+vec2(-1.0,1.0)*texelSize;\ngl_Position=vec4(position,0.0,1.0);\n}","fxaaPixelShader":"uniform sampler2D textureSampler;\nuniform vec2 texelSize;\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst float fxaaQualitySubpix=1.0;\nconst float fxaaQualityEdgeThreshold=0.166;\nconst float fxaaQualityEdgeThresholdMin=0.0833;\nconst vec3 kLumaCoefficients=vec3(0.2126,0.7152,0.0722);\n#define FxaaLuma(rgba) dot(rgba.rgb,kLumaCoefficients)\nvoid main(){\nvec2 posM;\nposM.x=vUV.x;\nposM.y=vUV.y;\nvec4 rgbyM=texture2D(textureSampler,vUV,0.0);\nfloat lumaM=FxaaLuma(rgbyM);\nfloat lumaS=FxaaLuma(texture2D(textureSampler,sampleCoordS,0.0));\nfloat lumaE=FxaaLuma(texture2D(textureSampler,sampleCoordE,0.0));\nfloat lumaN=FxaaLuma(texture2D(textureSampler,sampleCoordN,0.0));\nfloat lumaW=FxaaLuma(texture2D(textureSampler,sampleCoordW,0.0));\nfloat maxSM=max(lumaS,lumaM);\nfloat minSM=min(lumaS,lumaM);\nfloat maxESM=max(lumaE,maxSM);\nfloat minESM=min(lumaE,minSM);\nfloat maxWN=max(lumaN,lumaW);\nfloat minWN=min(lumaN,lumaW);\nfloat rangeMax=max(maxWN,maxESM);\nfloat rangeMin=min(minWN,minESM);\nfloat rangeMaxScaled=rangeMax*fxaaQualityEdgeThreshold;\nfloat range=rangeMax-rangeMin;\nfloat rangeMaxClamped=max(fxaaQualityEdgeThresholdMin,rangeMaxScaled);\nif(range<rangeMaxClamped) \n{\ngl_FragColor=rgbyM;\nreturn;\n}\nfloat lumaNW=FxaaLuma(texture2D(textureSampler,sampleCoordNW,0.0));\nfloat lumaSE=FxaaLuma(texture2D(textureSampler,sampleCoordSE,0.0));\nfloat lumaNE=FxaaLuma(texture2D(textureSampler,sampleCoordNE,0.0));\nfloat lumaSW=FxaaLuma(texture2D(textureSampler,sampleCoordSW,0.0));\nfloat lumaNS=lumaN+lumaS;\nfloat lumaWE=lumaW+lumaE;\nfloat subpixRcpRange=1.0/range;\nfloat subpixNSWE=lumaNS+lumaWE;\nfloat edgeHorz1=(-2.0*lumaM)+lumaNS;\nfloat edgeVert1=(-2.0*lumaM)+lumaWE;\nfloat lumaNESE=lumaNE+lumaSE;\nfloat lumaNWNE=lumaNW+lumaNE;\nfloat edgeHorz2=(-2.0*lumaE)+lumaNESE;\nfloat edgeVert2=(-2.0*lumaN)+lumaNWNE;\nfloat lumaNWSW=lumaNW+lumaSW;\nfloat lumaSWSE=lumaSW+lumaSE;\nfloat edgeHorz4=(abs(edgeHorz1)*2.0)+abs(edgeHorz2);\nfloat edgeVert4=(abs(edgeVert1)*2.0)+abs(edgeVert2);\nfloat edgeHorz3=(-2.0*lumaW)+lumaNWSW;\nfloat edgeVert3=(-2.0*lumaS)+lumaSWSE;\nfloat edgeHorz=abs(edgeHorz3)+edgeHorz4;\nfloat edgeVert=abs(edgeVert3)+edgeVert4;\nfloat subpixNWSWNESE=lumaNWSW+lumaNESE;\nfloat lengthSign=texelSize.x;\nbool horzSpan=edgeHorz>=edgeVert;\nfloat subpixA=subpixNSWE*2.0+subpixNWSWNESE;\nif (!horzSpan)\n{\nlumaN=lumaW;\n}\nif (!horzSpan) \n{\nlumaS=lumaE;\n}\nif (horzSpan) \n{\nlengthSign=texelSize.y;\n}\nfloat subpixB=(subpixA*(1.0/12.0))-lumaM;\nfloat gradientN=lumaN-lumaM;\nfloat gradientS=lumaS-lumaM;\nfloat lumaNN=lumaN+lumaM;\nfloat lumaSS=lumaS+lumaM;\nbool pairN=abs(gradientN)>=abs(gradientS);\nfloat gradient=max(abs(gradientN),abs(gradientS));\nif (pairN)\n{\nlengthSign=-lengthSign;\n}\nfloat subpixC=clamp(abs(subpixB)*subpixRcpRange,0.0,1.0);\nvec2 posB;\nposB.x=posM.x;\nposB.y=posM.y;\nvec2 offNP;\noffNP.x=(!horzSpan) ? 0.0 : texelSize.x;\noffNP.y=(horzSpan) ? 0.0 : texelSize.y;\nif (!horzSpan) \n{\nposB.x+=lengthSign*0.5;\n}\nif (horzSpan)\n{\nposB.y+=lengthSign*0.5;\n}\nvec2 posN;\nposN.x=posB.x-offNP.x*1.5;\nposN.y=posB.y-offNP.y*1.5;\nvec2 posP;\nposP.x=posB.x+offNP.x*1.5;\nposP.y=posB.y+offNP.y*1.5;\nfloat subpixD=((-2.0)*subpixC)+3.0;\nfloat lumaEndN=FxaaLuma(texture2D(textureSampler,posN,0.0));\nfloat subpixE=subpixC*subpixC;\nfloat lumaEndP=FxaaLuma(texture2D(textureSampler,posP,0.0));\nif (!pairN) \n{\nlumaNN=lumaSS;\n}\nfloat gradientScaled=gradient*1.0/4.0;\nfloat lumaMM=lumaM-lumaNN*0.5;\nfloat subpixF=subpixD*subpixE;\nbool lumaMLTZero=lumaMM<0.0;\nlumaEndN-=lumaNN*0.5;\nlumaEndP-=lumaNN*0.5;\nbool doneN=abs(lumaEndN)>=gradientScaled;\nbool doneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) \n{\nposN.x-=offNP.x*3.0;\n}\nif (!doneN) \n{\nposN.y-=offNP.y*3.0;\n}\nbool doneNP=(!doneN) || (!doneP);\nif (!doneP) \n{\nposP.x+=offNP.x*3.0;\n}\nif (!doneP)\n{\nposP.y+=offNP.y*3.0;\n}\nif (doneNP)\n{\nif (!doneN) lumaEndN=FxaaLuma(texture2D(textureSampler,posN.xy,0.0));\nif (!doneP) lumaEndP=FxaaLuma(texture2D(textureSampler,posP.xy,0.0));\nif (!doneN) lumaEndN=lumaEndN-lumaNN*0.5;\nif (!doneP) lumaEndP=lumaEndP-lumaNN*0.5;\ndoneN=abs(lumaEndN)>=gradientScaled;\ndoneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) posN.x-=offNP.x*12.0;\nif (!doneN) posN.y-=offNP.y*12.0;\ndoneNP=(!doneN) || (!doneP);\nif (!doneP) posP.x+=offNP.x*12.0;\nif (!doneP) posP.y+=offNP.y*12.0;\n}\nfloat dstN=posM.x-posN.x;\nfloat dstP=posP.x-posM.x;\nif (!horzSpan)\n{\ndstN=posM.y-posN.y;\n}\nif (!horzSpan) \n{\ndstP=posP.y-posM.y;\n}\nbool goodSpanN=(lumaEndN<0.0) != lumaMLTZero;\nfloat spanLength=(dstP+dstN);\nbool goodSpanP=(lumaEndP<0.0) != lumaMLTZero;\nfloat spanLengthRcp=1.0/spanLength;\nbool directionN=dstN<dstP;\nfloat dst=min(dstN,dstP);\nbool goodSpan=directionN ? goodSpanN : goodSpanP;\nfloat subpixG=subpixF*subpixF;\nfloat pixelOffset=(dst*(-spanLengthRcp))+0.5;\nfloat subpixH=subpixG*fxaaQualitySubpix;\nfloat pixelOffsetGood=goodSpan ? pixelOffset : 0.0;\nfloat pixelOffsetSubpix=max(pixelOffsetGood,subpixH);\nif (!horzSpan)\n{\nposM.x+=pixelOffsetSubpix*lengthSign;\n}\nif (horzSpan)\n{\nposM.y+=pixelOffsetSubpix*lengthSign;\n}\ngl_FragColor=texture2D(textureSampler,posM,0.0);\n}","geometryVertexShader":"precision highp float;\nprecision highp int;\n#include<bonesDeclaration>\n#include<instancesDeclaration>\nattribute vec3 position;\nattribute vec3 normal;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nvarying vec2 uv;\n#endif\n#ifdef UV2\nvarying vec2 uv2;\n#endif\n#endif\n\nuniform mat4 viewProjection;\nuniform mat4 view;\nvarying vec3 vNormalV;\nvarying vec4 vViewPos;\n#ifdef POSITION\nvarying vec3 vPosition;\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\nvec4 pos=vec4(finalWorld*vec4(position,1.0));\nvNormalV=normalize(vec3((view*finalWorld)*vec4(normal,0.0)));\nvViewPos=view*pos;\n#ifdef POSITION\nvPosition=pos.xyz/pos.w;\n#endif\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","geometryPixelShader":"#extension GL_EXT_draw_buffers : require\nprecision highp float;\nprecision highp int;\nvarying vec3 vNormalV;\nvarying vec4 vViewPos;\n#ifdef POSITION\nvarying vec3 vPosition;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef POSITION\n#include<mrtFragmentDeclaration>[3]\n#else\n#include<mrtFragmentDeclaration>[2]\n#endif\nvoid main() {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragData[0]=vec4(vViewPos.z/vViewPos.w,0.0,0.0,1.0);\n\ngl_FragData[1]=vec4(normalize(vNormalV),1.0);\n\n#ifdef POSITION\ngl_FragData[2]=vec4(vPosition,1.0);\n#endif\n}","refractionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D refractionSampler;\n\nuniform vec3 baseColor;\nuniform float depth;\nuniform float colorLevel;\nvoid main() {\nfloat ref=1.0-texture2D(refractionSampler,vUV).r;\nvec2 uv=vUV-vec2(0.5);\nvec2 offset=uv*depth*ref;\nvec3 sourceColor=texture2D(textureSampler,vUV-offset).rgb;\ngl_FragColor=vec4(sourceColor+sourceColor*ref*colorLevel,1.0);\n}","blackAndWhitePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform float degree;\nvoid main(void) \n{\nvec3 color=texture2D(textureSampler,vUV).rgb;\nfloat luminance=dot(color,vec3(0.3,0.59,0.11)); \nvec3 blackAndWhite=vec3(luminance,luminance,luminance);\ngl_FragColor=vec4(color-((color-blackAndWhite)*degree),1.0);\n}","convolutionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 screenSize;\nuniform float kernel[9];\nvoid main(void)\n{\nvec2 onePixel=vec2(1.0,1.0)/screenSize;\nvec4 colorSum =\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,-1))*kernel[0] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,-1))*kernel[1] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,-1))*kernel[2] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0))*kernel[3] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,0))*kernel[4] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0))*kernel[5] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,1))*kernel[6] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1))*kernel[7] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,1))*kernel[8];\nfloat kernelWeight =\nkernel[0] +\nkernel[1] +\nkernel[2] +\nkernel[3] +\nkernel[4] +\nkernel[5] +\nkernel[6] +\nkernel[7] +\nkernel[8];\nif (kernelWeight<=0.0) {\nkernelWeight=1.0;\n}\ngl_FragColor=vec4((colorSum/kernelWeight).rgb,1);\n}","filterPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform mat4 kernelMatrix;\nvoid main(void)\n{\nvec3 baseColor=texture2D(textureSampler,vUV).rgb;\nvec3 updatedColor=(kernelMatrix*vec4(baseColor,1.0)).rgb;\ngl_FragColor=vec4(updatedColor,1.0);\n}","volumetricLightScatteringPixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D lightScatteringSampler;\nuniform float decay;\nuniform float exposure;\nuniform float weight;\nuniform float density;\nuniform vec2 meshPositionOnScreen;\nvarying vec2 vUV;\nvoid main(void) {\nvec2 tc=vUV;\nvec2 deltaTexCoord=(tc-meshPositionOnScreen.xy);\ndeltaTexCoord*=1.0/float(NUM_SAMPLES)*density;\nfloat illuminationDecay=1.0;\nvec4 color=texture2D(lightScatteringSampler,tc)*0.4;\nfor(int i=0; i<NUM_SAMPLES; i++) {\ntc-=deltaTexCoord;\nvec4 dataSample=texture2D(lightScatteringSampler,tc)*0.4;\ndataSample*=illuminationDecay*weight;\ncolor+=dataSample;\nilluminationDecay*=decay;\n}\nvec4 realColor=texture2D(textureSampler,vUV);\ngl_FragColor=((vec4((vec3(color.r,color.g,color.b)*exposure),1))+(realColor*(1.5-0.4)));\n}\n","volumetricLightScatteringPassPixelShader":"#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\n#endif\n#if defined(ALPHATEST)\nuniform sampler2D diffuseSampler;\n#endif\nvoid main(void)\n{\n#if defined(ALPHATEST)\nvec4 diffuseColor=texture2D(diffuseSampler,vUV);\nif (diffuseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\n}\n","colorCorrectionPixelShader":"\nuniform sampler2D textureSampler; \nuniform sampler2D colorTable; \n\nvarying vec2 vUV;\n\nconst float SLICE_COUNT=16.0; \n\nvec4 sampleAs3DTexture(sampler2D textureSampler,vec3 uv,float width) {\nfloat sliceSize=1.0/width; \nfloat slicePixelSize=sliceSize/width; \nfloat sliceInnerSize=slicePixelSize*(width-1.0); \nfloat zSlice0=min(floor(uv.z*width),width-1.0);\nfloat zSlice1=min(zSlice0+1.0,width-1.0);\nfloat xOffset=slicePixelSize*0.5+uv.x*sliceInnerSize;\nfloat s0=xOffset+(zSlice0*sliceSize);\nfloat s1=xOffset+(zSlice1*sliceSize);\nvec4 slice0Color=texture2D(textureSampler,vec2(s0,uv.y));\nvec4 slice1Color=texture2D(textureSampler,vec2(s1,uv.y));\nfloat zOffset=mod(uv.z*width,1.0);\nvec4 result=mix(slice0Color,slice1Color,zOffset);\nreturn result;\n}\nvoid main(void)\n{\nvec4 screen_color=texture2D(textureSampler,vUV);\ngl_FragColor=sampleAs3DTexture(colorTable,screen_color.rgb,SLICE_COUNT);\n}","tonemapPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform float _ExposureAdjustment;\n#if defined(HABLE_TONEMAPPING)\nconst float A=0.15;\nconst float B=0.50;\nconst float C=0.10;\nconst float D=0.20;\nconst float E=0.02;\nconst float F=0.30;\nconst float W=11.2;\n#endif\nfloat Luminance(vec3 c)\n{\nreturn dot(c,vec3(0.22,0.707,0.071));\n}\nvoid main(void) \n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\n#if defined(REINHARD_TONEMAPPING)\nfloat lum=Luminance(colour.rgb); \nfloat lumTm=lum*_ExposureAdjustment;\nfloat scale=lumTm/(1.0+lumTm); \ncolour*=scale/lum;\n#elif defined(HABLE_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nconst float ExposureBias=2.0;\nvec3 x=ExposureBias*colour;\nvec3 curr=((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F;\nx=vec3(W,W,W);\nvec3 whiteScale=1.0/(((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F);\ncolour=curr*whiteScale;\n#elif defined(OPTIMIZED_HEJIDAWSON_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\n#elif defined(PHOTOGRAPHIC_TONEMAPPING)\ncolour=vec3(1.0,1.0,1.0)-exp2(-_ExposureAdjustment*colour);\n#endif\ngl_FragColor=vec4(colour.rgb,1.0);\n}","displayPassPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D passSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(passSampler,vUV);\n}","highlightsPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nconst vec3 RGBLuminanceCoefficients=vec3(0.2126,0.7152,0.0722);\nvoid main(void) \n{\nvec4 tex=texture2D(textureSampler,vUV);\nvec3 c=tex.rgb;\nfloat luma=dot(c.rgb,RGBLuminanceCoefficients);\n\n\ngl_FragColor=vec4(pow(c,vec3(25.0-luma*15.0)),tex.a); \n}","imageProcessingPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\nvoid main(void)\n{\nvec4 result=texture2D(textureSampler,vUV);\n#ifdef IMAGEPROCESSING\n#ifndef FROMLINEARSPACE\n\nresult.rgb=toLinearSpace(result.rgb);\n#endif\nresult=applyImageProcessing(result);\n#else\n\n#ifdef FROMLINEARSPACE\nresult=applyImageProcessing(result);\n#endif\n#endif\ngl_FragColor=result;\n}","kernelBlurVertexShader":"\nattribute vec2 position;\n\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#include<kernelBlurVaryingDeclaration>[0..varyingCount]\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nsampleCenter=(position*madd+madd);\n#include<kernelBlurVertex>[0..varyingCount]\ngl_Position=vec4(position,0.0,1.0);\n}","kernelBlurPixelShader":"\nuniform sampler2D textureSampler;\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#include<kernelBlurVaryingDeclaration>[0..varyingCount]\n#ifdef PACKEDFLOAT\nvec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nvoid main(void)\n{\n#ifdef PACKEDFLOAT \nfloat blend=0.;\n#else\nvec4 blend=vec4(0.);\n#endif\n#include<kernelBlurFragment>[0..varyingCount]\n#include<kernelBlurFragment2>[0..depCount]\n#ifdef PACKEDFLOAT\ngl_FragColor=pack(blend);\n#else\ngl_FragColor=blend;\n#endif\n}","lensFlareVertexShader":"\nattribute vec2 position;\n\nuniform mat4 viewportMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=position*madd+madd;\ngl_Position=viewportMatrix*vec4(position,0.0,1.0);\n}","lensFlarePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\ngl_FragColor=baseColor*color;\n}","anaglyphPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D leftSampler;\nvoid main(void)\n{\nvec4 leftFrag=texture2D(leftSampler,vUV);\nleftFrag=vec4(1.0,leftFrag.g,leftFrag.b,1.0);\nvec4 rightFrag=texture2D(textureSampler,vUV);\nrightFrag=vec4(rightFrag.r,1.0,1.0,1.0);\ngl_FragColor=vec4(rightFrag.rgb*leftFrag.rgb,1.0);\n}","stereoscopicInterlacePixelShader":"const vec3 TWO=vec3(2.0,2.0,2.0);\nvarying vec2 vUV;\nuniform sampler2D camASampler;\nuniform sampler2D textureSampler;\nuniform vec2 stepSize;\nvoid main(void)\n{\nbool useCamB;\nvec2 texCoord1;\nvec2 texCoord2;\nvec3 frag1;\nvec3 frag2;\n#ifdef IS_STEREOSCOPIC_HORIZ\nuseCamB=vUV.x>0.5;\ntexCoord1=vec2(useCamB ? (vUV.x-0.5)*2.0 : vUV.x*2.0,vUV.y);\ntexCoord2=vec2(texCoord1.x+stepSize.x,vUV.y);\n#else\nuseCamB=vUV.y>0.5;\ntexCoord1=vec2(vUV.x,useCamB ? (vUV.y-0.5)*2.0 : vUV.y*2.0);\ntexCoord2=vec2(vUV.x,texCoord1.y+stepSize.y);\n#endif\n\nif (useCamB){\nfrag1=texture2D(textureSampler,texCoord1).rgb;\nfrag2=texture2D(textureSampler,texCoord2).rgb;\n}else{\nfrag1=texture2D(camASampler ,texCoord1).rgb;\nfrag2=texture2D(camASampler ,texCoord2).rgb;\n}\ngl_FragColor=vec4((frag1+frag2)/TWO,1.0);\n}","vrDistortionCorrectionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 LensCenter;\nuniform vec2 Scale;\nuniform vec2 ScaleIn;\nuniform vec4 HmdWarpParam;\nvec2 HmdWarp(vec2 in01) {\nvec2 theta=(in01-LensCenter)*ScaleIn; \nfloat rSq=theta.x*theta.x+theta.y*theta.y;\nvec2 rvector=theta*(HmdWarpParam.x+HmdWarpParam.y*rSq+HmdWarpParam.z*rSq*rSq+HmdWarpParam.w*rSq*rSq*rSq);\nreturn LensCenter+Scale*rvector;\n}\nvoid main(void)\n{\nvec2 tc=HmdWarp(vUV);\nif (tc.x <0.0 || tc.x>1.0 || tc.y<0.0 || tc.y>1.0)\ngl_FragColor=vec4(0.0,0.0,0.0,0.0);\nelse{\ngl_FragColor=texture2D(textureSampler,tc);\n}\n}","glowBlurPostProcessPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nuniform vec2 direction;\nuniform float blurWidth;\n\nfloat getLuminance(vec3 color)\n{\nreturn dot(color,vec3(0.2126,0.7152,0.0722));\n}\nvoid main(void)\n{\nfloat weights[7];\nweights[0]=0.05;\nweights[1]=0.1;\nweights[2]=0.2;\nweights[3]=0.3;\nweights[4]=0.2;\nweights[5]=0.1;\nweights[6]=0.05;\nvec2 texelSize=vec2(1.0/screenSize.x,1.0/screenSize.y);\nvec2 texelStep=texelSize*direction*blurWidth;\nvec2 start=vUV-3.0*texelStep;\nvec4 baseColor=vec4(0.,0.,0.,0.);\nvec2 texelOffset=vec2(0.,0.);\nfor (int i=0; i<7; i++)\n{\n\nvec4 texel=texture2D(textureSampler,start+texelOffset);\nbaseColor.a+=texel.a*weights[i];\n\nfloat luminance=getLuminance(baseColor.rgb);\nfloat luminanceTexel=getLuminance(texel.rgb);\nfloat choice=step(luminanceTexel,luminance);\nbaseColor.rgb=choice*baseColor.rgb+(1.0-choice)*texel.rgb;\ntexelOffset+=texelStep;\n}\ngl_FragColor=baseColor;\n}","glowMapGenerationPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform sampler2D emissiveSampler;\n#endif\nuniform vec4 color;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUVDiffuse).a<0.4)\ndiscard;\n#endif\n#ifdef EMISSIVE\ngl_FragColor=texture2D(emissiveSampler,vUVEmissive);\n#else\ngl_FragColor=color;\n#endif\n}","glowMapGenerationVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nvarying vec4 vPosition;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform mat4 diffuseMatrix;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform mat4 emissiveMatrix;\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\n#ifdef CUBEMAP\nvPosition=finalWorld*vec4(position,1.0);\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#else\nvPosition=viewProjection*finalWorld*vec4(position,1.0);\ngl_Position=vPosition;\n#endif\n#ifdef ALPHATEST\n#ifdef DIFFUSEUV1\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef DIFFUSEUV2\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#ifdef EMISSIVE\n#ifdef EMISSIVEUV1\nvUVEmissive=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef EMISSIVEUV2\nvUVEmissive=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","glowMapMergePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform float offset;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\nbaseColor.a=abs(offset-baseColor.a);\n#ifdef STROKE\nfloat alpha=smoothstep(.0,.1,baseColor.a);\nbaseColor.a=alpha;\nbaseColor.rgb=baseColor.rgb*alpha;\n#endif\ngl_FragColor=baseColor;\n}","glowMapMergeVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) {\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","lineVertexShader":"\nattribute vec3 position;\nattribute vec4 normal;\n\nuniform mat4 worldViewProjection;\nuniform float width;\nuniform float aspectRatio;\nvoid main(void) {\nvec4 viewPosition=worldViewProjection*vec4(position,1.0);\nvec4 viewPositionNext=worldViewProjection*vec4(normal.xyz,1.0);\nvec2 currentScreen=viewPosition.xy/viewPosition.w;\nvec2 nextScreen=viewPositionNext.xy/viewPositionNext.w;\ncurrentScreen.x*=aspectRatio;\nnextScreen.x*=aspectRatio;\nvec2 dir=normalize(nextScreen-currentScreen);\nvec2 normalDir=vec2(-dir.y,dir.x);\nnormalDir*=width/2.0;\nnormalDir.x/=aspectRatio;\nvec4 offset=vec4(normalDir*normal.w,0.0,0.0);\ngl_Position=viewPosition+offset;\n}","linePixelShader":"uniform vec4 color;\nvoid main(void) {\ngl_FragColor=color;\n}","outlineVertexShader":"\nattribute vec3 position;\nattribute vec3 normal;\n#include<bonesDeclaration>\n\nuniform float offset;\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\n#include<logDepthDeclaration>\nvoid main(void)\n{\nvec3 offsetPosition=position+normal*offset;\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(offsetPosition,1.0);\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#include<logDepthVertex>\n}\n","outlinePixelShader":"#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nuniform vec4 color;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\n#include<logDepthFragment>\ngl_FragColor=color;\n}","layerVertexShader":"\nattribute vec2 position;\n\nuniform vec2 scale;\nuniform vec2 offset;\nuniform mat4 textureMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvec2 shiftedPosition=position*scale+offset;\nvUV=vec2(textureMatrix*vec4(shiftedPosition*madd+madd,1.0,0.0));\ngl_Position=vec4(shiftedPosition,0.0,1.0);\n}","layerPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=baseColor*color;\n}","backgroundVertexShader":"precision highp float;\n#include<__decl__backgroundVertex>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2; \n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nvarying vec2 vDiffuseUV;\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\nvoid main(void) {\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=position;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvec4 worldPos=finalWorld*vec4(position,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normal);\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(position,0.0)));\n#endif\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif \n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0 \nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n}\n","backgroundPixelShader":"#ifdef TEXTURELODSUPPORT\n#extension GL_EXT_shader_texture_lod : enable\n#endif\nprecision highp float;\n#include<__decl__backgroundFragment>\n\nuniform vec3 vEyePosition;\n\nvarying vec3 vPositionW;\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif \n#ifdef MAINUV2 \nvarying vec2 vMainUV2; \n#endif \n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef DIFFUSE\n#if DIFFUSEDIRECTUV == 1\n#define vDiffuseUV vMainUV1\n#elif DIFFUSEDIRECTUV == 2\n#define vDiffuseUV vMainUV2\n#else\nvarying vec2 vDiffuseUV;\n#endif\nuniform sampler2D diffuseSampler;\n#endif\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n#define sampleReflection(s,c) textureCube(s,c)\nuniform samplerCube reflectionSampler;\n#ifdef TEXTURELODSUPPORT\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#else\n#define sampleReflection(s,c) texture2D(s,c)\nuniform sampler2D reflectionSampler;\n#ifdef TEXTURELODSUPPORT\n#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n\n#ifndef FROMLINEARSPACE\n#define FROMLINEARSPACE;\n#endif\n\n#ifndef SHADOWONLY\n#define SHADOWONLY;\n#endif\n#include<imageProcessingDeclaration>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<helperFunctions>\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n#include<imageProcessingFunctions>\n#include<clipPlaneFragmentDeclaration>\n\n#include<fogFragmentDeclaration>\n#ifdef REFLECTIONFRESNEL\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\nvec3 fresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{\n\nfloat weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);\nreturn reflectance0+weight*(reflectance90-reflectance0)*pow(clamp(1.0-VdotN,0.,1.),5.0);\n}\n#endif\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(0.0,1.0,0.0);\n#endif\n\nfloat shadow=1.;\nfloat globalShadow=0.;\nfloat shadowLightCount=0.;\n#include<lightFragment>[0..maxSimultaneousLights]\n#ifdef SHADOWINUSE\nglobalShadow/=shadowLightCount;\n#else\nglobalShadow=1.0;\n#endif\n\nvec3 reflectionColor=vec3(1.,1.,1.);\n#ifdef REFLECTION\nvec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\n\n#ifdef REFLECTIONMAP_3D\nvec3 reflectionCoords=reflectionVector;\n#else\nvec2 reflectionCoords=reflectionVector.xy;\n#ifdef REFLECTIONMAP_PROJECTION\nreflectionCoords/=reflectionVector.z;\n#endif\nreflectionCoords.y=1.0-reflectionCoords.y;\n#endif\n#ifdef REFLECTIONBLUR\nfloat reflectionLOD=vReflectionInfos.y;\n#ifdef TEXTURELODSUPPORT\n\nreflectionLOD=reflectionLOD*log2(vReflectionMicrosurfaceInfos.x)*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;\nreflectionColor=sampleReflectionLod(reflectionSampler,reflectionCoords,reflectionLOD).rgb;\n#else\nfloat lodReflectionNormalized=clamp(reflectionLOD,0.,1.);\nfloat lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;\nvec3 reflectionSpecularMid=sampleReflection(reflectionSampler,reflectionCoords).rgb;\nif(lodReflectionNormalizedDoubled<1.0){\nreflectionColor=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords).rgb,\nreflectionSpecularMid,\nlodReflectionNormalizedDoubled\n);\n} else {\nreflectionColor=mix(\nreflectionSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords).rgb,\nlodReflectionNormalizedDoubled-1.0\n);\n}\n#endif\n#else\nvec4 reflectionSample=sampleReflection(reflectionSampler,reflectionCoords);\nreflectionColor=reflectionSample.rgb;\n#endif\n#ifdef GAMMAREFLECTION\nreflectionColor=toLinearSpace(reflectionColor.rgb);\n#endif\n\nreflectionColor*=vReflectionInfos.x;\n#endif\n\nvec3 diffuseColor=vec3(1.,1.,1.);\nfloat finalAlpha=alpha;\n#ifdef DIFFUSE\nvec4 diffuseMap=texture2D(diffuseSampler,vDiffuseUV);\n#ifdef GAMMADIFFUSE\ndiffuseMap.rgb=toLinearSpace(diffuseMap.rgb);\n#endif\n\ndiffuseMap.rgb*=vDiffuseInfos.y;\n#ifdef DIFFUSEHASALPHA\nfinalAlpha*=diffuseMap.a;\n#endif\ndiffuseColor=diffuseMap.rgb;\n#endif\n\n#ifdef REFLECTIONFRESNEL\nvec3 colorBase=diffuseColor;\n#else\nvec3 colorBase=reflectionColor*diffuseColor;\n#endif\ncolorBase=max(colorBase,0.0);\n\n#ifdef USERGBCOLOR\nvec3 finalColor=colorBase;\n#else\nvec3 finalColor=colorBase.r*vPrimaryColor.rgb*vPrimaryColor.a;\nfinalColor+=colorBase.g*vSecondaryColor.rgb*vSecondaryColor.a;\nfinalColor+=colorBase.b*vTertiaryColor.rgb*vTertiaryColor.a;\n#endif\n\n#ifdef REFLECTIONFRESNEL\nvec3 reflectionAmount=vReflectionControl.xxx;\nvec3 reflectionReflectance0=vReflectionControl.yyy;\nvec3 reflectionReflectance90=vReflectionControl.zzz;\nfloat VdotN=dot(normalize(vEyePosition),normalW);\nvec3 planarReflectionFresnel=fresnelSchlickEnvironmentGGX(clamp(VdotN,0.0,1.0),reflectionReflectance0,reflectionReflectance90,1.0);\nreflectionAmount*=planarReflectionFresnel;\n#ifdef REFLECTIONFALLOFF\nfloat reflectionDistanceFalloff=1.0-clamp(length(vPositionW.xyz-vBackgroundCenter)*vReflectionControl.w,0.0,1.0);\nreflectionDistanceFalloff*=reflectionDistanceFalloff;\nreflectionAmount*=reflectionDistanceFalloff;\n#endif\nfinalColor=mix(finalColor,reflectionColor,clamp(reflectionAmount,0.,1.));\n#endif\n#ifdef OPACITYFRESNEL\nfloat viewAngleToFloor=dot(normalW,normalize(vEyePosition-vBackgroundCenter));\n\nconst float startAngle=0.1;\nfloat fadeFactor=clamp(viewAngleToFloor/startAngle,0.0,1.0);\nfinalAlpha*=fadeFactor*fadeFactor;\n#endif\n\n#ifdef SHADOWINUSE\nfinalColor=mix(finalColor*shadowLevel,finalColor,globalShadow);\n#endif\n\nvec4 color=vec4(finalColor,finalAlpha);\n#include<fogFragment>\n#ifdef IMAGEPROCESSINGPOSTPROCESS\n\n\ncolor.rgb=clamp(color.rgb,0.,30.0);\n#else\n\ncolor=applyImageProcessing(color);\n#endif\n#ifdef PREMULTIPLYALPHA\n\ncolor.rgb*=color.a;\n#endif\n#ifdef NOISE\ncolor.rgb=dither(vPositionW.xy,color.rgb);\n#endif\ngl_FragColor=color;\n}"};
  84459. BABYLON.Effect.IncludesShadersStore={"depthPrePass":"#ifdef DEPTHPREPASS\ngl_FragColor=vec4(0.,0.,0.,1.0);\nreturn;\n#endif","bonesDeclaration":"#if NUM_BONE_INFLUENCERS>0\nuniform mat4 mBones[BonesPerMesh];\nattribute vec4 matricesIndices;\nattribute vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nattribute vec4 matricesIndicesExtra;\nattribute vec4 matricesWeightsExtra;\n#endif\n#endif","instancesDeclaration":"#ifdef INSTANCES\nattribute vec4 world0;\nattribute vec4 world1;\nattribute vec4 world2;\nattribute vec4 world3;\n#else\nuniform mat4 world;\n#endif","pointCloudVertexDeclaration":"#ifdef POINTSIZE\nuniform float pointSize;\n#endif","bumpVertexDeclaration":"#if defined(BUMP) || defined(PARALLAX)\n#if defined(TANGENT) && defined(NORMAL) \nvarying mat3 vTBN;\n#endif\n#endif\n","clipPlaneVertexDeclaration":"#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nvarying float fClipDistance;\n#endif","fogVertexDeclaration":"#ifdef FOG\nvarying vec3 vFogDistance;\n#endif","morphTargetsVertexGlobalDeclaration":"#ifdef MORPHTARGETS\nuniform float morphTargetInfluences[NUM_MORPH_INFLUENCERS];\n#endif","morphTargetsVertexDeclaration":"#ifdef MORPHTARGETS\nattribute vec3 position{X};\n#ifdef MORPHTARGETS_NORMAL\nattribute vec3 normal{X};\n#endif\n#ifdef MORPHTARGETS_TANGENT\nattribute vec3 tangent{X};\n#endif\n#endif","logDepthDeclaration":"#ifdef LOGARITHMICDEPTH\nuniform float logarithmicDepthConstant;\nvarying float vFragmentDepth;\n#endif","morphTargetsVertex":"#ifdef MORPHTARGETS\npositionUpdated+=(position{X}-position)*morphTargetInfluences[{X}];\n#ifdef MORPHTARGETS_NORMAL\nnormalUpdated+=(normal{X}-normal)*morphTargetInfluences[{X}];\n#endif\n#ifdef MORPHTARGETS_TANGENT\ntangentUpdated.xyz+=(tangent{X}-tangent.xyz)*morphTargetInfluences[{X}];\n#endif\n#endif","instancesVertex":"#ifdef INSTANCES\nmat4 finalWorld=mat4(world0,world1,world2,world3);\n#else\nmat4 finalWorld=world;\n#endif","bonesVertex":"#if NUM_BONE_INFLUENCERS>0\nmat4 influence;\ninfluence=mBones[int(matricesIndices[0])]*matricesWeights[0];\n#if NUM_BONE_INFLUENCERS>1\ninfluence+=mBones[int(matricesIndices[1])]*matricesWeights[1];\n#endif \n#if NUM_BONE_INFLUENCERS>2\ninfluence+=mBones[int(matricesIndices[2])]*matricesWeights[2];\n#endif \n#if NUM_BONE_INFLUENCERS>3\ninfluence+=mBones[int(matricesIndices[3])]*matricesWeights[3];\n#endif \n#if NUM_BONE_INFLUENCERS>4\ninfluence+=mBones[int(matricesIndicesExtra[0])]*matricesWeightsExtra[0];\n#endif \n#if NUM_BONE_INFLUENCERS>5\ninfluence+=mBones[int(matricesIndicesExtra[1])]*matricesWeightsExtra[1];\n#endif \n#if NUM_BONE_INFLUENCERS>6\ninfluence+=mBones[int(matricesIndicesExtra[2])]*matricesWeightsExtra[2];\n#endif \n#if NUM_BONE_INFLUENCERS>7\ninfluence+=mBones[int(matricesIndicesExtra[3])]*matricesWeightsExtra[3];\n#endif \nfinalWorld=finalWorld*influence;\n#endif","bumpVertex":"#if defined(BUMP) || defined(PARALLAX)\n#if defined(TANGENT) && defined(NORMAL)\nvec3 tbnNormal=normalize(normalUpdated);\nvec3 tbnTangent=normalize(tangentUpdated.xyz);\nvec3 tbnBitangent=cross(tbnNormal,tbnTangent)*tangentUpdated.w;\nvTBN=mat3(finalWorld)*mat3(tbnTangent,tbnBitangent,tbnNormal);\n#endif\n#endif","clipPlaneVertex":"#ifdef CLIPPLANE\nfClipDistance=dot(worldPos,vClipPlane);\n#endif","fogVertex":"#ifdef FOG\nvFogDistance=(view*worldPos).xyz;\n#endif","shadowsVertex":"#ifdef SHADOWS\n#if defined(SHADOW{X}) && !defined(SHADOWCUBE{X})\nvPositionFromLight{X}=lightMatrix{X}*worldPos;\nvDepthMetric{X}=((vPositionFromLight{X}.z+light{X}.depthValues.x)/(light{X}.depthValues.y));\n#endif\n#endif","pointCloudVertex":"#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif","logDepthVertex":"#ifdef LOGARITHMICDEPTH\nvFragmentDepth=1.0+gl_Position.w;\ngl_Position.z=log2(max(0.000001,vFragmentDepth))*logarithmicDepthConstant;\n#endif","helperFunctions":"const float PI=3.1415926535897932384626433832795;\nconst float LinearEncodePowerApprox=2.2;\nconst float GammaEncodePowerApprox=1.0/LinearEncodePowerApprox;\nconst vec3 LuminanceEncodeApprox=vec3(0.2126,0.7152,0.0722);\nmat3 transposeMat3(mat3 inMatrix) {\nvec3 i0=inMatrix[0];\nvec3 i1=inMatrix[1];\nvec3 i2=inMatrix[2];\nmat3 outMatrix=mat3(\nvec3(i0.x,i1.x,i2.x),\nvec3(i0.y,i1.y,i2.y),\nvec3(i0.z,i1.z,i2.z)\n);\nreturn outMatrix;\n}\n\nmat3 inverseMat3(mat3 inMatrix) {\nfloat a00=inMatrix[0][0],a01=inMatrix[0][1],a02=inMatrix[0][2];\nfloat a10=inMatrix[1][0],a11=inMatrix[1][1],a12=inMatrix[1][2];\nfloat a20=inMatrix[2][0],a21=inMatrix[2][1],a22=inMatrix[2][2];\nfloat b01=a22*a11-a12*a21;\nfloat b11=-a22*a10+a12*a20;\nfloat b21=a21*a10-a11*a20;\nfloat det=a00*b01+a01*b11+a02*b21;\nreturn mat3(b01,(-a22*a01+a02*a21),(a12*a01-a02*a11),\nb11,(a22*a00-a02*a20),(-a12*a00+a02*a10),\nb21,(-a21*a00+a01*a20),(a11*a00-a01*a10))/det;\n}\nfloat computeFallOff(float value,vec2 clipSpace,float frustumEdgeFalloff)\n{\nfloat mask=smoothstep(1.0-frustumEdgeFalloff,1.0,clamp(dot(clipSpace,clipSpace),0.,1.));\nreturn mix(value,1.0,mask);\n}\nvec3 applyEaseInOut(vec3 x){\nreturn x*x*(3.0-2.0*x);\n}\nvec3 toLinearSpace(vec3 color)\n{\nreturn pow(color,vec3(LinearEncodePowerApprox));\n}\nvec3 toGammaSpace(vec3 color)\n{\nreturn pow(color,vec3(GammaEncodePowerApprox));\n}\nfloat square(float value)\n{\nreturn value*value;\n}\nfloat getLuminance(vec3 color)\n{\nreturn clamp(dot(color,LuminanceEncodeApprox),0.,1.);\n}\n\nfloat getRand(vec2 seed) {\nreturn fract(sin(dot(seed.xy ,vec2(12.9898,78.233)))*43758.5453);\n}\nvec3 dither(vec2 seed,vec3 color) {\nfloat rand=getRand(seed);\ncolor+=mix(-0.5/255.0,0.5/255.0,rand);\ncolor=max(color,0.0);\nreturn color;\n}","lightFragmentDeclaration":"#ifdef LIGHT{X}\nuniform vec4 vLightData{X};\nuniform vec4 vLightDiffuse{X};\n#ifdef SPECULARTERM\nuniform vec3 vLightSpecular{X};\n#else\nvec3 vLightSpecular{X}=vec3(0.);\n#endif\n#ifdef SHADOW{X}\n#if defined(SHADOWCUBE{X})\nuniform samplerCube shadowSampler{X};\n#else\nvarying vec4 vPositionFromLight{X};\nvarying float vDepthMetric{X};\nuniform sampler2D shadowSampler{X};\nuniform mat4 lightMatrix{X};\n#endif\nuniform vec4 shadowsInfo{X};\nuniform vec2 depthValues{X};\n#endif\n#ifdef SPOTLIGHT{X}\nuniform vec4 vLightDirection{X};\n#endif\n#ifdef HEMILIGHT{X}\nuniform vec3 vLightGround{X};\n#endif\n#endif","lightsFragmentFunctions":"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n#ifdef NDOTL\nfloat ndl;\n#endif\n};\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 lightVectorW;\nfloat attenuation=1.0;\nif (lightData.w == 0.)\n{\nvec3 direction=lightData.xyz-vPositionW;\nattenuation=max(0.,1.0-length(direction)/range);\nlightVectorW=normalize(direction);\n}\nelse\n{\nlightVectorW=normalize(-lightData.xyz);\n}\n\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 direction=lightData.xyz-vPositionW;\nvec3 lightVectorW=normalize(direction);\nfloat attenuation=max(0.,1.0-length(direction)/range);\n\nfloat cosAngle=max(0.,dot(lightDirection.xyz,-lightVectorW));\nif (cosAngle>=lightDirection.w)\n{\ncosAngle=max(0.,pow(cosAngle,lightData.w));\nattenuation*=cosAngle;\n\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nresult.diffuse=vec3(0.);\n#ifdef SPECULARTERM\nresult.specular=vec3(0.);\n#endif\n#ifdef NDOTL\nresult.ndl=0.;\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float glossiness) {\nlightingInfo result;\n\nfloat ndl=dot(vNormal,lightData.xyz)*0.5+0.5;\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=mix(groundColor,diffuseColor,ndl);\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightData.xyz);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor;\n#endif\nreturn result;\n}\n","lightUboDeclaration":"#ifdef LIGHT{X}\nuniform Light{X}\n{\nvec4 vLightData;\nvec4 vLightDiffuse;\nvec3 vLightSpecular;\n#ifdef SPOTLIGHT{X}\nvec4 vLightDirection;\n#endif\n#ifdef HEMILIGHT{X}\nvec3 vLightGround;\n#endif\nvec4 shadowsInfo;\nvec2 depthValues;\n} light{X};\n#ifdef SHADOW{X}\n#if defined(SHADOWCUBE{X})\nuniform samplerCube shadowSampler{X};\n#else\nvarying vec4 vPositionFromLight{X};\nvarying float vDepthMetric{X};\nuniform sampler2D shadowSampler{X};\nuniform mat4 lightMatrix{X};\n#endif\n#endif\n#endif","defaultVertexDeclaration":"\nuniform mat4 viewProjection;\nuniform mat4 view;\n#ifdef DIFFUSE\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nuniform mat4 ambientMatrix;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nuniform vec2 vSpecularInfos;\nuniform mat4 specularMatrix;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n","defaultFragmentDeclaration":"uniform vec4 vDiffuseColor;\n#ifdef SPECULARTERM\nuniform vec4 vSpecularColor;\n#endif\nuniform vec3 vEmissiveColor;\n\n#ifdef DIFFUSE\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY \nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform vec2 vTangentSpaceParams;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\n#ifndef REFRACTIONMAP_3D\nuniform mat4 refractionMatrix;\n#endif\n#ifdef REFRACTIONFRESNEL\nuniform vec4 refractionLeftColor;\nuniform vec4 refractionRightColor;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nuniform vec2 vSpecularInfos;\n#endif\n#ifdef DIFFUSEFRESNEL\nuniform vec4 diffuseLeftColor;\nuniform vec4 diffuseRightColor;\n#endif\n#ifdef OPACITYFRESNEL\nuniform vec4 opacityParts;\n#endif\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\n#ifdef REFLECTIONMAP_SKYBOX\n#else\n#if defined(REFLECTIONMAP_PLANAR) || defined(REFLECTIONMAP_CUBIC) || defined(REFLECTIONMAP_PROJECTION)\nuniform mat4 reflectionMatrix;\n#endif\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 reflectionLeftColor;\nuniform vec4 reflectionRightColor;\n#endif\n#endif","defaultUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nvec4 diffuseLeftColor;\nvec4 diffuseRightColor;\nvec4 opacityParts;\nvec4 reflectionLeftColor;\nvec4 reflectionRightColor;\nvec4 refractionLeftColor;\nvec4 refractionRightColor;\nvec4 emissiveLeftColor; \nvec4 emissiveRightColor;\nvec2 vDiffuseInfos;\nvec2 vAmbientInfos;\nvec2 vOpacityInfos;\nvec2 vReflectionInfos;\nvec2 vEmissiveInfos;\nvec2 vLightmapInfos;\nvec2 vSpecularInfos;\nvec3 vBumpInfos;\nmat4 diffuseMatrix;\nmat4 ambientMatrix;\nmat4 opacityMatrix;\nmat4 reflectionMatrix;\nmat4 emissiveMatrix;\nmat4 lightmapMatrix;\nmat4 specularMatrix;\nmat4 bumpMatrix; \nvec4 vTangentSpaceParams;\nmat4 refractionMatrix;\nvec4 vRefractionInfos;\nvec4 vSpecularColor;\nvec3 vEmissiveColor;\nvec4 vDiffuseColor;\nfloat pointSize; \n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};","shadowsFragmentFunctions":"#ifdef SHADOWS\n#ifndef SHADOWFLOAT\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nfloat computeShadowCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadow=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadow=textureCube(shadowSampler,directionToLight).x;\n#endif\nif (depth>shadow)\n{\nreturn darkness;\n}\nreturn 1.0;\n}\nfloat computeShadowWithPCFCube(vec3 lightPosition,samplerCube shadowSampler,float mapSize,float darkness,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\nfloat visibility=1.;\nvec3 poissonDisk[4];\npoissonDisk[0]=vec3(-1.0,1.0,-1.0);\npoissonDisk[1]=vec3(1.0,-1.0,-1.0);\npoissonDisk[2]=vec3(-1.0,-1.0,-1.0);\npoissonDisk[3]=vec3(1.0,-1.0,1.0);\n\n#ifndef SHADOWFLOAT\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize))<depth) visibility-=0.25;\n#else\nif (textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize).x<depth) visibility-=0.25;\n#endif\nreturn min(1.0,visibility+darkness);\n}\nfloat computeShadowWithESMCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float depthScale,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadowMapSample=textureCube(shadowSampler,directionToLight).x;\n#endif\nfloat esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness); \nreturn esm;\n}\nfloat computeShadowWithCloseESMCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float depthScale,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadowMapSample=textureCube(shadowSampler,directionToLight).x;\n#endif\nfloat esm=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);\nreturn esm;\n}\nfloat computeShadow(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nfloat shadow=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadow=texture2D(shadowSampler,uv).x;\n#endif\nif (shadowPixelDepth>shadow)\n{\nreturn computeFallOff(darkness,clipSpace.xy,frustumEdgeFalloff);\n}\nreturn 1.;\n}\nfloat computeShadowWithPCF(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float mapSize,float darkness,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\nfloat visibility=1.;\nvec2 poissonDisk[4];\npoissonDisk[0]=vec2(-0.94201624,-0.39906216);\npoissonDisk[1]=vec2(0.94558609,-0.76890725);\npoissonDisk[2]=vec2(-0.094184101,-0.92938870);\npoissonDisk[3]=vec2(0.34495938,0.29387760);\n\n#ifndef SHADOWFLOAT\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[0]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[1]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[2]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[3]*mapSize))<shadowPixelDepth) visibility-=0.25;\n#else\nif (texture2D(shadowSampler,uv+poissonDisk[0]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[1]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[2]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[3]*mapSize).x<shadowPixelDepth) visibility-=0.25;\n#endif\nreturn computeFallOff(min(1.0,visibility+darkness),clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithESM(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float depthScale,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadowMapSample=texture2D(shadowSampler,uv).x;\n#endif\nfloat esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness);\nreturn computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithCloseESM(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float depthScale,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0); \n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadowMapSample=texture2D(shadowSampler,uv).x;\n#endif\nfloat esm=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);\nreturn computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);\n}\n#endif\n","fresnelFunction":"#ifdef FRESNEL\nfloat computeFresnelTerm(vec3 viewDirection,vec3 worldNormal,float bias,float power)\n{\nfloat fresnelTerm=pow(bias+abs(dot(viewDirection,worldNormal)),power);\nreturn clamp(fresnelTerm,0.,1.);\n}\n#endif","reflectionFunction":"vec3 computeReflectionCoords(vec4 worldPos,vec3 worldNormal)\n{\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvec3 direction=normalize(vDirectionW);\nfloat t=clamp(direction.y*-0.5+0.5,0.,1.0);\nfloat s=atan(direction.z,direction.x)*RECIPROCAL_PI2+0.5;\n#ifdef REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED\nreturn vec3(1.0-s,t,0);\n#else\nreturn vec3(s,t,0);\n#endif\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR\nvec3 cameraToVertex=normalize(worldPos.xyz-vEyePosition.xyz);\nvec3 r=reflect(cameraToVertex,worldNormal);\nfloat t=clamp(r.y*-0.5+0.5,0.,1.0);\nfloat s=atan(r.z,r.x)*RECIPROCAL_PI2+0.5;\nreturn vec3(s,t,0);\n#endif\n#ifdef REFLECTIONMAP_SPHERICAL\nvec3 viewDir=normalize(vec3(view*worldPos));\nvec3 viewNormal=normalize(vec3(view*vec4(worldNormal,0.0)));\nvec3 r=reflect(viewDir,viewNormal);\nr.z=r.z-1.0;\nfloat m=2.0*length(r);\nreturn vec3(r.x/m+0.5,1.0-r.y/m-0.5,0);\n#endif\n#ifdef REFLECTIONMAP_PLANAR\nvec3 viewDir=worldPos.xyz-vEyePosition.xyz;\nvec3 coords=normalize(reflect(viewDir,worldNormal));\nreturn vec3(reflectionMatrix*vec4(coords,1));\n#endif\n#ifdef REFLECTIONMAP_CUBIC\nvec3 viewDir=worldPos.xyz-vEyePosition.xyz;\nvec3 coords=reflect(viewDir,worldNormal);\n#ifdef INVERTCUBICMAP\ncoords.y=1.0-coords.y;\n#endif\nreturn vec3(reflectionMatrix*vec4(coords,0));\n#endif\n#ifdef REFLECTIONMAP_PROJECTION\nreturn vec3(reflectionMatrix*(view*worldPos));\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nreturn vPositionUVW;\n#endif\n#ifdef REFLECTIONMAP_EXPLICIT\nreturn vec3(0,0,0);\n#endif\n}","imageProcessingDeclaration":"#ifdef EXPOSURE\nuniform float exposureLinear;\n#endif\n#ifdef CONTRAST\nuniform float contrast;\n#endif\n#ifdef VIGNETTE\nuniform vec2 vInverseScreenSize;\nuniform vec4 vignetteSettings1;\nuniform vec4 vignetteSettings2;\n#endif\n#ifdef COLORCURVES\nuniform vec4 vCameraColorCurveNegative;\nuniform vec4 vCameraColorCurveNeutral;\nuniform vec4 vCameraColorCurvePositive;\n#endif\n#ifdef COLORGRADING\n#ifdef COLORGRADING3D\nuniform highp sampler3D txColorTransform;\n#else\nuniform sampler2D txColorTransform;\n#endif\nuniform vec4 colorTransformSettings;\n#endif","imageProcessingFunctions":"#if defined(COLORGRADING) && !defined(COLORGRADING3D)\n\nvec3 sampleTexture3D(sampler2D colorTransform,vec3 color,vec2 sampler3dSetting)\n{\nfloat sliceSize=2.0*sampler3dSetting.x; \n#ifdef SAMPLER3DGREENDEPTH\nfloat sliceContinuous=(color.g-sampler3dSetting.x)*sampler3dSetting.y;\n#else\nfloat sliceContinuous=(color.b-sampler3dSetting.x)*sampler3dSetting.y;\n#endif\nfloat sliceInteger=floor(sliceContinuous);\n\n\nfloat sliceFraction=sliceContinuous-sliceInteger;\n#ifdef SAMPLER3DGREENDEPTH\nvec2 sliceUV=color.rb;\n#else\nvec2 sliceUV=color.rg;\n#endif\nsliceUV.x*=sliceSize;\nsliceUV.x+=sliceInteger*sliceSize;\nsliceUV=clamp(sliceUV,0.,1.);\nvec4 slice0Color=texture2D(colorTransform,sliceUV);\nsliceUV.x+=sliceSize;\nsliceUV=clamp(sliceUV,0.,1.);\nvec4 slice1Color=texture2D(colorTransform,sliceUV);\nvec3 result=mix(slice0Color.rgb,slice1Color.rgb,sliceFraction);\n#ifdef SAMPLER3DBGRMAP\ncolor.rgb=result.rgb;\n#else\ncolor.rgb=result.bgr;\n#endif\nreturn color;\n}\n#endif\nvec4 applyImageProcessing(vec4 result) {\n#ifdef EXPOSURE\nresult.rgb*=exposureLinear;\n#endif\n#ifdef VIGNETTE\n\nvec2 viewportXY=gl_FragCoord.xy*vInverseScreenSize;\nviewportXY=viewportXY*2.0-1.0;\nvec3 vignetteXY1=vec3(viewportXY*vignetteSettings1.xy+vignetteSettings1.zw,1.0);\nfloat vignetteTerm=dot(vignetteXY1,vignetteXY1);\nfloat vignette=pow(vignetteTerm,vignetteSettings2.w);\n\nvec3 vignetteColor=vignetteSettings2.rgb;\n#ifdef VIGNETTEBLENDMODEMULTIPLY\nvec3 vignetteColorMultiplier=mix(vignetteColor,vec3(1,1,1),vignette);\nresult.rgb*=vignetteColorMultiplier;\n#endif\n#ifdef VIGNETTEBLENDMODEOPAQUE\nresult.rgb=mix(vignetteColor,result.rgb,vignette);\n#endif\n#endif\n#ifdef TONEMAPPING\nconst float tonemappingCalibration=1.590579;\nresult.rgb=1.0-exp2(-tonemappingCalibration*result.rgb);\n#endif\n\nresult.rgb=toGammaSpace(result.rgb);\nresult.rgb=clamp(result.rgb,0.0,1.0);\n#ifdef CONTRAST\n\nvec3 resultHighContrast=applyEaseInOut(result.rgb);\nif (contrast<1.0) {\n\nresult.rgb=mix(vec3(0.5,0.5,0.5),result.rgb,contrast);\n} else {\n\nresult.rgb=mix(result.rgb,resultHighContrast,contrast-1.0);\n}\n#endif\n\n#ifdef COLORGRADING\nvec3 colorTransformInput=result.rgb*colorTransformSettings.xxx+colorTransformSettings.yyy;\n#ifdef COLORGRADING3D\nvec3 colorTransformOutput=texture(txColorTransform,colorTransformInput).rgb;\n#else\nvec3 colorTransformOutput=sampleTexture3D(txColorTransform,colorTransformInput,colorTransformSettings.yz).rgb;\n#endif\nresult.rgb=mix(result.rgb,colorTransformOutput,colorTransformSettings.www);\n#endif\n#ifdef COLORCURVES\n\nfloat luma=getLuminance(result.rgb);\nvec2 curveMix=clamp(vec2(luma*3.0-1.5,luma*-3.0+1.5),vec2(0.0),vec2(1.0));\nvec4 colorCurve=vCameraColorCurveNeutral+curveMix.x*vCameraColorCurvePositive-curveMix.y*vCameraColorCurveNegative;\nresult.rgb*=colorCurve.rgb;\nresult.rgb=mix(vec3(luma),result.rgb,colorCurve.a);\n#endif\nreturn result;\n}","bumpFragmentFunctions":"#ifdef BUMP\n#if BUMPDIRECTUV == 1\n#define vBumpUV vMainUV1\n#elif BUMPDIRECTUV == 2\n#define vBumpUV vMainUV2\n#else\nvarying vec2 vBumpUV;\n#endif\nuniform sampler2D bumpSampler;\n#if defined(TANGENT) && defined(NORMAL) \nvarying mat3 vTBN;\n#endif\n\nmat3 cotangent_frame(vec3 normal,vec3 p,vec2 uv)\n{\n\nuv=gl_FrontFacing ? uv : -uv;\n\nvec3 dp1=dFdx(p);\nvec3 dp2=dFdy(p);\nvec2 duv1=dFdx(uv);\nvec2 duv2=dFdy(uv);\n\nvec3 dp2perp=cross(dp2,normal);\nvec3 dp1perp=cross(normal,dp1);\nvec3 tangent=dp2perp*duv1.x+dp1perp*duv2.x;\nvec3 bitangent=dp2perp*duv1.y+dp1perp*duv2.y;\n\ntangent*=vTangentSpaceParams.x;\nbitangent*=vTangentSpaceParams.y;\n\nfloat invmax=inversesqrt(max(dot(tangent,tangent),dot(bitangent,bitangent)));\nreturn mat3(tangent*invmax,bitangent*invmax,normal);\n}\nvec3 perturbNormal(mat3 cotangentFrame,vec2 uv)\n{\nvec3 map=texture2D(bumpSampler,uv).xyz;\nmap=map*2.0-1.0;\n#ifdef NORMALXYSCALE\nmap=normalize(map*vec3(vBumpInfos.y,vBumpInfos.y,1.0));\n#endif\nreturn normalize(cotangentFrame*map);\n}\n#ifdef PARALLAX\nconst float minSamples=4.;\nconst float maxSamples=15.;\nconst int iMaxSamples=15;\n\nvec2 parallaxOcclusion(vec3 vViewDirCoT,vec3 vNormalCoT,vec2 texCoord,float parallaxScale) {\nfloat parallaxLimit=length(vViewDirCoT.xy)/vViewDirCoT.z;\nparallaxLimit*=parallaxScale;\nvec2 vOffsetDir=normalize(vViewDirCoT.xy);\nvec2 vMaxOffset=vOffsetDir*parallaxLimit;\nfloat numSamples=maxSamples+(dot(vViewDirCoT,vNormalCoT)*(minSamples-maxSamples));\nfloat stepSize=1.0/numSamples;\n\nfloat currRayHeight=1.0;\nvec2 vCurrOffset=vec2(0,0);\nvec2 vLastOffset=vec2(0,0);\nfloat lastSampledHeight=1.0;\nfloat currSampledHeight=1.0;\nfor (int i=0; i<iMaxSamples; i++)\n{\ncurrSampledHeight=texture2D(bumpSampler,vBumpUV+vCurrOffset).w;\n\nif (currSampledHeight>currRayHeight)\n{\nfloat delta1=currSampledHeight-currRayHeight;\nfloat delta2=(currRayHeight+stepSize)-lastSampledHeight;\nfloat ratio=delta1/(delta1+delta2);\nvCurrOffset=(ratio)* vLastOffset+(1.0-ratio)*vCurrOffset;\n\nbreak;\n}\nelse\n{\ncurrRayHeight-=stepSize;\nvLastOffset=vCurrOffset;\nvCurrOffset+=stepSize*vMaxOffset;\nlastSampledHeight=currSampledHeight;\n}\n}\nreturn vCurrOffset;\n}\nvec2 parallaxOffset(vec3 viewDir,float heightScale)\n{\n\nfloat height=texture2D(bumpSampler,vBumpUV).w;\nvec2 texCoordOffset=heightScale*viewDir.xy*height;\nreturn -texCoordOffset;\n}\n#endif\n#endif","clipPlaneFragmentDeclaration":"#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif","fogFragmentDeclaration":"#ifdef FOG\n#define FOGMODE_NONE 0.\n#define FOGMODE_EXP 1.\n#define FOGMODE_EXP2 2.\n#define FOGMODE_LINEAR 3.\n#define E 2.71828\nuniform vec4 vFogInfos;\nuniform vec3 vFogColor;\nvarying vec3 vFogDistance;\nfloat CalcFogFactor()\n{\nfloat fogCoeff=1.0;\nfloat fogStart=vFogInfos.y;\nfloat fogEnd=vFogInfos.z;\nfloat fogDensity=vFogInfos.w;\nfloat fogDistance=length(vFogDistance);\nif (FOGMODE_LINEAR == vFogInfos.x)\n{\nfogCoeff=(fogEnd-fogDistance)/(fogEnd-fogStart);\n}\nelse if (FOGMODE_EXP == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fogDistance*fogDensity);\n}\nelse if (FOGMODE_EXP2 == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fogDistance*fogDistance*fogDensity*fogDensity);\n}\nreturn clamp(fogCoeff,0.0,1.0);\n}\n#endif","clipPlaneFragment":"#ifdef CLIPPLANE\nif (fClipDistance>0.0)\n{\ndiscard;\n}\n#endif","bumpFragment":"vec2 uvOffset=vec2(0.0,0.0);\n#if defined(BUMP) || defined(PARALLAX)\n#ifdef NORMALXYSCALE\nfloat normalScale=1.0;\n#else \nfloat normalScale=vBumpInfos.y;\n#endif\n#if defined(TANGENT) && defined(NORMAL)\nmat3 TBN=vTBN;\n#else\nmat3 TBN=cotangent_frame(normalW*normalScale,vPositionW,vBumpUV);\n#endif\n#endif\n#ifdef PARALLAX\nmat3 invTBN=transposeMat3(TBN);\n#ifdef PARALLAXOCCLUSION\nuvOffset=parallaxOcclusion(invTBN*-viewDirectionW,invTBN*normalW,vBumpUV,vBumpInfos.z);\n#else\nuvOffset=parallaxOffset(invTBN*viewDirectionW,vBumpInfos.z);\n#endif\n#endif\n#ifdef BUMP\nnormalW=perturbNormal(TBN,vBumpUV+uvOffset);\n#endif","lightFragment":"#ifdef LIGHT{X}\n#if defined(SHADOWONLY) || (defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X}) && defined(LIGHTMAPNOSPECULAR{X}))\n\n#else\n#ifdef PBR\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,NdotL);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightGround,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,NdotL);\n#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,NdotL);\n#endif\n#else\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,glossiness);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightGround,glossiness);\n#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,glossiness);\n#endif\n#endif\n#endif\n#ifdef SHADOW{X}\n#ifdef SHADOWCLOSEESM{X}\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithCloseESMCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues);\n#else\nshadow=computeShadowWithCloseESM(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w);\n#endif\n#else\n#ifdef SHADOWESM{X}\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithESMCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues);\n#else\nshadow=computeShadowWithESM(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w);\n#endif\n#else \n#ifdef SHADOWPCF{X}\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithPCFCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.depthValues);\n#else\nshadow=computeShadowWithPCF(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#else\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.depthValues);\n#else\nshadow=computeShadow(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#endif\n#endif\n#endif\n#ifdef SHADOWONLY\n#ifndef SHADOWINUSE\n#define SHADOWINUSE\n#endif\nglobalShadow+=shadow;\nshadowLightCount+=1.0;\n#endif\n#else\nshadow=1.;\n#endif\n#ifndef SHADOWONLY\n#ifdef CUSTOMUSERLIGHTING\ndiffuseBase+=computeCustomDiffuseLighting(info,diffuseBase,shadow);\n#ifdef SPECULARTERM\nspecularBase+=computeCustomSpecularLighting(info,specularBase,shadow);\n#endif\n#elif defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X})\ndiffuseBase+=lightmapColor*shadow;\n#ifdef SPECULARTERM\n#ifndef LIGHTMAPNOSPECULAR{X}\nspecularBase+=info.specular*shadow*lightmapColor;\n#endif\n#endif\n#else\ndiffuseBase+=info.diffuse*shadow;\n#ifdef SPECULARTERM\nspecularBase+=info.specular*shadow;\n#endif\n#endif\n#endif\n#endif","logDepthFragment":"#ifdef LOGARITHMICDEPTH\ngl_FragDepthEXT=log2(vFragmentDepth)*logarithmicDepthConstant*0.5;\n#endif","fogFragment":"#ifdef FOG\nfloat fog=CalcFogFactor();\ncolor.rgb=fog*color.rgb+(1.0-fog)*vFogColor;\n#endif","pbrVertexDeclaration":"uniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef ALBEDO\nuniform mat4 albedoMatrix;\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nuniform mat4 ambientMatrix;\nuniform vec3 vAmbientInfos;\n#endif\n#ifdef OPACITY\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#ifdef REFLECTIVITY \nuniform vec3 vReflectivityInfos;\nuniform mat4 reflectivityMatrix;\n#endif\n#ifdef MICROSURFACEMAP\nuniform vec2 vMicroSurfaceSamplerInfos;\nuniform mat4 microSurfaceSamplerMatrix;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\nuniform mat4 refractionMatrix;\nuniform vec3 vRefractionMicrosurfaceInfos;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#endif\n","pbrFragmentDeclaration":"uniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\n\nuniform vec4 vLightingIntensity;\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\n\n#ifdef ALBEDO\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nuniform vec3 vAmbientInfos;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform vec2 vTangentSpaceParams;\n#endif\n#ifdef OPACITY \nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\n#endif\n#ifdef REFLECTIVITY\nuniform vec3 vReflectivityInfos;\n#endif\n#ifdef MICROSURFACEMAP\nuniform vec2 vMicroSurfaceSamplerInfos;\n#endif\n\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\nuniform mat4 refractionMatrix;\nuniform vec3 vRefractionMicrosurfaceInfos;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#endif","pbrUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nuniform vec2 vAlbedoInfos;\nuniform vec3 vAmbientInfos;\nuniform vec2 vOpacityInfos;\nuniform vec2 vEmissiveInfos;\nuniform vec2 vLightmapInfos;\nuniform vec3 vReflectivityInfos;\nuniform vec2 vMicroSurfaceSamplerInfos;\nuniform vec4 vRefractionInfos;\nuniform vec2 vReflectionInfos;\nuniform vec3 vBumpInfos;\nuniform mat4 albedoMatrix;\nuniform mat4 ambientMatrix;\nuniform mat4 opacityMatrix;\nuniform mat4 emissiveMatrix;\nuniform mat4 lightmapMatrix;\nuniform mat4 reflectivityMatrix;\nuniform mat4 microSurfaceSamplerMatrix;\nuniform mat4 bumpMatrix;\nuniform vec2 vTangentSpaceParams;\nuniform mat4 refractionMatrix;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\nuniform vec4 vLightingIntensity;\nuniform vec3 vRefractionMicrosurfaceInfos;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\nuniform float pointSize;\n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};","pbrFunctions":"\n#define RECIPROCAL_PI2 0.15915494\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\n\nconst float kRougnhessToAlphaScale=0.1;\nconst float kRougnhessToAlphaOffset=0.29248125;\nfloat convertRoughnessToAverageSlope(float roughness)\n{\n\nconst float kMinimumVariance=0.0005;\nfloat alphaG=square(roughness)+kMinimumVariance;\nreturn alphaG;\n}\n\nfloat smithVisibilityG1_TrowbridgeReitzGGX(float dot,float alphaG)\n{\nfloat tanSquared=(1.0-dot*dot)/(dot*dot);\nreturn 2.0/(1.0+sqrt(1.0+alphaG*alphaG*tanSquared));\n}\nfloat smithVisibilityG_TrowbridgeReitzGGX_Walter(float NdotL,float NdotV,float alphaG)\n{\nreturn smithVisibilityG1_TrowbridgeReitzGGX(NdotL,alphaG)*smithVisibilityG1_TrowbridgeReitzGGX(NdotV,alphaG);\n}\n\n\nfloat normalDistributionFunction_TrowbridgeReitzGGX(float NdotH,float alphaG)\n{\n\n\n\nfloat a2=square(alphaG);\nfloat d=NdotH*NdotH*(a2-1.0)+1.0;\nreturn a2/(PI*d*d);\n}\nvec3 fresnelSchlickGGX(float VdotH,vec3 reflectance0,vec3 reflectance90)\n{\nreturn reflectance0+(reflectance90-reflectance0)*pow(clamp(1.0-VdotH,0.,1.),5.0);\n}\nvec3 fresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{\n\nfloat weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);\nreturn reflectance0+weight*(reflectance90-reflectance0)*pow(clamp(1.0-VdotN,0.,1.),5.0);\n}\n\nvec3 computeSpecularTerm(float NdotH,float NdotL,float NdotV,float VdotH,float roughness,vec3 reflectance0,vec3 reflectance90)\n{\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\nfloat distribution=normalDistributionFunction_TrowbridgeReitzGGX(NdotH,alphaG);\nfloat visibility=smithVisibilityG_TrowbridgeReitzGGX_Walter(NdotL,NdotV,alphaG);\nvisibility/=(4.0*NdotL*NdotV); \nfloat specTerm=max(0.,visibility*distribution)*NdotL;\nvec3 fresnel=fresnelSchlickGGX(VdotH,reflectance0,reflectance90);\nreturn fresnel*specTerm;\n}\nfloat computeDiffuseTerm(float NdotL,float NdotV,float VdotH,float roughness)\n{\n\n\nfloat diffuseFresnelNV=pow(clamp(1.0-NdotL,0.000001,1.),5.0);\nfloat diffuseFresnelNL=pow(clamp(1.0-NdotV,0.000001,1.),5.0);\nfloat diffuseFresnel90=0.5+2.0*VdotH*VdotH*roughness;\nfloat fresnel =\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNL) *\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNV);\nreturn fresnel*NdotL/PI;\n}\nfloat adjustRoughnessFromLightProperties(float roughness,float lightRadius,float lightDistance)\n{\n#ifdef USEPHYSICALLIGHTFALLOFF\n\nfloat lightRoughness=lightRadius/lightDistance;\n\nfloat totalRoughness=clamp(lightRoughness+roughness,0.,1.);\nreturn totalRoughness;\n#else\nreturn roughness;\n#endif\n}\nfloat computeDefaultMicroSurface(float microSurface,vec3 reflectivityColor)\n{\nconst float kReflectivityNoAlphaWorkflow_SmoothnessMax=0.95;\nfloat reflectivityLuminance=getLuminance(reflectivityColor);\nfloat reflectivityLuma=sqrt(reflectivityLuminance);\nmicroSurface=reflectivityLuma*kReflectivityNoAlphaWorkflow_SmoothnessMax;\nreturn microSurface;\n}\n\n\nfloat fresnelGrazingReflectance(float reflectance0) {\nfloat reflectance90=clamp(reflectance0*25.0,0.0,1.0);\nreturn reflectance90;\n}\n\n\n#define UNPACK_LOD(x) (1.0-x)*255.0\nfloat getLodFromAlphaG(float cubeMapDimensionPixels,float alphaG,float NdotV) {\nfloat microsurfaceAverageSlope=alphaG;\n\n\n\n\n\n\nmicrosurfaceAverageSlope*=sqrt(abs(NdotV));\nfloat microsurfaceAverageSlopeTexels=microsurfaceAverageSlope*cubeMapDimensionPixels;\nfloat lod=log2(microsurfaceAverageSlopeTexels);\nreturn lod;\n}\nfloat environmentRadianceOcclusion(float ambientOcclusion,float NdotVUnclamped) {\n\n\nfloat temp=NdotVUnclamped+ambientOcclusion;\nreturn clamp(square(temp)-1.0+ambientOcclusion,0.0,1.0);\n}\nfloat environmentHorizonOcclusion(vec3 reflection,vec3 normal) {\n\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflection.z*=-1.0;\n#endif\nfloat temp=clamp( 1.0+1.1*dot(reflection,normal),0.0,1.0);\nreturn square(temp);\n}","harmonicsFunctions":"#ifdef USESPHERICALFROMREFLECTIONMAP\nuniform vec3 vSphericalX;\nuniform vec3 vSphericalY;\nuniform vec3 vSphericalZ;\nuniform vec3 vSphericalXX_ZZ;\nuniform vec3 vSphericalYY_ZZ;\nuniform vec3 vSphericalZZ;\nuniform vec3 vSphericalXY;\nuniform vec3 vSphericalYZ;\nuniform vec3 vSphericalZX;\nvec3 quaternionVectorRotation_ScaledSqrtTwo(vec4 Q,vec3 V){\nvec3 T=cross(Q.xyz,V);\nT+=Q.www*V;\nreturn cross(Q.xyz,T)+V;\n}\nvec3 environmentIrradianceJones(vec3 normal)\n{\n\n\n\n\n\n\n\n\n\nfloat Nx=normal.x;\nfloat Ny=normal.y;\nfloat Nz=normal.z;\nvec3 C1=vSphericalZZ.rgb;\nvec3 Cx=vSphericalX.rgb;\nvec3 Cy=vSphericalY.rgb;\nvec3 Cz=vSphericalZ.rgb;\nvec3 Cxx_zz=vSphericalXX_ZZ.rgb;\nvec3 Cyy_zz=vSphericalYY_ZZ.rgb;\nvec3 Cxy=vSphericalXY.rgb;\nvec3 Cyz=vSphericalYZ.rgb;\nvec3 Czx=vSphericalZX.rgb;\nvec3 a1=Cyy_zz*Ny+Cy;\nvec3 a2=Cyz*Nz+a1;\nvec3 b1=Czx*Nz+Cx;\nvec3 b2=Cxy*Ny+b1;\nvec3 b3=Cxx_zz*Nx+b2;\nvec3 t1=Cz*Nz+C1;\nvec3 t2=a2*Ny+t1;\nvec3 t3=b3*Nx+t2;\nreturn t3;\n}\n#endif","pbrLightFunctions":"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n};\nfloat computeDistanceLightFalloff(vec3 lightOffset,float lightDistanceSquared,float range)\n{ \n#ifdef USEPHYSICALLIGHTFALLOFF\nfloat lightDistanceFalloff=1.0/((lightDistanceSquared+0.001));\n#else\nfloat lightDistanceFalloff=max(0.,1.0-length(lightOffset)/range);\n#endif\nreturn lightDistanceFalloff;\n}\nfloat computeDirectionalLightFalloff(vec3 lightDirection,vec3 directionToLightCenterW,float cosHalfAngle,float exponent)\n{\nfloat falloff=0.0;\n#ifdef USEPHYSICALLIGHTFALLOFF\nconst float kMinusLog2ConeAngleIntensityRatio=6.64385618977; \n\n\n\n\n\nfloat concentrationKappa=kMinusLog2ConeAngleIntensityRatio/(1.0-cosHalfAngle);\n\n\nvec4 lightDirectionSpreadSG=vec4(-lightDirection*concentrationKappa,-concentrationKappa);\nfalloff=exp2(dot(vec4(directionToLightCenterW,1.0),lightDirectionSpreadSG));\n#else\nfloat cosAngle=max(0.000000000000001,dot(-lightDirection,directionToLightCenterW));\nif (cosAngle>=cosHalfAngle)\n{\nfalloff=max(0.,pow(cosAngle,exponent));\n}\n#endif\nreturn falloff;\n}\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float rangeRadius,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,out float NdotL) {\nlightingInfo result;\nvec3 lightDirection;\nfloat attenuation=1.0;\nfloat lightDistance;\n\nif (lightData.w == 0.)\n{\nvec3 lightOffset=lightData.xyz-vPositionW;\nfloat lightDistanceSquared=dot(lightOffset,lightOffset);\nattenuation=computeDistanceLightFalloff(lightOffset,lightDistanceSquared,rangeRadius);\nlightDistance=sqrt(lightDistanceSquared);\nlightDirection=normalize(lightOffset);\n}\n\nelse\n{\nlightDistance=length(-lightData.xyz);\nlightDirection=normalize(-lightData.xyz);\n}\n\nroughness=adjustRoughnessFromLightProperties(roughness,rangeRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+lightDirection);\nNdotL=clamp(dot(vNormal,lightDirection),0.00000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90);\nresult.specular=specTerm*diffuseColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float rangeRadius,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,out float NdotL) {\nlightingInfo result;\nvec3 lightOffset=lightData.xyz-vPositionW;\nvec3 directionToLightCenterW=normalize(lightOffset);\n\nfloat lightDistanceSquared=dot(lightOffset,lightOffset);\nfloat attenuation=computeDistanceLightFalloff(lightOffset,lightDistanceSquared,rangeRadius);\n\nfloat directionalAttenuation=computeDirectionalLightFalloff(lightDirection.xyz,directionToLightCenterW,lightDirection.w,lightData.w);\nattenuation*=directionalAttenuation;\n\nfloat lightDistance=sqrt(lightDistanceSquared);\nroughness=adjustRoughnessFromLightProperties(roughness,rangeRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+directionToLightCenterW);\nNdotL=clamp(dot(vNormal,directionToLightCenterW),0.000000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90);\nresult.specular=specTerm*diffuseColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,out float NdotL) {\nlightingInfo result;\n\n\n\nNdotL=dot(vNormal,lightData.xyz)*0.5+0.5;\nresult.diffuse=mix(groundColor,diffuseColor,NdotL);\n#ifdef SPECULARTERM\n\nvec3 lightVectorW=normalize(lightData.xyz);\nvec3 H=normalize(viewDirectionW+lightVectorW);\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nNdotL=clamp(NdotL,0.000000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90);\nresult.specular=specTerm*diffuseColor;\n#endif\nreturn result;\n}","mrtFragmentDeclaration":"#if __VERSION__>=200\nlayout(location=0) out vec4 glFragData[{X}];\n#endif\n","bones300Declaration":"#if NUM_BONE_INFLUENCERS>0\nuniform mat4 mBones[BonesPerMesh];\nin vec4 matricesIndices;\nin vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nin vec4 matricesIndicesExtra;\nin vec4 matricesWeightsExtra;\n#endif\n#endif","instances300Declaration":"#ifdef INSTANCES\nin vec4 world0;\nin vec4 world1;\nin vec4 world2;\nin vec4 world3;\n#else\nuniform mat4 world;\n#endif","kernelBlurFragment":"#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCoord{X}))*KERNEL_WEIGHT{X};\n#else\nblend+=texture2D(textureSampler,sampleCoord{X})*KERNEL_WEIGHT{X};\n#endif","kernelBlurFragment2":"#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X}))*KERNEL_DEP_WEIGHT{X};\n#else\nblend+=texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X})*KERNEL_DEP_WEIGHT{X};\n#endif","kernelBlurVaryingDeclaration":"varying vec2 sampleCoord{X};","kernelBlurVertex":"sampleCoord{X}=sampleCenter+delta*KERNEL_OFFSET{X};","backgroundVertexDeclaration":"uniform mat4 view;\nuniform mat4 viewProjection;\nuniform float shadowLevel;\n#ifdef DIFFUSE\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif","backgroundFragmentDeclaration":" uniform vec4 vPrimaryColor;\nuniform vec4 vSecondaryColor;\nuniform vec4 vTertiaryColor;\nuniform float shadowLevel;\nuniform float alpha;\n#ifdef DIFFUSE\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#endif\n#if defined(REFLECTIONFRESNEL) || defined(OPACITYFRESNEL)\nuniform vec3 vBackgroundCenter;\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 vReflectionControl;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif","backgroundUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nuniform vec4 vPrimaryColor;\nuniform vec4 vSecondaryColor;\nuniform vec4 vTertiaryColor;\nuniform vec2 vDiffuseInfos;\nuniform vec2 vReflectionInfos;\nuniform mat4 diffuseMatrix;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform float pointSize;\nuniform float shadowLevel;\nuniform float alpha;\n#if defined(REFLECTIONFRESNEL) || defined(OPACITYFRESNEL)\nuniform vec3 vBackgroundCenter;\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 vReflectionControl;\n#endif\n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};"};
  84460. (function universalModuleDefinition(root, factory) {
  84461. var f = factory();
  84462. if (root && root["BABYLON"]) {
  84463. return;
  84464. }
  84465. var globalObject = (typeof global !== 'undefined') ? global : ((typeof window !== 'undefined') ? window : this);
  84466. globalObject["BABYLON"] = f;
  84467. if(typeof exports === 'object' && typeof module === 'object')
  84468. module.exports = f;
  84469. else if(typeof define === 'function' && define.amd)
  84470. define(["BABYLON"], factory);
  84471. else if(typeof exports === 'object')
  84472. exports["BABYLON"] = f;
  84473. else {
  84474. root["BABYLON"] = f;
  84475. }
  84476. })(this, function() {
  84477. return BABYLON;
  84478. });